diff options
Diffstat (limited to 'src/library/scala/util')
11 files changed, 250 insertions, 239 deletions
diff --git a/src/library/scala/util/automata/BaseBerrySethi.scala b/src/library/scala/util/automata/BaseBerrySethi.scala index 51e15f0e71..18f36f9496 100644 --- a/src/library/scala/util/automata/BaseBerrySethi.scala +++ b/src/library/scala/util/automata/BaseBerrySethi.scala @@ -6,8 +6,6 @@ ** |/ ** \* */ - - package scala.util.automata import scala.util.regexp.{ Base } @@ -15,8 +13,9 @@ import scala.collection.{ mutable, immutable } // todo: replace global variable pos with acc -/** This class turns a regular expression over A into a [[scala.util.automata.NondetWorkAutom]] - * over A using the celebrated position automata construction (also called ''Berry-Sethi'' or ''Glushkov''). +/** This class turns a regular expression over `A` into a + * [[scala.util.automata.NondetWordAutom]] over `A` using the celebrated + * position automata construction (also called ''Berry-Sethi'' or ''Glushkov''). */ abstract class BaseBerrySethi { val lang: Base @@ -43,7 +42,7 @@ abstract class BaseBerrySethi { val (l1, l2) = x.rs span (_.isNullable) ((l1 ++ (l2 take 1)) map compFunction).foldLeft(emptySet)(_ ++ _) case Star(t) => compFunction(t) - case _ => throw new IllegalArgumentException("unexpected pattern " + r.getClass()) + case _ => throw new IllegalArgumentException("unexpected pattern " + r.getClass) } /** Computes `first(r)` for the word regexp `r`. */ @@ -89,7 +88,7 @@ abstract class BaseBerrySethi { if (p.isNullable) fol ++ first else first } - case _ => throw new IllegalArgumentException("unexpected pattern: " + r.getClass()) + case _ => throw new IllegalArgumentException("unexpected pattern: " + r.getClass) } /** Returns the "Sethi-length" of a pattern, creating the set of position along the way. @@ -98,10 +97,10 @@ abstract class BaseBerrySethi { */ protected def traverse(r: RegExp): Unit = r match { // (is tree automaton stuff, more than Berry-Sethi) - case x: Alt => x.rs foreach traverse - case x: Sequ => x.rs foreach traverse - case x: Meta => traverse(x.r) - case Star(t) => traverse(t) - case _ => throw new IllegalArgumentException("unexp pattern " + r.getClass()) + case x: Alt => x.rs foreach traverse + case x: Sequ => x.rs foreach traverse + case x: Meta => traverse(x.r) + case Star(t) => traverse(t) + case _ => throw new IllegalArgumentException("unexp pattern " + r.getClass) } } diff --git a/src/library/scala/util/control/Breaks.scala b/src/library/scala/util/control/Breaks.scala index 80df8cc0bd..9b1abefe00 100644 --- a/src/library/scala/util/control/Breaks.scala +++ b/src/library/scala/util/control/Breaks.scala @@ -6,31 +6,28 @@ ** |/ ** \* */ - - package scala.util.control /** A class that can be instantiated for the break control abstraction. * Example usage: - * - * <pre> + * {{{ * val mybreaks = new Breaks - * import</b> mybreaks.{break, breakable} + * import mybreaks.{break, breakable} * * breakable { - * <b>for</b> (...) { - * <b>if</b> (...) break + * for (...) { + * if (...) break * } - * }</pre> - * + * } + * }}} * Calls to break from one instantiation of `Breaks` will never - * target breakable objects of some other instantion. + * target breakable objects of some other instantiation. */ class Breaks { private val breakException = new BreakControl - /** A block from which one can exit with a `break`'. */ + /** A block from which one can exit with a `break`. */ def breakable(op: => Unit) { try { op @@ -54,26 +51,25 @@ class Breaks { } } - /* Break from dynamically closest enclosing breakable block. + /** Break from dynamically closest enclosing breakable block. * - * @note This might be different than the statically closest enclosing block! + * @note This might be different than the statically closest enclosing block! */ def break() { throw breakException } } /** An object that can be used for the break control abstraction. - * Example usage:<pre> - * - * <b>import</b> Breaks.{break, breakable} + * Example usage: + * {{{ + * import Breaks.{break, breakable} * * breakable { - * <b>for</b> (...) { - * <b>if</b> (...) break + * for (...) { + * if (...) break * } - * }</pre> - * + * } + * }}} */ object Breaks extends Breaks private class BreakControl extends ControlThrowable - diff --git a/src/library/scala/util/control/ControlThrowable.scala b/src/library/scala/util/control/ControlThrowable.scala index 4d1116ba6f..8cbe3064ef 100644 --- a/src/library/scala/util/control/ControlThrowable.scala +++ b/src/library/scala/util/control/ControlThrowable.scala @@ -6,32 +6,28 @@ ** |/ ** \* */ - package scala.util.control -/** - * A marker trait indicating that the `Throwable` it is mixed - * into is intended for flow control. - * - * Note that `Throwable` subclasses which extend this trait - * may extend any other `Throwable` subclass (eg. - * `RuntimeException`) and are not required to extend - * `Throwable` directly. +/** A marker trait indicating that the `Throwable` it is mixed into is + * intended for flow control. * - * Instances of `Throwable` subclasses marked in this way should - * not normally be caught. Where catch-all behaviour is required - * `ControlThrowable`s should be propagated, for example: + * Note that `Throwable` subclasses which extend this trait may extend any + * other `Throwable` subclass (eg. `RuntimeException`) and are not required + * to extend `Throwable` directly. * - * <pre> + * Instances of `Throwable` subclasses marked in this way should not normally + * be caught. Where catch-all behaviour is required `ControlThrowable` + * should be propagated, for example: + * {{{ * import scala.util.control.ControlThrowable * * try { * // Body might throw arbitrarily - * } catch { - * case ce : ControlThrowable => throw ce // propagate - * case t : Exception => log(t) // log and suppress - * </pre> + * } catch { + * case ce : ControlThrowable => throw ce // propagate + * case t : Exception => log(t) // log and suppress + * }}} * - * @author Miles Sabin + * @author Miles Sabin */ trait ControlThrowable extends Throwable with NoStackTrace diff --git a/src/library/scala/util/control/Exception.scala b/src/library/scala/util/control/Exception.scala index ad90b222c2..c8470d2504 100644 --- a/src/library/scala/util/control/Exception.scala +++ b/src/library/scala/util/control/Exception.scala @@ -1,3 +1,11 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + package scala.util.control import collection.immutable.List @@ -5,17 +13,14 @@ import java.lang.reflect.InvocationTargetException /** Classes representing the components of exception handling. * Each class is independently composable. Some example usages: + * {{{ + * import scala.util.control.Exception._ + * import java.net._ * - * - * - * <pre> - * <b>import</b> scala.util.control.Exception._ - * <b>import</b> java.net._ - * - * <b>val</b> s = "http://www.scala-lang.org/" - * <b>val</b> x1 = catching(classOf[MalformedURLException]) opt new URL(s) - * <b>val</b> x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s) - * </pre> + * val s = "http://www.scala-lang.org/" + * val x1 = catching(classOf[MalformedURLException]) opt new URL(s) + * val x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s) + * }}} * * @author Paul Phillips */ @@ -31,6 +36,7 @@ object Exception { def isDefinedAt(x: Throwable) = downcast(x) exists isDef def apply(x: Throwable): T = f(downcast(x).get) } + def mkThrowableCatcher[T](isDef: Throwable => Boolean, f: Throwable => T) = mkCatcher(isDef, f) implicit def throwableSubtypeToCatcher[Ex <: Throwable: ClassManifest, T](pf: PartialFunction[Ex, T]) = @@ -62,7 +68,7 @@ object Exception { protected val name = "Finally" def and(other: => Unit): Finally = new Finally({ body ; other }) - def invoke(): Unit = { body } + def invoke() { body } } /** A container class for catch/finally logic. @@ -92,14 +98,14 @@ object Exception { } finally fin map (_.invoke()) - /* Create an empty Try container with this Catch and the supplied Finally */ + /* Create an empty Try container with this Catch and the supplied `Finally`. */ def andFinally(body: => Unit): Catch[T] = fin match { case None => new Catch(pf, Some(new Finally(body)), rethrow) case Some(f) => new Catch(pf, Some(f and body), rethrow) } /** Apply this catch logic to the supplied body, mapping the result - * into Option[T] - None if any exception was caught, Some(T) otherwise. + * into `Option[T]` - `None` if any exception was caught, `Some(T)` otherwise. */ def opt[U >: T](body: => U): Option[U] = toOption(Some(body)) @@ -109,8 +115,8 @@ object Exception { */ def either[U >: T](body: => U): Either[Throwable, U] = toEither(Right(body)) - /** Create a new Catch with the same isDefinedAt logic as this one, - * but with the supplied apply method replacing the current one. */ + /** Create a `Catch` object with the same `isDefinedAt` logic as this one, + * but with the supplied `apply` method replacing the current one. */ def withApply[U](f: Throwable => U): Catch[U] = { val pf2 = new Catcher[U] { def isDefinedAt(x: Throwable) = pf isDefinedAt x @@ -130,21 +136,21 @@ object Exception { def apply(): T = catcher(body) def apply[U >: T](other: => U): U = catcher(other) - /** As apply, but map caught exceptions to None and success to Some(T) */ + /** As apply, but map caught exceptions to `None` and success to `Some(T)`. */ def opt(): Option[T] = catcher opt body def opt[U >: T](other: => U): Option[U] = catcher opt other - /** As apply, but map caught exceptions to Left(ex) and success to Right(x) */ + /** As apply, but map caught exceptions to `Left(ex)` and success to Right(x) */ def either(): Either[Throwable, T] = catcher either body def either[U >: T](other: => U): Either[Throwable, U] = catcher either other - /** Create a new Try with the supplied body replacing the current body */ + /** Create a `Try` object with the supplied body replacing the current body. */ def tryInstead[U >: T](other: => U) = new Try(other, catcher) - /** Create a new Try with the supplied logic appended to the existing Catch logic. */ + /** Create a `Try` object with the supplied logic appended to the existing Catch logic. */ def or[U >: T](pf: Catcher[U]) = new Try(body, catcher or pf) - /** Create a new Try with the supplied code appended to the existing Finally. */ + /** Create a `Try`object with the supplied code appended to the existing `Finally`. */ def andFinally(fin: => Unit) = new Try(body, catcher andFinally fin) override def toString() = List("Try(<body>)", catcher.toString) mkString " " @@ -153,49 +159,51 @@ object Exception { final val nothingCatcher: Catcher[Nothing] = mkThrowableCatcher(_ => false, throw _) final def allCatcher[T]: Catcher[T] = mkThrowableCatcher(_ => true, throw _) - /** The empty Catch object. */ + /** The empty `Catch` object. */ final val noCatch: Catch[Nothing] = new Catch(nothingCatcher) withDesc "<nothing>" - /** A Catch object which catches everything. */ + /** A `Catch` object which catches everything. */ final def allCatch[T]: Catch[T] = new Catch(allCatcher[T]) withDesc "<everything>" - /** Creates a Catch object which will catch any of the supplied exceptions. - * Since the returned Catch object has no specific logic defined and will simply - * rethrow the exceptions it catches, you will typically want to call "opt" or - * "either" on the return value, or assign custom logic by calling "withApply". + /** Creates a `Catch` object which will catch any of the supplied exceptions. + * Since the returned `Catch` object has no specific logic defined and will simply + * rethrow the exceptions it catches, you will typically want to call `opt` or + * `either` on the return value, or assign custom logic by calling "withApply". * - * Note that Catch objects automatically rethrow ControlExceptions and others + * Note that `Catch` objects automatically rethrow `ControlExceptions` and others * which should only be caught in exceptional circumstances. If you really want - * to catch exactly what you specify, use "catchingPromiscuously" instead. + * to catch exactly what you specify, use `catchingPromiscuously` instead. */ def catching[T](exceptions: Class[_]*): Catch[T] = new Catch(pfFromExceptions(exceptions : _*)) withDesc (exceptions map (_.getName) mkString ", ") def catching[T](c: Catcher[T]): Catch[T] = new Catch(c) - /** Creates a Catch object which will catch any of the supplied exceptions. + /** Creates a `Catch` object which will catch any of the supplied exceptions. * Unlike "catching" which filters out those in shouldRethrow, this one will - * catch whatever you ask of it: ControlThrowable, InterruptedException, - * OutOfMemoryError, you name it. + * catch whatever you ask of it: `ControlThrowable`, `InterruptedException`, + * `OutOfMemoryError`, you name it. */ def catchingPromiscuously[T](exceptions: Class[_]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions : _*)) def catchingPromiscuously[T](c: Catcher[T]): Catch[T] = new Catch(c, None, _ => false) - /** Creates a Catch object which catches and ignores any of the supplied exceptions. */ + /** Creates a `Catch` object which catches and ignores any of the supplied exceptions. */ def ignoring(exceptions: Class[_]*): Catch[Unit] = catching(exceptions: _*) withApply (_ => ()) - /** Creates a Catch object which maps all the supplied exceptions to 'None'. */ + /** Creates a `Catch` object which maps all the supplied exceptions to `None`. */ def failing[T](exceptions: Class[_]*): Catch[Option[T]] = catching(exceptions: _*) withApply (_ => None) - /** Creates a Catch object which maps all the supplied exceptions to the given value. */ + /** Creates a `Catch` object which maps all the supplied exceptions to the given value. */ def failAsValue[T](exceptions: Class[_]*)(value: => T): Catch[T] = catching(exceptions: _*) withApply (_ => value) - /** Returns a partially constructed Catch object, which you must give - * an exception handler function as an argument to "by". Example: - * handling(ex1, ex2) by (_.printStackTrace) + /** Returns a partially constructed `Catch` object, which you must give + * an exception handler function as an argument to `by`. Example: + * {{{ + * handling(ex1, ex2) by (_.printStackTrace) + * }}} */ class By[T,R](f: T => R) { def by(x: T): R = f(x) @@ -205,10 +213,10 @@ object Exception { new By[Throwable => T, Catch[T]](fun _) } - /** Returns a Catch object with no catch logic and the argument as Finally. */ + /** Returns a `Catch` object with no catch logic and the argument as `Finally`. */ def ultimately[T](body: => Unit): Catch[T] = noCatch andFinally body - /** Creates a Catch object which unwraps any of the supplied exceptions. */ + /** Creates a `Catch` object which unwraps any of the supplied exceptions. */ def unwrapping[T](exceptions: Class[_]*): Catch[T] = { def unwrap(x: Throwable): Throwable = if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause) diff --git a/src/library/scala/util/control/TailCalls.scala b/src/library/scala/util/control/TailCalls.scala index 59e9618028..ca5442046c 100644 --- a/src/library/scala/util/control/TailCalls.scala +++ b/src/library/scala/util/control/TailCalls.scala @@ -1,10 +1,18 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + package scala.util.control /** Methods exported by this object implement tail calls via trampolining. - * Tail calling methods have to return their result using `done` or call the next - * method using `tailcall`. Both return a `TailRec` object. The result of evaluating - * a tailcalling function can be retrieved from a `Tailrec` value using method result`. - * Here's a usage example: + * Tail calling methods have to return their result using `done` or call the + * next method using `tailcall`. Both return a `TailRec` object. The result + * of evaluating a tailcalling function can be retrieved from a `Tailrec` + * value using method `result`. Here's a usage example: * {{{ * import scala.util.control.TailCalls._ * @@ -19,10 +27,10 @@ package scala.util.control */ object TailCalls { - /** This class represents a tailcalling computation. + /** This class represents a tailcalling computation */ abstract class TailRec[+A] { - /** Returns the result of the tailcalling computation + /** Returns the result of the tailcalling computation. */ def result: A = { def loop(body: TailRec[A]): A = body match { @@ -36,7 +44,8 @@ object TailCalls { /** Internal class representing a tailcall */ protected case class Call[A](rest: () => TailRec[A]) extends TailRec[A] - /** Internal class representing the final result return from a tailcalling computation */ + /** Internal class representing the final result returned from a tailcalling + * computation */ protected case class Done[A](override val result: A) extends TailRec[A] /** Performs a tailcall @@ -47,10 +56,9 @@ object TailCalls { /** Used to return final result from tailcalling computation * @param `result` the result value - * @return a `TailRec` object representing a computation which immediately returns `result` + * @return a `TailRec` object representing a computation which immediately + * returns `result` */ def done[A](result: A): TailRec[A] = new Done(result) } - - diff --git a/src/library/scala/util/parsing/combinator/PackratParsers.scala b/src/library/scala/util/parsing/combinator/PackratParsers.scala index 3f09ae506d..ea856efc3a 100644 --- a/src/library/scala/util/parsing/combinator/PackratParsers.scala +++ b/src/library/scala/util/parsing/combinator/PackratParsers.scala @@ -6,7 +6,6 @@ ** |/ ** \* */ - package scala.util.parsing.combinator import scala.util.parsing.combinator._ @@ -14,29 +13,34 @@ import scala.util.parsing.input.{ Reader, Position } import scala.collection.mutable /** - * `PackratParsers` is a component that extends the parser combinators provided by - * [[scala.util.parsing.combinator.Parsers]] with a memoization facility (``Packrat Parsing''). + * `PackratParsers` is a component that extends the parser combinators + * provided by [[scala.util.parsing.combinator.Parsers]] with a memoization + * facility (''Packrat Parsing''). * - * Packrat Parsing is a technique for implementing backtracking, recursive-descent parsers, with the - * advantage that it guarantees unlimited lookahead and a linear parse time. Using this technique, + * Packrat Parsing is a technique for implementing backtracking, + * recursive-descent parsers, with the advantage that it guarantees + * unlimited lookahead and a linear parse time. Using this technique, * left recursive grammars can also be accepted. * * Using `PackratParsers` is very similar to using `Parsers`: - * - any class/trait that extends `Parsers` (directly or through a subclass) can mix in `PackratParsers`. - * Example: `object MyGrammar extends StandardTokenParsers with PackratParsers ` - * - each grammar production previously declared as a `def` without formal parameters - * becomes a `lazy val`, and its type is changed from `Parser[Elem]` to `PackratParser[Elem]`. - * So, for example, `def production: Parser[Int] = {...}` - * becomes `lazy val production: PackratParser[Int] = {...}` - * - Important: using `PackratParser`s is not an ``all or nothing'' decision. + * - any class/trait that extends `Parsers` (directly or through a subclass) + * can mix in `PackratParsers`. + * Example: `'''object''' MyGrammar '''extends''' StandardTokenParsers '''with''' PackratParsers` + * - each grammar production previously declared as a `def` without formal + * parameters becomes a `lazy val`, and its type is changed from + * `Parser[Elem]` to `PackratParser[Elem]`. + * So, for example, `'''def''' production: Parser[Int] = {...}` + * becomes `'''lazy val''' production: PackratParser[Int] = {...}` + * - Important: using `PackratParser`s is not an ''all or nothing'' decision. * They can be free mixed with regular `Parser`s in a single grammar. * * Cached parse results are attached to the ''input'', not the grammar. * Therefore, `PackratsParser`s require a `PackratReader` as input, which - * adds memoization to an underlying `Reader`. Programmers can create `PackratReader` - * objects either manually, as in `production(new PackratReader(new lexical.Scanner("input")))`, - * but the common way should be to rely on the combinator `phrase` to wrap a given - * input with a `PackratReader` if the input is not one itself. + * adds memoization to an underlying `Reader`. Programmers can create + * `PackratReader` objects either manually, as in + * `production('''new''' PackratReader('''new''' lexical.Scanner("input")))`, + * but the common way should be to rely on the combinator `phrase` to wrap + * a given input with a `PackratReader` if the input is not one itself. * * @see Bryan Ford: "Packrat Parsing: Simple, Powerful, Lazy, Linear Time." ICFP'02 * @see Alessandro Warth, James R. Douglass, Todd Millstein: "Packrat Parsers Can Support Left Recursion." PEPM'08 @@ -54,7 +58,7 @@ trait PackratParsers extends Parsers { * A specialized `Reader` class that wraps an underlying `Reader` * and provides memoization of parse results. */ - class PackratReader[+T](underlying: Reader[T]) extends Reader[T] { outer => + class PackratReader[+T](underlying: Reader[T]) extends Reader[T] { outer => /* * caching of intermediate parse results and information about recursion @@ -91,7 +95,6 @@ trait PackratParsers extends Parsers { def atEnd: Boolean = underlying.atEnd } - /** * A parser generator delimiting whole phrases (i.e. programs). * @@ -108,7 +111,6 @@ trait PackratParsers extends Parsers { } } - private def getPosFromResult(r: ParseResult[_]): Position = r.next.pos // auxiliary data structures @@ -136,14 +138,14 @@ trait PackratParsers extends Parsers { /** * Implicitly convert a parser to a packrat parser. * The conversion is triggered by giving the appropriate target type: - * val myParser: PackratParser[MyResult] = aParser - */ + * {{{ + * val myParser: PackratParser[MyResult] = aParser + * }}} */ implicit def parser2packrat[T](p: => super.Parser[T]): PackratParser[T] = { lazy val q = p memo(super.Parser {in => q(in)}) } - /* * An unspecified function that is called when a packrat reader is applied. * It verifies whether we are in the process of growing a parse or not. diff --git a/src/library/scala/util/parsing/combinator/Parsers.scala b/src/library/scala/util/parsing/combinator/Parsers.scala index e9155afc55..bb73b28ea8 100644 --- a/src/library/scala/util/parsing/combinator/Parsers.scala +++ b/src/library/scala/util/parsing/combinator/Parsers.scala @@ -23,7 +23,8 @@ import annotation.migration * * There are two aspects to the result of a parser: * 1. success or failure - * 2. the result. + * 1. the result. + * * A `Parser[T]` provides both kinds of information. * * The term ''parser combinator'' refers to the fact that these parsers @@ -44,18 +45,20 @@ import annotation.migration * @author Adriaan Moors */ trait Parsers { - /** the type of input elements the provided parsers consume (When consuming invidual characters, a parser is typically - * called a ''scanner'', which produces ''tokens'' that are consumed by what is normally called a ''parser''. + /** the type of input elements the provided parsers consume (When consuming + * invidual characters, a parser is typically called a ''scanner'', which + * produces ''tokens'' that are consumed by what is normally called a ''parser''. * Nonetheless, the same principles apply, regardless of the input type.) */ type Elem - /** The parser input is an abstract reader of input elements, i.e. the type of input the parsers in this component - * expect. */ + /** The parser input is an abstract reader of input elements, i.e. the type + * of input the parsers in this component expect. */ type Input = Reader[Elem] - /** A base class for parser results. A result is either successful or not (failure may be fatal, i.e., an Error, or - * not, i.e., a Failure). On success, provides a result of type `T` which consists of some result (and the rest of - * the input). */ + /** A base class for parser results. A result is either successful or not + * (failure may be fatal, i.e., an Error, or not, i.e., a Failure). On + * success, provides a result of type `T` which consists of some result + * (and the rest of the input). */ sealed abstract class ParseResult[+T] { /** Functional composition of ParseResults. * @@ -91,7 +94,7 @@ trait Parsers { val successful: Boolean } - /** The success case of ParseResult: contains the result and the remaining input. + /** The success case of `ParseResult`: contains the result and the remaining input. * * @param result The parser's output * @param next The parser's remaining input @@ -131,7 +134,7 @@ trait Parsers { def get: Nothing = sys.error("No result when parsing failed") } - /** An extractor so NoSuccess(msg, next) can be used in matches. */ + /** An extractor so `NoSuccess(msg, next)` can be used in matches. */ object NoSuccess { def unapply[T](x: ParseResult[T]) = x match { case Failure(msg, next) => Some(msg, next) @@ -140,7 +143,7 @@ trait Parsers { } } - /** The failure case of ParseResult: contains an error-message and the remaining input. + /** The failure case of `ParseResult`: contains an error-message and the remaining input. * Parsing will back-track when a failure occurs. * * @param msg An error message string describing the failure. @@ -156,8 +159,9 @@ trait Parsers { }} } - /** The fatal failure case of ParseResult: contains an error-message and the remaining input. - * No back-tracking is done when a parser returns an `Error` + /** The fatal failure case of ParseResult: contains an error-message and + * the remaining input. + * No back-tracking is done when a parser returns an `Error`. * * @param msg An error message string describing the error. * @param next The parser's unconsumed input at the point where the error occurred. @@ -168,7 +172,6 @@ trait Parsers { def append[U >: Nothing](a: => ParseResult[U]): ParseResult[U] = this } - def Parser[T](f: Input => ParseResult[T]): Parser[T] = new Parser[T]{ def apply(in: Input) = f(in) } @@ -199,7 +202,6 @@ trait Parsers { Parser{ in => this(in) append p(in)} } - // the operator formerly known as +++, ++, &, but now, behold the venerable ~ // it's short, light (looks like whitespace), has few overloaded meaning (thanks to the recent change from ~ to unary_~) // and we love it! (or do we like `,` better?) @@ -313,7 +315,6 @@ trait Parsers { */ def ^^ [U](f: T => U): Parser[U] = map(f).named(toString+"^^") - /** A parser combinator that changes a successful result into the specified value. * * `p ^^^ v` succeeds if `p` succeeds; discards its result, and returns `v` instead. @@ -355,7 +356,6 @@ trait Parsers { */ def ^? [U](f: PartialFunction[T, U]): Parser[U] = ^?(f, r => "Constructor function not defined at "+r) - /** A parser combinator that parameterizes a subsequent parser with the result of this one. * * Use this combinator when a parser depends on the result of a previous parser. `p` should be @@ -376,15 +376,15 @@ trait Parsers { /** Returns `into(fq)`. */ def >>[U](fq: T => Parser[U])=into(fq) - /** Returns a parser that repeatedly parses what this parser parses. * * @return rep(this) */ def * = rep(this) - /** Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep` parser. - * The `sep` parser specifies how the results parsed by this parser should be combined. + /** Returns a parser that repeatedly parses what this parser parses, + * interleaved with the `sep` parser. The `sep` parser specifies how + * the results parsed by this parser should be combined. * * @return chainl1(this, sep) */ @@ -405,8 +405,9 @@ trait Parsers { def ? = opt(this) } - /** Wrap a parser so that its failures become errors (the `|` combinator will give up as soon as - * it encounters an error, on failure it simply tries the next alternative). + /** Wrap a parser so that its failures become errors (the `|` combinator + * will give up as soon as it encounters an error, on failure it simply + * tries the next alternative). */ def commit[T](p: => Parser[T]) = Parser{ in => p(in) match{ @@ -420,7 +421,6 @@ trait Parsers { case class EFCons(hd: Elem => ElemFun, tl: ElemFun) extends ElemFun case class EFNil(res: Boolean) extends ElemFun*/ - /** A parser matching input elements that satisfy a given predicate. * * `elem(kind, p)` succeeds if the input starts with an element `e` for which `p(e)` is true. @@ -463,8 +463,8 @@ trait Parsers { /** The parser that matches an element in the domain of the partial function `f`. * - * If `f` is defined on the first element in the input, `f` is applied to it to produce - * this parser's result. + * If `f` is defined on the first element in the input, `f` is applied + * to it to produce this parser's result. * * Example: The parser `accept("name", {case Identifier(n) => Name(n)})` * accepts an `Identifier(n)` and returns a `Name(n)` @@ -476,7 +476,6 @@ trait Parsers { */ def accept[U](expected: String, f: PartialFunction[Elem, U]): Parser[U] = acceptMatch(expected, f) - def acceptIf(p: Elem => Boolean)(err: Elem => String): Parser[Elem] = Parser { in => if (p(in.first)) Success(in.first, in.rest) else Failure(err(in.first), in) @@ -487,7 +486,8 @@ trait Parsers { else Failure(expected+" expected", in) } - def acceptSeq[ES <% Iterable[Elem]](es: ES): Parser[List[Elem]] = es.foldRight[Parser[List[Elem]]](success(Nil)){(x, pxs) => accept(x) ~ pxs ^^ mkList} + def acceptSeq[ES <% Iterable[Elem]](es: ES): Parser[List[Elem]] = + es.foldRight[Parser[List[Elem]]](success(Nil)){(x, pxs) => accept(x) ~ pxs ^^ mkList} /** A parser that always fails. * @@ -503,7 +503,6 @@ trait Parsers { */ def err(msg: String) = Parser{ in => Error(msg, in) } - /** A parser that always succeeds. * * @param v The result for the parser @@ -520,8 +519,8 @@ trait Parsers { /** A parser generator for repetitions. * - * `rep(p)` repeatedly uses `p` to parse the input until `p` fails (the result is a List - * of the consecutive results of `p`). + * `rep(p)` repeatedly uses `p` to parse the input until `p` fails + * (the result is a List of the consecutive results of `p`). * * @param p a `Parser` that is to be applied successively to the input * @return A parser that returns a list of results produced by repeatedly applying `p` to the input. @@ -604,8 +603,8 @@ trait Parsers { @tailrec def applyp(in0: Input): ParseResult[List[T]] = if (elems.length == num) Success(elems.toList, in0) else p0(in0) match { - case Success(x, rest) => elems += x ; applyp(rest) - case ns: NoSuccess => return ns + case Success(x, rest) => elems += x ; applyp(rest) + case ns: NoSuccess => return ns } applyp(in) @@ -613,8 +612,8 @@ trait Parsers { /** A parser generator for non-empty repetitions. * - * `rep1sep(p, q)` repeatedly applies `p` interleaved with `q` to parse the input, until `p` fails. - * The parser `p` must succeed at least once. + * `rep1sep(p, q)` repeatedly applies `p` interleaved with `q` to parse the + * input, until `p` fails. The parser `p` must succeed at least once. * * @param p a `Parser` that is to be applied successively to the input * @param q a `Parser` that parses the elements that separate the elements parsed by `p` @@ -626,8 +625,9 @@ trait Parsers { def rep1sep[T](p : => Parser[T], q : => Parser[Any]): Parser[List[T]] = p ~ rep(q ~> p) ^^ {case x~y => x::y} - /** A parser generator that, roughly, generalises the rep1sep generator so that `q`, which parses the separator, - * produces a left-associative function that combines the elements it separates. + /** A parser generator that, roughly, generalises the rep1sep generator so + * that `q`, which parses the separator, produces a left-associative + * function that combines the elements it separates. * * ''From: J. Fokker. Functional parsers. In J. Jeuring and E. Meijer, editors, Advanced Functional Programming, * volume 925 of Lecture Notes in Computer Science, pages 1--23. Springer, 1995.'' @@ -639,22 +639,25 @@ trait Parsers { def chainl1[T](p: => Parser[T], q: => Parser[(T, T) => T]): Parser[T] = chainl1(p, p, q) - /** A parser generator that, roughly, generalises the `rep1sep` generator so that `q`, which parses the separator, - * produces a left-associative function that combines the elements it separates. + /** A parser generator that, roughly, generalises the `rep1sep` generator + * so that `q`, which parses the separator, produces a left-associative + * function that combines the elements it separates. * * @param first a parser that parses the first element * @param p a parser that parses the subsequent elements - * @param q a parser that parses the token(s) separating the elements, yielding a left-associative function that - * combines two elements into one + * @param q a parser that parses the token(s) separating the elements, + * yielding a left-associative function that combines two elements + * into one */ def chainl1[T, U](first: => Parser[T], p: => Parser[U], q: => Parser[(T, U) => T]): Parser[T] = first ~ rep(q ~ p) ^^ { case x ~ xs => xs.foldLeft(x){(_, _) match {case (a, f ~ b) => f(a, b)}} } - /** A parser generator that generalises the `rep1sep` generator so that `q`, which parses the separator, - * produces a right-associative function that combines the elements it separates. Additionally, - * The right-most (last) element and the left-most combining function have to be supplied. + /** A parser generator that generalises the `rep1sep` generator so that `q`, + * which parses the separator, produces a right-associative function that + * combines the elements it separates. Additionally, the right-most (last) + * element and the left-most combining function have to be supplied. * * rep1sep(p: Parser[T], q) corresponds to chainr1(p, q ^^ cons, cons, Nil) (where val cons = (x: T, y: List[T]) => x :: y) * @@ -681,7 +684,8 @@ trait Parsers { def opt[T](p: => Parser[T]): Parser[Option[T]] = p ^^ (x => Some(x)) | success(None) - /** Wrap a parser so that its failures and errors become success and vice versa -- it never consumes any input. + /** Wrap a parser so that its failures and errors become success and + * vice versa -- it never consumes any input. */ def not[T](p: => Parser[T]): Parser[Unit] = Parser { in => p(in) match { @@ -690,11 +694,13 @@ trait Parsers { } } - /** A parser generator for guard expressions. The resulting parser will fail or succeed - * just like the one given as parameter but it will not consume any input. + /** A parser generator for guard expressions. The resulting parser will + * fail or succeed just like the one given as parameter but it will not + * consume any input. * * @param p a `Parser` that is to be applied to the input - * @return A parser that returns success if and only if `p` succeeds but never consumes any input + * @return A parser that returns success if and only if `p` succeeds but + * never consumes any input */ def guard[T](p: => Parser[T]): Parser[T] = Parser { in => p(in) match{ @@ -703,12 +709,13 @@ trait Parsers { } } - - /** `positioned` decorates a parser's result with the start position of the input it consumed. + /** `positioned` decorates a parser's result with the start position of the + * input it consumed. * * @param p a `Parser` whose result conforms to `Positional`. - * @return A parser that has the same behaviour as `p`, but which marks its result with the - * start position of the input it consumed, if it didn't already have a position. + * @return A parser that has the same behaviour as `p`, but which marks its + * result with the start position of the input it consumed, + * if it didn't already have a position. */ def positioned[T <: Positional](p: => Parser[T]): Parser[T] = Parser { in => p(in) match { diff --git a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala index 6c8bad01c1..3ac5c07dc4 100644 --- a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala +++ b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala @@ -6,8 +6,6 @@ ** |/ ** \* */ - - package scala.util.parsing package combinator package lexical @@ -16,16 +14,19 @@ import token._ import input.CharArrayReader.EofCh import scala.collection.mutable -/** This component provides a standard lexical parser for a simple, Scala-like language. - * It parses keywords and identifiers, numeric literals (integers), strings, and delimiters. +/** This component provides a standard lexical parser for a simple, + * [[http://scala-lang.org Scala]]-like language. It parses keywords and + * identifiers, numeric literals (integers), strings, and delimiters. * - * To distinguish between identifiers and keywords, it uses a set of reserved identifiers: - * every string contained in `reserved` is returned as a keyword token. - * (Note that "=>" is hard-coded as a keyword.) - * Additionally, the kinds of delimiters can be specified by the `delimiters` set. + * To distinguish between identifiers and keywords, it uses a set of + * reserved identifiers: every string contained in `reserved` is returned + * as a keyword token. (Note that `=>` is hard-coded as a keyword.) + * Additionally, the kinds of delimiters can be specified by the + * `delimiters` set. * - * Usually this component is used to break character-based input into bigger tokens, - * which are then passed to a token-parser {@see TokenParsers}. + * Usually this component is used to break character-based input into + * bigger tokens, which are then passed to a token-parser {@see + * [[scala.util.parsing.combinator.syntactical.TokenParsers]]}. * * @author Martin Odersky * @author Iulian Dragos diff --git a/src/library/scala/util/parsing/combinator/testing/Tester.scala b/src/library/scala/util/parsing/combinator/testing/Tester.scala index ca1df2f6d4..4607dc8843 100644 --- a/src/library/scala/util/parsing/combinator/testing/Tester.scala +++ b/src/library/scala/util/parsing/combinator/testing/Tester.scala @@ -6,7 +6,6 @@ ** |/ ** \* */ - package scala.util.parsing.combinator.testing import scala.util.parsing.combinator._ @@ -16,15 +15,13 @@ import scala.util.parsing.combinator.syntactical.TokenParsers /** Facilitates testing a given parser on various input strings. * * Example use: - * - * <pre> - * <b>val</b> syntactic = <b>new</b> MyParsers - * </pre> + * {{{ + * val syntactic = new MyParsers + * }}} * and - * <pre> - * <b>val</b> parser = syntactic.term - * </pre> - * + * {{{ + * val parser = syntactic.term + * }}} * (If `MyParsers` extends [[scala.util.parsing.combinator.syntactical.TokenParsers]] * with a parser called `term`.) * @@ -36,10 +33,9 @@ abstract class Tester { val syntactic: TokenParsers { val lexical: Lexical } val parser: syntactic.Parser[Any] - - /** Scans a String (using a `syntactic.lexical.Scanner`), parses it - * using `phrase(parser)`, and prints the input and the - * parsed result to the console. + /** Scans a String (using a `syntactic.lexical.Scanner`), parses it using + * `phrase(parser)`, and prints the input and the parsed result to the + * console. */ def test(in: String) { Console.println("\nin : "+in) diff --git a/src/library/scala/util/parsing/json/JSON.scala b/src/library/scala/util/parsing/json/JSON.scala index 036964680e..b0926d20e7 100644 --- a/src/library/scala/util/parsing/json/JSON.scala +++ b/src/library/scala/util/parsing/json/JSON.scala @@ -6,21 +6,19 @@ ** |/ ** \* */ - - package scala.util.parsing.json import scala.util.parsing.combinator._ import scala.util.parsing.combinator.syntactical._ import scala.util.parsing.combinator.lexical._ /** - * This object provides a simple interface to the JSON parser class. The default conversion - * for numerics is into a double. If you wish to override this behavior at the global level, - * you can set the globalNumberParser property to your own (String => Any) function. If you only - * want to override at the per-thread level then you can set the perThreadNumberParser property to your - * function. For example: - * - * <pre> + * This object provides a simple interface to the JSON parser class. + * The default conversion for numerics is into a double. If you wish to + * override this behavior at the global level, you can set the + * `globalNumberParser` property to your own `(String => Any)` function. + * If you only want to override at the per-thread level then you can set + * the `perThreadNumberParser` property to your function. For example: + * {{{ * val myConversionFunc = {input : String => BigDecimal(input)} * * // Global override @@ -28,18 +26,18 @@ import scala.util.parsing.combinator.lexical._ * * // Per-thread override * JSON.perThreadNumberParser = myConversionFunc - * </pre> + * }}} * - * @author Derek Chen-Becker <"java"+@+"chen-becker"+"."+"org"> + * @author Derek Chen-Becker <"java"+@+"chen-becker"+"."+"org"> */ object JSON extends Parser { /** - * Parse the given JSON string and return a list of elements. If the - * string is a JSON object it will be a list of pairs. If it's a JSON + * Parse the given `JSON` string and return a list of elements. If the + * string is a `JSON` object it will be a list of pairs. If it's a `JSON` * array it will be be a list of individual elements. * - * @param input the given JSON string. + * @param input the given `JSON` string. * @return an optional list of of elements. */ @deprecated("Use parseFull or parseRaw as needed.", "2.8.0") @@ -49,7 +47,7 @@ object JSON extends Parser { }) /** - * This method converts "raw" results back into the original, deprecated + * This method converts ''raw'' results back into the original, deprecated * form. */ private def unRaw (in : Any) : Any = in match { @@ -59,12 +57,12 @@ object JSON extends Parser { } /** - * Parse the given JSON string and return a list of elements. If the - * string is a JSON object it will be a JSONObject. If it's a JSON - * array it will be be a JSONArray. + * Parse the given `JSON` string and return a list of elements. If the + * string is a `JSON` object it will be a `JSONObject`. If it's a `JSON` + * array it will be be a `JSONArray`. * - * @param input the given JSON string. - * @return an optional JSONType element. + * @param input the given `JSON` string. + * @return an optional `JSONType` element. */ def parseRaw(input : String) : Option[JSONType] = phrase(root)(new lexical.Scanner(input)) match { @@ -73,11 +71,11 @@ object JSON extends Parser { } /** - * Parse the given JSON string and return either a <code>List[Any]</code> - * if the JSON string specifies an <code>Array</code>, or a - * <code>Map[String,Any]</code> if the JSON string specifies an object. + * Parse the given `JSON` string and return either a `List[Any]` + * if the `JSON` string specifies an `Array`, or a + * `Map[String,Any]` if the `JSON` string specifies an object. * - * @param input the given JSON string. + * @param input the given `JSON` string. * @return an optional list or map. */ def parseFull(input: String): Option[Any] = @@ -87,8 +85,8 @@ object JSON extends Parser { } /** - * A utility method to resolve a parsed JSON list into objects or - * arrays. See the parse method for details. + * A utility method to resolve a parsed `JSON` list into objects or + * arrays. See the `parse` method for details. */ def resolveType(input: Any): Any = input match { case JSONObject(data) => data.transform { @@ -105,8 +103,9 @@ object JSON extends Parser { def globalNumberParser : NumericParser = defaultNumberParser /** - * Defines the function used to convert a numeric string literal into a numeric format on a per-thread - * basis. Use globalNumberParser for a global override + * Defines the function used to convert a numeric string literal into a + * numeric format on a per-thread basis. Use `globalNumberParser` for a + * global override. */ def perThreadNumberParser_=(f : NumericParser) { numberParser.set(f) } def perThreadNumberParser : NumericParser = numberParser.get() diff --git a/src/library/scala/util/regexp/WordExp.scala b/src/library/scala/util/regexp/WordExp.scala index 6a83794ef4..cf146934d1 100644 --- a/src/library/scala/util/regexp/WordExp.scala +++ b/src/library/scala/util/regexp/WordExp.scala @@ -13,27 +13,27 @@ package scala.util.regexp /** * The class `WordExp` provides regular word expressions. * - * Users have to instantiate type member `_regexpT <;: RegExp` (from class `Base`) - * and a type member `_labelT <;: Label`. + * Users have to instantiate type member `_regexpT <;: RegExp` + * (from class `Base`) and a type member `_labelT <;: Label`. * * Here is a short example: - * <pre> - * <b>import</b> scala.util.regexp._ - * <b>import</b> scala.util.automata._ - * <b>object</b> MyLang <b>extends</b> WordExp { - * <b>type</b> _regexpT = RegExp - * <b>type</b> _labelT = MyChar + * {{{ + * import scala.util.regexp._ + * import scala.util.automata._ + * object MyLang extends WordExp { + * type _regexpT = RegExp + * type _labelT = MyChar * - * <b>case class</b> MyChar(c:Char) <b>extends</b> Label + * case class MyChar(c:Char) extends Label * } - * <b>import</b> MyLang._ + * import MyLang._ * // (a* | b)* - * <b>val</b> rex = Star(Alt(Star(Letter(MyChar('a'))),Letter(MyChar('b')))) - * <b>object</b> MyBerriSethi <b>extends</b> WordBerrySethi { - * <b>override val</b> lang = MyLang + * val rex = Star(Alt(Star(Letter(MyChar('a'))),Letter(MyChar('b')))) + * object MyBerriSethi extends WordBerrySethi { + * override val lang = MyLang * } - * <b>val</b> nfa = MyBerriSethi.automatonFrom(Sequ(rex), 1) - * </pre> + * val nfa = MyBerriSethi.automatonFrom(Sequ(rex), 1) + * }}} * * @author Burak Emir * @version 1.0 @@ -55,4 +55,3 @@ abstract class WordExp extends Base { var pos = -1 } } - |