summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorPaul Phillips <paulp@improving.org>2009-06-03 12:31:59 +0000
committerPaul Phillips <paulp@improving.org>2009-06-03 12:31:59 +0000
commite46e603f658ee9cbec4d762928b6645fd7f6b8cd (patch)
tree42da25805c0bdb2f93d09ee0fc43b289728a493f /src
parent7d7b037bd0c52ce4af09f2177c995b4dd3a7fdc6 (diff)
downloadscala-e46e603f658ee9cbec4d762928b6645fd7f6b8cd.tar.gz
scala-e46e603f658ee9cbec4d762928b6645fd7f6b8cd.tar.bz2
scala-e46e603f658ee9cbec4d762928b6645fd7f6b8cd.zip
Another big XML commit.
and using as a testbed for default arguments.
Diffstat (limited to 'src')
-rw-r--r--src/library/scala/xml/Comment.scala26
-rw-r--r--src/library/scala/xml/MetaData.scala53
-rw-r--r--src/library/scala/xml/Node.scala4
-rw-r--r--src/library/scala/xml/NodeBuffer.scala21
-rw-r--r--src/library/scala/xml/NodeSeq.scala33
-rw-r--r--src/library/scala/xml/Null.scala2
-rw-r--r--src/library/scala/xml/PCData.scala7
-rw-r--r--src/library/scala/xml/Parsing.scala38
-rw-r--r--src/library/scala/xml/ProcInstr.scala5
-rw-r--r--src/library/scala/xml/QNode.scala4
-rw-r--r--src/library/scala/xml/SpecialNode.scala5
-rw-r--r--src/library/scala/xml/Text.scala6
-rw-r--r--src/library/scala/xml/Unparsed.scala14
-rw-r--r--src/library/scala/xml/Utility.scala128
-rw-r--r--src/library/scala/xml/XML.scala104
-rw-r--r--src/library/scala/xml/Xhtml.scala69
-rw-r--r--src/library/scala/xml/dtd/Decl.scala3
-rw-r--r--src/library/scala/xml/dtd/DocType.scala26
-rw-r--r--src/library/scala/xml/parsing/ConstructingHandler.scala16
-rw-r--r--src/library/scala/xml/parsing/MarkupHandler.scala4
-rw-r--r--src/library/scala/xml/path/Expression.scala7
-rw-r--r--src/library/scala/xml/transform/BasicTransformer.scala4
22 files changed, 193 insertions, 386 deletions
diff --git a/src/library/scala/xml/Comment.scala b/src/library/scala/xml/Comment.scala
index 2a932b90f8..421b5b4afb 100644
--- a/src/library/scala/xml/Comment.scala
+++ b/src/library/scala/xml/Comment.scala
@@ -16,29 +16,17 @@ package scala.xml
* @author Burak Emir
* @param text the text contained in this node, may not contain "--"
*/
-case class Comment(commentText: String) extends SpecialNode {
-
- final override def collectNamespacesAndDontTransform = false
-
- if (commentText.indexOf("--") != -1)
- throw new IllegalArgumentException("text containts \"--\"")
-
- /** structural equality */
- override def equals(x: Any): Boolean = x match {
- case Comment(x) => x.equals(commentText)
- case _ => false
- }
-
- /** the constant &quot;#REM&quot; */
+case class Comment(commentText: String) extends SpecialNode
+{
def label = "#REM"
-
- /** hashcode for this Comment */
- override def hashCode() = commentText.hashCode()
-
override def text = ""
+ final override def collectNamespacesAndDontTransform = false
+
+ if (commentText contains "--")
+ throw new IllegalArgumentException("text contains \"--\"")
/** Appends &quot;<!-- text -->&quot; to this string buffer.
*/
override def buildString(sb: StringBuilder) =
- sb.append("<!--").append(commentText).append("-->")
+ sb append ("<!--" + commentText + "-->")
}
diff --git a/src/library/scala/xml/MetaData.scala b/src/library/scala/xml/MetaData.scala
index aafedf7702..95a1bbbf69 100644
--- a/src/library/scala/xml/MetaData.scala
+++ b/src/library/scala/xml/MetaData.scala
@@ -12,6 +12,7 @@
package scala.xml
import Utility.sbToString
+import annotation.tailrec
/**
* Copyright 2008 Google Inc. All Rights Reserved.
@@ -25,11 +26,10 @@ object MetaData {
* the attributes in new_tail, but does not guarantee to preserve the relative order of attribs.
* Duplicates can be removed with normalize.
*/
+ @tailrec
def concatenate(attribs: MetaData, new_tail: MetaData): MetaData =
- if (attribs eq Null)
- new_tail
- else
- concatenate(attribs.next, attribs.copy(new_tail)) // tail-recursive
+ if (attribs eq Null) new_tail
+ else concatenate(attribs.next, attribs.copy(new_tail))
/**
* returns normalized MetaData, with all duplicates removed and namespace prefixes resolved to
@@ -81,29 +81,17 @@ object MetaData {
* @author Burak Emir <bqe@google.com>
*/
@serializable
-abstract class MetaData extends Iterable[MetaData] {
-
- /** updates this MetaData with the MetaData given as argument. All attributes that occur in updates
- * are part of the resulting MetaData. If an unprefixed attribute occurs in both this instance and
- * updates, only the one in updates is part of the result (avoiding duplicates). However, for
- * prefixed attributes no duplicate-detection is attempted, the method
- * append(updates: MetaData, scope:NamespaceBinding) should be used instead.
- *
- * @param updates MetaData with new attributes and updated attributes
- * @return a new MetaData instance that contains the combined attributes of this and updates
- */
- def append(updates: MetaData): MetaData =
- MetaData.update(this, TopScope, updates)
-
- /** updates this MetaData with the MetaData given as argument. All attributes that occur in updates
+abstract class MetaData extends Iterable[MetaData]
+{
+ /** Updates this MetaData with the MetaData given as argument. All attributes that occur in updates
* are part of the resulting MetaData. If an attribute occurs in both this instance and
* updates, only the one in updates is part of the result (avoiding duplicates). For prefixed
- * attributes, namespaces are resolved using the given scope.
+ * attributes, namespaces are resolved using the given scope, which defaults to TopScope.
*
* @param updates MetaData with new and updated attributes
* @return a new MetaData instance that contains old, new and updated attributes
*/
- def append(updates: MetaData, scope: NamespaceBinding): MetaData =
+ def append(updates: MetaData, scope: NamespaceBinding = TopScope): MetaData =
MetaData.update(this, scope, updates)
/**
@@ -160,16 +148,13 @@ abstract class MetaData extends Iterable[MetaData] {
def isPrefixed: Boolean
/** deep equals method */
- override def equals(that: Any) =
- that match {
- case m: MetaData =>
- var res = (this.length == m.length) && (this.hashCode() == m.hashCode())
- val it = this.iterator
- while (res && it.hasNext) { res = it.next.containedIn1(m) }
- res
- case _ =>
- false
- }
+ override def equals(that: Any) = that match {
+ case m: MetaData =>
+ (this.length == m.length) &&
+ (this.hashCode == m.hashCode) &&
+ (this forall (_ containedIn1 m))
+ case _ => false
+ }
/** returns an iterator on attributes */
def iterator: Iterator[MetaData] = new Iterator[MetaData] {
@@ -238,8 +223,8 @@ abstract class MetaData extends Iterable[MetaData] {
def toString1(): String = sbToString(toString1)
- //appends string representations of single attribute to StringBuilder
- def toString1(sb:StringBuilder): Unit
+ // appends string representations of single attribute to StringBuilder
+ def toString1(sb: StringBuilder): Unit
override def toString(): String = sbToString(buildString)
@@ -259,7 +244,7 @@ abstract class MetaData extends Iterable[MetaData] {
* @param key ...
* @return ...
*/
- def remove(key:String): MetaData
+ def remove(key: String): MetaData
/**
* @param namespace ...
diff --git a/src/library/scala/xml/Node.scala b/src/library/scala/xml/Node.scala
index d022d9f8b8..2b6427ae74 100644
--- a/src/library/scala/xml/Node.scala
+++ b/src/library/scala/xml/Node.scala
@@ -174,8 +174,8 @@ abstract class Node extends NodeSeq {
* @param stripComment if true, strips comment nodes from result
* @return ...
*/
- def buildString(stripComment: Boolean): String =
- Utility.toXML(this, stripComment)
+ def buildString(stripComments: Boolean): String =
+ Utility.toXML(this, stripComments = stripComments).toString
/**
* Same as <code>toString(false)</code>.
diff --git a/src/library/scala/xml/NodeBuffer.scala b/src/library/scala/xml/NodeBuffer.scala
index d83876e255..d20f6fadcc 100644
--- a/src/library/scala/xml/NodeBuffer.scala
+++ b/src/library/scala/xml/NodeBuffer.scala
@@ -39,23 +39,12 @@ class NodeBuffer extends scala.collection.mutable.ArrayBuffer[Node] {
*/
def &+(o: Any): NodeBuffer = {
o match {
- case null | _:Unit | Text("")=>
- // ignore
-
- case it:Iterator[_] =>
- while (it.hasNext)
- this &+ it.next
-
- case n:Node =>
- super.+=(n)
-
- case ns:Iterable[_] =>
- this &+ ns.iterator
-
- case d =>
- super.+=(new Atom(d))
+ case null | _: Unit | Text("") => // ignore
+ case it: Iterator[_] => it foreach (this &+ _)
+ case n: Node => super.+=(n)
+ case ns: Iterable[_] => this &+ ns.iterator
+ case d => super.+=(new Atom(d))
}
this
}
-
}
diff --git a/src/library/scala/xml/NodeSeq.scala b/src/library/scala/xml/NodeSeq.scala
index 6485ed3df7..09828f7652 100644
--- a/src/library/scala/xml/NodeSeq.scala
+++ b/src/library/scala/xml/NodeSeq.scala
@@ -21,7 +21,7 @@ import collection.mutable.ListBuffer
* @version 1.0
*/
object NodeSeq {
- final val Empty = new NodeSeq { def theSeq = Nil }
+ final val Empty = fromSeq(Nil)
def fromSeq(s: Seq[Node]): NodeSeq = new NodeSeq {
def theSeq = s
}
@@ -46,8 +46,8 @@ abstract class NodeSeq extends immutable.Sequence[Node] with SequenceTemplate[No
def theSeq: Seq[Node]
def length = theSeq.length
override def iterator = theSeq.iterator
- def apply(i: Int): Node = theSeq.apply(i)
+ def apply(i: Int): Node = theSeq(i)
def apply(f: Node => Boolean): NodeSeq = filter(f)
/** structural equality */
@@ -55,7 +55,7 @@ abstract class NodeSeq extends immutable.Sequence[Node] with SequenceTemplate[No
case z:Node => (length == 1) && z == apply(0)
case z:Seq[_] => sameElements(z)
case z:String => text == z
- case _ => false;
+ case _ => false
}
/** Projection function. Similar to XPath, use <code>this \ "foo"</code>
@@ -128,29 +128,6 @@ abstract class NodeSeq extends immutable.Sequence[Node] with SequenceTemplate[No
}
}
- override def toString(): String = theSeq.iterator.foldLeft ("") {
- (s: String, x: Node) => s + x.toString()
- }
-/*
- def map(f: Node => NodeSeq): NodeSeq = flatMap(f)
-
- def flatMap(f: Node => NodeSeq): NodeSeq = {
- val y = toList flatMap { x => f(x).toList }
- y
- }
-
- override def filter(f: Node => Boolean): NodeSeq = {
- val x = toList filter f
- x
- }
-*/
-
- def text: String = {
- val sb = new StringBuilder()
- val it = this.iterator
- while (it.hasNext) {
- sb.append(it.next.text)
- }
- sb.toString()
- }
+ override def toString(): String = theSeq.mkString
+ def text: String = this map (_.text) mkString
}
diff --git a/src/library/scala/xml/Null.scala b/src/library/scala/xml/Null.scala
index 5885201acd..7718c61493 100644
--- a/src/library/scala/xml/Null.scala
+++ b/src/library/scala/xml/Null.scala
@@ -14,7 +14,7 @@ package scala.xml
case object Null extends MetaData {
/** appends given MetaData items to this MetaData list */
- override def append(m: MetaData): MetaData = m
+ override def append(m: MetaData, scope: NamespaceBinding = TopScope): MetaData = m
override def containedIn1(m: MetaData): Boolean = false
diff --git a/src/library/scala/xml/PCData.scala b/src/library/scala/xml/PCData.scala
index 210b82f54b..5cf4bda070 100644
--- a/src/library/scala/xml/PCData.scala
+++ b/src/library/scala/xml/PCData.scala
@@ -23,9 +23,6 @@ case class PCData(_data: String) extends Atom[String](_data) {
* @param sb ...
* @return ...
*/
- override def buildString(sb: StringBuilder) = {
- sb.append("<![CDATA[")
- sb.append(data)
- sb.append("]]>")
- }
+ override def buildString(sb: StringBuilder) =
+ sb append "<![CDATA[%s]]>".format(data)
}
diff --git a/src/library/scala/xml/Parsing.scala b/src/library/scala/xml/Parsing.scala
index 7d5545233f..3f64ff63e2 100644
--- a/src/library/scala/xml/Parsing.scala
+++ b/src/library/scala/xml/Parsing.scala
@@ -29,27 +29,26 @@ object Parsing {
}
/** <pre>(#x20 | #x9 | #xD | #xA)+</pre> */
- final def isSpace(cs: Seq[Char]): Boolean = {
- val it = cs.iterator
- it.hasNext && it.forall { isSpace }
- }
+ final def isSpace(cs: Seq[Char]): Boolean = cs forall isSpace
/** <pre>NameChar ::= Letter | Digit | '.' | '-' | '_' | ':'
* | CombiningChar | Extender</pre>
*
* see [4] and Appendix B of XML 1.0 specification
*/
- def isNameChar(ch: Char) = isNameStart(ch) || (ch match {
- case '.' | '-' | ':' => true
- case _ => java.lang.Character.getType(ch).asInstanceOf[Byte] match {
- case java.lang.Character.COMBINING_SPACING_MARK => true // Mc
- case java.lang.Character.ENCLOSING_MARK => true // Me
- case java.lang.Character.NON_SPACING_MARK => true // Mn
- case java.lang.Character.MODIFIER_LETTER => true // Lm
- case java.lang.Character.DECIMAL_DIGIT_NUMBER => true // Nd
- case _ => false
- }
- });
+ private val nameCharTypeList = {
+ import java.lang.Character._
+ List(
+ COMBINING_SPACING_MARK, // Mc
+ ENCLOSING_MARK, // Me
+ NON_SPACING_MARK, // Mn
+ MODIFIER_LETTER, // Lm
+ DECIMAL_DIGIT_NUMBER // Nd
+ )
+ }
+ def isNameChar(ch: Char) =
+ isNameStart(ch) || List('.', '-', ':').contains(ch) ||
+ nameCharTypeList.contains(Character.getType(ch).asInstanceOf[Byte])
/** <pre>NameStart ::= ( Letter | '_' )</pre>
* where Letter means in one of the Unicode general
@@ -94,12 +93,5 @@ object Parsing {
def checkSysID(s: String): Boolean =
s.indexOf('"') == -1 || s.indexOf('\'') == -1
- def checkPubID(s: String): Boolean =
- if (s.length() > 0) {
- val z:Seq[Char] = s
- val y = z.iterator
- while (y.hasNext && isPubIDChar(y.next)) {}
- !y.hasNext
- } else true
-
+ def checkPubID(s: String): Boolean = s forall isPubIDChar
}
diff --git a/src/library/scala/xml/ProcInstr.scala b/src/library/scala/xml/ProcInstr.scala
index 590b14a2ec..e70b606fb3 100644
--- a/src/library/scala/xml/ProcInstr.scala
+++ b/src/library/scala/xml/ProcInstr.scala
@@ -17,11 +17,12 @@ package scala.xml
* @param target target name of this PI
* @param text text contained in this node, may not contain "?>"
*/
-case class ProcInstr(target:String, proctext:String) extends SpecialNode {
+case class ProcInstr(target:String, proctext:String) extends SpecialNode
+{
if (!Utility.isName(target))
throw new IllegalArgumentException(target+" must be an XML Name")
- else if (text.indexOf("?>") != -1)
+ if (text.indexOf("?>") != -1)
throw new IllegalArgumentException(proctext+" may not contain \"?>\"")
final override def collectNamespacesAndDontTransform = false
diff --git a/src/library/scala/xml/QNode.scala b/src/library/scala/xml/QNode.scala
index 98b1a15422..7a47d3ef9d 100644
--- a/src/library/scala/xml/QNode.scala
+++ b/src/library/scala/xml/QNode.scala
@@ -18,7 +18,5 @@ package scala.xml
* @version 1.0
*/
object QNode {
-
- def unapplySeq(n:Node) = Some (Tuple4(n.scope.getURI(n.prefix), n.label, n.attributes, n.child))
-
+ def unapplySeq(n: Node) = Some((n.scope.getURI(n.prefix), n.label, n.attributes, n.child))
}
diff --git a/src/library/scala/xml/SpecialNode.scala b/src/library/scala/xml/SpecialNode.scala
index 9663258abc..084de78ecd 100644
--- a/src/library/scala/xml/SpecialNode.scala
+++ b/src/library/scala/xml/SpecialNode.scala
@@ -21,8 +21,8 @@ package scala.xml
*
* @author Burak Emir
*/
-abstract class SpecialNode extends Node with pull.XMLEvent {
-
+abstract class SpecialNode extends Node with pull.XMLEvent
+{
/** always empty */
final override def attributes = Null
@@ -34,5 +34,4 @@ abstract class SpecialNode extends Node with pull.XMLEvent {
/** append string representation to the given stringbuffer */
def buildString(sb: StringBuilder): StringBuilder
-
}
diff --git a/src/library/scala/xml/Text.scala b/src/library/scala/xml/Text.scala
index 7b01439fa3..f434d10acf 100644
--- a/src/library/scala/xml/Text.scala
+++ b/src/library/scala/xml/Text.scala
@@ -19,10 +19,10 @@ package scala.xml
*
* @param text the text contained in this node, may not be null.
*/
-case class Text(_data: String) extends Atom[String](_data) {
-
+case class Text(_data: String) extends Atom[String](_data)
+{
if (null == data)
- throw new java.lang.NullPointerException("tried to construct Text with null")
+ throw new IllegalArgumentException("tried to construct Text with null")
final override def equals(x: Any) = x match {
case s:String => s == data
diff --git a/src/library/scala/xml/Unparsed.scala b/src/library/scala/xml/Unparsed.scala
index 3563d47a91..299bca655c 100644
--- a/src/library/scala/xml/Unparsed.scala
+++ b/src/library/scala/xml/Unparsed.scala
@@ -15,12 +15,12 @@ package scala.xml
* are off regarding wellformedness etc.
*
* @author Burak Emir
- * @param _data content in this node, may not be null.
+ * @param data content in this node, may not be null.
*/
-case class Unparsed(_data: String) extends Atom[String](_data) {
-
+class Unparsed(data: String) extends Atom[String](data)
+{
if (null == data)
- throw new java.lang.NullPointerException("tried to construct Unparsed with null")
+ throw new IllegalArgumentException("tried to construct Unparsed with null")
final override def equals(x: Any) = x match {
case s:String => s == data
@@ -32,5 +32,9 @@ case class Unparsed(_data: String) extends Atom[String](_data) {
/** returns text, with some characters escaped according to XML spec */
override def buildString(sb: StringBuilder) = sb append data
-
}
+
+object Unparsed {
+ def apply(data: String) = new Unparsed(data)
+ def unapply(x: Unparsed) = Some(x.data)
+} \ No newline at end of file
diff --git a/src/library/scala/xml/Utility.scala b/src/library/scala/xml/Utility.scala
index c541555d23..17584ee40d 100644
--- a/src/library/scala/xml/Utility.scala
+++ b/src/library/scala/xml/Utility.scala
@@ -12,6 +12,7 @@
package scala.xml
import collection.mutable.{Set, HashSet}
+import parsing.XhtmlEntities
/**
* The <code>Utility</code> object provides utility functions for processing
@@ -21,6 +22,8 @@ import collection.mutable.{Set, HashSet}
*/
object Utility extends AnyRef with parsing.TokenTests
{
+ implicit def implicitSbToString(sb: StringBuilder) = sb.toString()
+
// helper for the extremely oft-repeated sequence of creating a
// StringBuilder, passing it around, and then grabbing its String.
private [xml] def sbToString(f: (StringBuilder) => Unit): String = {
@@ -30,18 +33,6 @@ object Utility extends AnyRef with parsing.TokenTests
}
private[xml] def isAtomAndNotText(x: Node) = x.isAtom && !x.isInstanceOf[Text]
- // XXX this is very ham fisted at the moment
- class XMLOptions {
- val stripComments: Boolean = false
- val decodeEntities: Boolean = true
- val preserveWhitespace: Boolean = false
- val minimizeTags: Boolean = false
- }
- object XMLOptions {
- def withStripComments(x: Boolean) = new XMLOptions { override val stripComments = x }
- def withMinimizeTags(x: Boolean) = new XMLOptions { override val minimizeTags = x }
- }
-
/** trims an element - call this method, when you know that it is an
* element (and not a text node) so you know that it will not be trimmed
* away. With this assumption, the function can return a <code>Node</code>,
@@ -95,13 +86,13 @@ object Utility extends AnyRef with parsing.TokenTests
object Escapes {
/** For reasons unclear escape and unescape are a long ways from
- * being logical inverses. */
+ being logical inverses. */
private val pairs = List(
"lt" -> '<',
"gt" -> '>',
"amp" -> '&',
"quot" -> '"'
- // comment explaining why this isn't escaped --
+ // enigmatic comment explaining why this isn't escaped --
// is valid xhtml but not html, and IE doesn't know it, says jweb
// "apos" -> '\''
)
@@ -164,50 +155,32 @@ object Utility extends AnyRef with parsing.TokenTests
}
}
- /**
- * Returs the string representation of an XML node, with comments stripped
- * the comments.
- *
- * @param n the XML node
- * @return the string representation of node <code>n</code>.
- *
- * @see "toXML(Node, Boolean)"
- */
- def toXML(n: Node): String = toXML(n, true)
-
- /**
- * Return the string representation of a Node. uses namespace mapping from
- * <code>defaultPrefixes(n)</code>.
- *
- * @param n the XML node
- * @param stripComment ...
- * @return ...
- *
- * @todo define a way to escape literal characters to &amp;xx; references
- */
- def toXML(n: Node, _stripComments: Boolean): String = {
- sbToString(toXML(n, TopScope, _)(XMLOptions.withStripComments(_stripComments)))
- }
-
- /**
- * Appends a tree to the given stringbuffer within given namespace scope.
- *
- * @param n the node
- * @param pscope the parent scope
- * @param sb stringbuffer to append to
- * @param stripComment if true, strip comments
- */
- def toXML(x: Node, pscope: NamespaceBinding, sb: StringBuilder, _stripComments: Boolean) {
- toXML(x, pscope, sb)(XMLOptions.withStripComments(_stripComments))
- }
-
- def toXML(x: Node, pscope: NamespaceBinding, sb: StringBuilder)(implicit config: XMLOptions) {
- import config._
-
+ // def toXML(
+ // x: Node,
+ // pscope: NamespaceBinding = TopScope,
+ // sb: StringBuilder = new StringBuilder,
+ // stripComments: Boolean = false,
+ // decodeEntities: Boolean = true,
+ // preserveWhitespace: Boolean = false,
+ // minimizeTags: Boolean = false): String =
+ // {
+ // toXMLsb(x, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
+ // sb.toString()
+ // }
+
+ def toXML(
+ x: Node,
+ pscope: NamespaceBinding = TopScope,
+ sb: StringBuilder = new StringBuilder,
+ stripComments: Boolean = false,
+ decodeEntities: Boolean = true,
+ preserveWhitespace: Boolean = false,
+ minimizeTags: Boolean = false): StringBuilder =
+ {
x match {
case c: Comment if !stripComments => c buildString sb
case x: SpecialNode => x buildString sb
- case g: Group => for (c <- g.nodes) toXML(c, x.scope, sb)
+ case g: Group => for (c <- g.nodes) toXML(c, x.scope, sb) ; sb
case _ =>
// print tag with namespace declarations
sb.append('<')
@@ -228,21 +201,12 @@ object Utility extends AnyRef with parsing.TokenTests
}
}
-
-
- /**
- * @param children ...
- * @param pscope ...
- * @param sb ...
- * @param stripComment ...
- */
- def sequenceToXML(children: Seq[Node], pscope: NamespaceBinding, sb: StringBuilder, _stripComments: Boolean) {
- sequenceToXML(children, pscope, sb)(XMLOptions.withStripComments(_stripComments))
- }
-
- def sequenceToXML(children: Seq[Node], pscope: NamespaceBinding, sb: StringBuilder)(implicit config: XMLOptions) {
- import config._
-
+ def sequenceToXML(
+ children: Seq[Node],
+ pscope: NamespaceBinding = TopScope,
+ sb: StringBuilder = new StringBuilder,
+ stripComments: Boolean = false): Unit =
+ {
if (children.isEmpty) return
else if (children forall isAtomAndNotText) { // add space
val it = children.iterator
@@ -263,9 +227,9 @@ object Utility extends AnyRef with parsing.TokenTests
* @param name ...
* @return ...
*/
- final def prefix(name: String): Option[String] = {
- val i = name.indexOf(':'.asInstanceOf[Int])
- if (i != -1) Some(name.substring(0, i)) else None
+ final def prefix(name: String): Option[String] = (name indexOf ':') match {
+ case -1 => None
+ case i => Some(name.substring(0, i))
}
/**
@@ -300,7 +264,7 @@ object Utility extends AnyRef with parsing.TokenTests
* @return ...
*/
def appendQuoted(s: String, sb: StringBuilder) = {
- val ch = if (s.indexOf('"'.asInstanceOf[Int]) == -1) '"' else '\'';
+ val ch = if (s contains '"') '\'' else '"'
sb.append(ch).append(s).append(ch)
}
@@ -326,17 +290,11 @@ object Utility extends AnyRef with parsing.TokenTests
* @return ...
*/
def getName(s: String, index: Int): String = {
- var i = index;
- val sb = new StringBuilder();
- if (i < s.length) {
- var c = s.charAt(i);
- if (isNameStart(s.charAt(i)))
- while (i < s.length && { c = s.charAt(i); isNameChar(c)}) {
- sb.append(c)
- i = i + 1
- }
- sb.toString()
- } else null
+ if (index >= s.length) null
+ else (s drop index) match {
+ case Seq(x, xs @ _*) if isNameStart(x) => (Array(x) ++ (xs takeWhile isNameChar)).mkString
+ case _ => ""
+ }
}
/**
diff --git a/src/library/scala/xml/XML.scala b/src/library/scala/xml/XML.scala
index f5251416b5..1c41af5117 100644
--- a/src/library/scala/xml/XML.scala
+++ b/src/library/scala/xml/XML.scala
@@ -17,6 +17,7 @@ import scala.xml.parsing.NoBindingFactoryAdapter
import org.xml.sax.InputSource
import java.io.{File, FileDescriptor, FileInputStream, FileOutputStream}
import java.io.{InputStream, Reader, StringReader, Writer}
+import scala.util.control.Exception.ultimately
/** The object <code>XML</code> provides constants, and functions to load
* and save XML elements. Use this when data binding is not desired, i.e.
@@ -25,8 +26,8 @@ import java.io.{InputStream, Reader, StringReader, Writer}
* @author Burak Emir
* @version 1.0, 25/04/2005
*/
-object XML {
-
+object XML
+{
val xml = "xml"
val xmlns = "xmlns"
val namespace = "http://www.w3.org/XML/1998/namespace"
@@ -36,83 +37,51 @@ object XML {
val encoding = "ISO-8859-1"
// functions for generic xml loading, saving
+ private def mkAdapter(is: InputSource): Elem = new NoBindingFactoryAdapter().loadXML(is)
+ private def mkAdapter(fis: FileInputStream): Elem = mkAdapter(new InputSource(fis))
/** loads XML from given file, using XML parser in JDK. */
final def loadFile(file: File): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(
- new FileInputStream(file)
- ))
+ mkAdapter(new FileInputStream(file))
- /** loads XML from given file descriptor, using XML parser in JDK.
- *
- * @param fileDesc ...
- * @return ...
- */
+ /** loads XML from given file descriptor, using XML parser in JDK. */
final def loadFile(fileDesc: FileDescriptor): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(
- new FileInputStream(fileDesc)
- ))
+ mkAdapter(new FileInputStream(fileDesc))
/** loads XML from given file, using XML parser in JDK. */
final def loadFile(fileName: String): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(
- new FileInputStream(fileName)
- ));
+ mkAdapter(new FileInputStream(fileName))
/** loads XML from given InputStream, using XML parser in JDK. */
- final def load( is:InputStream ): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(is))
+ final def load(is: InputStream): Elem =
+ mkAdapter(new InputSource(is))
/** loads XML from given Reader, using XML parser in JDK. */
final def load(reader: Reader): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(reader))
+ mkAdapter(new InputSource(reader))
/** loads XML from given sysID, using XML parser in JDK. */
final def load(sysID: String): Elem =
- new NoBindingFactoryAdapter().loadXML(new InputSource(sysID))
+ mkAdapter(new InputSource(sysID))
/** loads XML from a given input source, using XML parser in JDK.
*
* @param source ...
* @return ...
*/
- final def load(source: InputSource): Elem =
- new NoBindingFactoryAdapter().loadXML(source)
+ final def load(source: InputSource): Elem = mkAdapter(source)
/** loads XML from a string, using XML parser in JDK. */
- final def loadString(string: String): Elem =
- load(new StringReader(string))
-
- /** Saves XML to filename with encoding ISO-8859-1 without xml-decl without
- * <code>doctype</code>.
- *
- * @param filename ...
- * @param node ...
- */
- final def save(filename: String, node: Node): Unit =
- save(filename, node, encoding)
+ final def loadString(string: String): Elem = load(new StringReader(string))
- /** saves XML to filename with given encoding, without xml-decl without
- * <code>doctype</code>.
- *
- * @param filename ...
- * @param node ...
- * @param enc ...
- */
- final def save(filename: String, node: Node, enc: String): Unit =
- saveFull(filename, node, enc, false, null);
-
- /** saves a node to a file with given filename using encoding iso-8859-1
- * optionally with xmldecl and doctype declaration.
- *
- * @param filename the filename
- * @param node the xml node we want to write
- * @param xmlDecl if true, write xml declaration
- * @param doctype if not null, write doctype declaration
- */
+ @deprecated("Use save() instead")
final def saveFull(filename: String, node: Node, xmlDecl: Boolean, doctype: dtd.DocType): Unit =
saveFull(filename, node, encoding, xmlDecl, doctype)
+ @deprecated("Use save() instead")
+ final def saveFull(filename: String, node: Node, enc: String, xmlDecl: Boolean, doctype: dtd.DocType): Unit =
+ saveFull(filename, node, enc, xmlDecl, doctype)
+
/** Saves a node to a file with given filename using given encoding
* optionally with xmldecl and doctype declaration.
*
@@ -122,22 +91,23 @@ object XML {
* @param xmlDecl if true, write xml declaration
* @param doctype if not null, write doctype declaration
*/
-
- final def saveFull(filename: String, node: Node, enc: String, xmlDecl: Boolean, doctype: dtd.DocType) {
- var fos: FileOutputStream = null
- var w: Writer = null
- try {
- // using NIO classes of JDK 1.4
- import java.io.{FileOutputStream, Writer}
- import java.nio.channels.{Channels, FileChannel}
-
- fos = new FileOutputStream(filename)
- w = Channels.newWriter(fos.getChannel(), enc)
+ final def save(
+ filename: String,
+ node: Node,
+ enc: String = encoding,
+ xmlDecl: Boolean = false,
+ doctype: dtd.DocType
+ ): Unit =
+ {
+ // using NIO classes of JDK 1.4
+ import java.io._
+ import java.nio.channels._
+ val fos = new FileOutputStream(filename)
+ val w = Channels.newWriter(fos.getChannel(), enc)
+
+ ultimately({ w.close() ; fos.close() })(
write(w, node, enc, xmlDecl, doctype)
- } finally {
- w.close()
- fos.close()
- }
+ )
}
/** Writes the given node using writer, optionally with xml decl and doctype.
@@ -153,6 +123,6 @@ object XML {
/* TODO: optimize by giving writer parameter to toXML*/
if (xmlDecl) w.write("<?xml version='1.0' encoding='" + enc + "'?>\n")
if (doctype ne null) w.write( doctype.toString() + "\n")
- w.write(Utility.toXML(node))
+ w.write(Utility.toXML(node).toString)
}
}
diff --git a/src/library/scala/xml/Xhtml.scala b/src/library/scala/xml/Xhtml.scala
index ec1790238f..70b9be93ed 100644
--- a/src/library/scala/xml/Xhtml.scala
+++ b/src/library/scala/xml/Xhtml.scala
@@ -3,7 +3,7 @@
package scala.xml
import parsing.XhtmlEntities
-import Utility.{ XMLOptions, sbToString, isAtomAndNotText }
+import Utility.{ sbToString, isAtomAndNotText }
/* (c) David Pollak 2007 WorldWide Conferencing, LLC */
@@ -14,7 +14,7 @@ object Xhtml
*
* @param node the node
*/
- def toXhtml(node: Node): String = toXhtml(node, false, false)
+ def toXhtml(node: Node): String = sbToString(toXhtml(x = node, sb = _))
/**
* Convenience function: amounts to calling toXhtml(node) on each
@@ -22,43 +22,17 @@ object Xhtml
*
* @param nodeSeq the node sequence
*/
- def toXhtml(nodeSeq: NodeSeq): String =
- sbToString(sequenceToXML(nodeSeq, TopScope, _, false, false))
-
- /**
- * Convenience function: amounts to calling toXhtml(node, TopScope, ...)
- * with the supplied parameters.
- *
- * @param nodeSeq the node sequence
- */
- def toXhtml(n: Node, _stripComments: Boolean, _convertAmp: Boolean): String = {
- sbToString(toXhtml(n, TopScope, _, _stripComments, _convertAmp))
- }
-
- /**
- * Appends a tree to the given stringbuffer within given namespace scope.
- *
- * @param n the node
- * @param pscope the parent scope
- * @param sb stringbuffer to append to
- * @param stripComment if true, strip comments
- * @param convertAmp if true, decode entity references
- */
- def toXhtml(n: Node, pscope: NamespaceBinding, sb: StringBuilder, _stripComments: Boolean, _convertAmp: Boolean): String = {
- implicit val config = new XMLOptions {
- override val stripComments = _stripComments
- override val decodeEntities = _convertAmp
- }
- sbToString(toXhtml(n, TopScope, _))
- }
+ def toXhtml(nodeSeq: NodeSeq): String = sbToString(sequenceToXML(nodeSeq: Seq[Node], sb = _))
def toXhtml(
x: Node,
- pscope: NamespaceBinding,
- sb: StringBuilder)(implicit config: XMLOptions): Unit =
+ pscope: NamespaceBinding = TopScope,
+ sb: StringBuilder = new StringBuilder,
+ stripComments: Boolean = false,
+ decodeEntities: Boolean = false,
+ preserveWhitespace: Boolean = false,
+ minimizeTags: Boolean = false): Unit =
{
- import config._
-
def decode(er: EntityRef) = XhtmlEntities.entMap.get(er.entityName) match {
case Some(chr) if chr.toInt >= 128 => sb.append(chr)
case _ => er.buildString(sb)
@@ -97,25 +71,17 @@ object Xhtml
*/
def sequenceToXML(
children: Seq[Node],
- pscope: NamespaceBinding,
- sb: StringBuilder,
- _stripComments: Boolean,
- _convertAmp: Boolean): Unit =
+ pscope: NamespaceBinding = TopScope,
+ sb: StringBuilder = new StringBuilder,
+ stripComments: Boolean = false,
+ decodeEntities: Boolean = false,
+ preserveWhitespace: Boolean = false,
+ minimizeTags: Boolean = false): Unit =
{
- implicit val config = new XMLOptions {
- override val stripComments = _stripComments
- override val decodeEntities = _convertAmp
- }
- sequenceToXML(children, pscope, sb)
- }
+ if (children.isEmpty)
+ return
- def sequenceToXML(
- children: Seq[Node],
- pscope: NamespaceBinding,
- sb: StringBuilder)(implicit config: XMLOptions): Unit =
- {
val doSpaces = children forall isAtomAndNotText // interleave spaces
-
for (c <- children.take(children.length - 1)) {
toXhtml(c, pscope, sb)
if (doSpaces) sb append ' '
@@ -123,4 +89,3 @@ object Xhtml
toXhtml(children.last, pscope, sb)
}
}
-
diff --git a/src/library/scala/xml/dtd/Decl.scala b/src/library/scala/xml/dtd/Decl.scala
index 50385c69a6..af7ef47fef 100644
--- a/src/library/scala/xml/dtd/Decl.scala
+++ b/src/library/scala/xml/dtd/Decl.scala
@@ -21,7 +21,8 @@ abstract class MarkupDecl extends Decl {
/** an element declaration
*/
case class ElemDecl(name: String, contentModel: ContentModel)
-extends MarkupDecl with DtdTypeSymbol {
+extends MarkupDecl with DtdTypeSymbol
+{
override def buildString(sb: StringBuilder): StringBuilder = {
sb
.append("<!ELEMENT ")
diff --git a/src/library/scala/xml/dtd/DocType.scala b/src/library/scala/xml/dtd/DocType.scala
index 0c587c0df5..eb5eb27c55 100644
--- a/src/library/scala/xml/dtd/DocType.scala
+++ b/src/library/scala/xml/dtd/DocType.scala
@@ -19,27 +19,17 @@ package scala.xml.dtd
* @param extID None, or Some(external ID of this doctype)
* @param intSubset sequence of internal subset declarations
*/
-case class DocType(name: String, extID: ExternalID, intSubset: Seq[dtd.Decl]) {
-
+case class DocType(name: String, extID: ExternalID, intSubset: Seq[dtd.Decl])
+{
if (!Utility.isName(name))
- throw new IllegalArgumentException(name+" must be an XML Name");
-
- /** hashcode for this processing instruction */
- final override def hashCode() =
- name.hashCode() + 7 * extID.hashCode() + 41*intSubset.toList.hashCode();
+ throw new IllegalArgumentException(name+" must be an XML Name")
/** returns "&lt;!DOCTYPE + name + extID? + ("["+intSubSet+"]")? >" */
final override def toString() = {
- val sb = new StringBuilder("<!DOCTYPE ")
- sb.append(name)
- sb.append(' ')
- sb.append(extID.toString())
- if (intSubset.length > 0) {
- sb.append('[')
- for (d <- intSubset) sb.append(d.toString())
- sb.append(']')
- }
- sb.append('>')
- sb.toString()
+ def intString =
+ if (intSubset.isEmpty) ""
+ else intSubset.mkString("[", "", "]")
+
+ """<!DOCTYPE %s %s%s>""".format(name, extID.toString, intString)
}
}
diff --git a/src/library/scala/xml/parsing/ConstructingHandler.scala b/src/library/scala/xml/parsing/ConstructingHandler.scala
index f3435646e3..f21cca2a7f 100644
--- a/src/library/scala/xml/parsing/ConstructingHandler.scala
+++ b/src/library/scala/xml/parsing/ConstructingHandler.scala
@@ -16,8 +16,8 @@ package scala.xml.parsing
* @author Burak Emir
* @version 1.0
*/
-abstract class ConstructingHandler extends MarkupHandler {
-
+abstract class ConstructingHandler extends MarkupHandler
+{
val preserveWS: Boolean
def elem(pos: Int, pre: String, label: String, attrs: MetaData,
@@ -27,13 +27,7 @@ abstract class ConstructingHandler extends MarkupHandler {
def procInstr(pos: Int, target: String, txt: String) =
ProcInstr(target, txt)
- def comment(pos: Int, txt: String) =
- Comment(txt)
-
- def entityRef(pos: Int, n: String) =
- EntityRef(n)
-
- def text(pos: Int, txt:String) =
- Text(txt)
-
+ def comment(pos: Int, txt: String) = Comment(txt)
+ def entityRef(pos: Int, n: String) = EntityRef(n)
+ def text(pos: Int, txt: String) = Text(txt)
}
diff --git a/src/library/scala/xml/parsing/MarkupHandler.scala b/src/library/scala/xml/parsing/MarkupHandler.scala
index e0b90c7320..e49254f386 100644
--- a/src/library/scala/xml/parsing/MarkupHandler.scala
+++ b/src/library/scala/xml/parsing/MarkupHandler.scala
@@ -25,8 +25,8 @@ import scala.xml.dtd._
* @todo can we ignore more entity declarations (i.e. those with extIDs)?
* @todo expanding entity references
*/
-abstract class MarkupHandler extends AnyRef with Logged {
-
+abstract class MarkupHandler extends Logged
+{
// impl. of Logged
//def log(msg:String) = {}
diff --git a/src/library/scala/xml/path/Expression.scala b/src/library/scala/xml/path/Expression.scala
index d6b658446a..b62414c889 100644
--- a/src/library/scala/xml/path/Expression.scala
+++ b/src/library/scala/xml/path/Expression.scala
@@ -9,11 +9,10 @@
// $Id$
-package scala.xml.path;
-
-
-object Expression {
+package scala.xml.path
+object Expression
+{
final def testFromString(x: String): Test = {
x.charAt(0) match {
case '*' if( x.length() == 1 ) => WildcardTest;
diff --git a/src/library/scala/xml/transform/BasicTransformer.scala b/src/library/scala/xml/transform/BasicTransformer.scala
index ed7aec7627..e566e27d02 100644
--- a/src/library/scala/xml/transform/BasicTransformer.scala
+++ b/src/library/scala/xml/transform/BasicTransformer.scala
@@ -16,8 +16,8 @@ package scala.xml.transform
* @author Burak Emir
* @version 1.0
*/
-abstract class BasicTransformer extends Function1[Node,Node] {
-
+abstract class BasicTransformer extends Function1[Node,Node]
+{
protected case class NeedsCopy(result: Seq[Node]) extends Throwable
/** Returns a new node buffer with the first <code>pos</code> elements