27930
|
1 |
/* Title: Pure/General/yxml.scala
|
|
2 |
ID: $Id$
|
|
3 |
Author: Makarius
|
|
4 |
|
|
5 |
Efficient text representation of XML trees.
|
|
6 |
*/
|
|
7 |
|
|
8 |
package isabelle
|
|
9 |
|
|
10 |
import java.util.regex.Pattern
|
|
11 |
|
|
12 |
|
|
13 |
object YXML {
|
|
14 |
|
|
15 |
/* markers */
|
|
16 |
|
|
17 |
private val X = '\5'
|
|
18 |
private val Y = '\6'
|
|
19 |
|
|
20 |
def detect(source: CharSequence) = {
|
|
21 |
source.length >= 2 &&
|
|
22 |
source.charAt(0) == X &&
|
|
23 |
source.charAt(1) == Y
|
|
24 |
}
|
|
25 |
|
|
26 |
|
|
27 |
/* parsing */
|
|
28 |
|
|
29 |
class BadYXML(msg: String) extends Exception
|
|
30 |
|
|
31 |
private def err(msg: String) = throw new BadYXML(msg)
|
|
32 |
private def err_attribute() = err("bad attribute")
|
|
33 |
private def err_element() = err("bad element")
|
|
34 |
private def err_unbalanced(name: String) =
|
|
35 |
if (name == "") err("unbalanced element")
|
|
36 |
else err("unbalanced element \"" + name + "\"")
|
|
37 |
|
|
38 |
private val X_pattern = Pattern.compile(Pattern.quote(X.toString))
|
|
39 |
private val Y_pattern = Pattern.compile(Pattern.quote(Y.toString))
|
|
40 |
private val eq_pattern = Pattern.compile(Pattern.quote("="))
|
|
41 |
|
|
42 |
private def parse_attrib(s: String) =
|
|
43 |
eq_pattern.split(s, 2).toList match {
|
|
44 |
case List(x, y) => if (x != "") (x, y) else err_attribute()
|
|
45 |
case _ => err_attribute()
|
|
46 |
}
|
|
47 |
|
|
48 |
|
|
49 |
def parse_body(source: CharSequence) = {
|
|
50 |
|
|
51 |
/* stack operations */
|
|
52 |
|
|
53 |
var stack: List[((String, XML.Attributes), List[XML.Tree])] = null
|
|
54 |
|
|
55 |
def add(x: XML.Tree) = stack match {
|
|
56 |
case ((elem, body) :: pending) => stack = (elem, x :: body) :: pending
|
|
57 |
}
|
|
58 |
|
|
59 |
def push(name: String, atts: XML.Attributes) =
|
|
60 |
if (name == "") err_element()
|
|
61 |
else stack = ((name, atts), Nil) :: stack
|
|
62 |
|
|
63 |
def pop() = stack match {
|
|
64 |
case ((("", _), _) :: _) => err_unbalanced("")
|
|
65 |
case (((name, atts), body) :: pending) =>
|
|
66 |
stack = pending; add(XML.Elem(name, atts, body.reverse))
|
|
67 |
}
|
|
68 |
|
|
69 |
|
|
70 |
/* parse chunks */
|
|
71 |
|
|
72 |
stack = List((("", Nil), Nil))
|
|
73 |
for (chunk <- X_pattern.split(source) if chunk != "") {
|
|
74 |
Y_pattern.split(chunk).toList match {
|
|
75 |
case Nil => pop()
|
|
76 |
case "" :: name :: atts => push(name, atts.map(parse_attrib))
|
|
77 |
case txts => for (txt <- txts) add(XML.Text(txt))
|
|
78 |
}
|
|
79 |
}
|
|
80 |
stack match {
|
|
81 |
case List((("", _), result)) => result.reverse
|
|
82 |
case ((name, _), _) :: _ => err_unbalanced(name)
|
|
83 |
}
|
|
84 |
}
|
|
85 |
|
|
86 |
def parse(source: CharSequence) =
|
|
87 |
parse_body(source) match {
|
|
88 |
case List(result) => result
|
|
89 |
case Nil => XML.Text("")
|
|
90 |
case _ => err("multiple results")
|
|
91 |
}
|
|
92 |
}
|