src/Pure/PIDE/xml.scala
author wenzelm
Tue Sep 18 15:55:29 2012 +0200 (2012-09-18 ago)
changeset 49417 c5a8592fb5d3
parent 49416 1053a564dd25
child 49465 76ecbc7f3683
permissions -rw-r--r--
recover order of stacked markup;
     1 /*  Title:      Pure/PIDE/xml.scala
     2     Module:     PIDE
     3     Author:     Makarius
     4 
     5 Untyped XML trees and basic data representation.
     6 */
     7 
     8 package isabelle
     9 
    10 import java.lang.System
    11 import java.util.WeakHashMap
    12 import java.lang.ref.WeakReference
    13 import javax.xml.parsers.DocumentBuilderFactory
    14 
    15 
    16 object XML
    17 {
    18   /** XML trees **/
    19 
    20   /* datatype representation */
    21 
    22   type Attributes = Properties.T
    23 
    24   sealed abstract class Tree { override def toString = string_of_tree(this) }
    25   case class Elem(markup: Markup, body: List[Tree]) extends Tree
    26   case class Text(content: String) extends Tree
    27 
    28   def elem(name: String, body: List[Tree]) = Elem(Markup(name, Nil), body)
    29   def elem(name: String) = Elem(Markup(name, Nil), Nil)
    30 
    31   type Body = List[Tree]
    32 
    33 
    34   /* string representation */
    35 
    36   def string_of_body(body: Body): String =
    37   {
    38     val s = new StringBuilder
    39 
    40     def text(txt: String) {
    41       if (txt == null) s ++= txt
    42       else {
    43         for (c <- txt.iterator) c match {
    44           case '<' => s ++= "&lt;"
    45           case '>' => s ++= "&gt;"
    46           case '&' => s ++= "&amp;"
    47           case '"' => s ++= "&quot;"
    48           case '\'' => s ++= "&apos;"
    49           case _ => s += c
    50         }
    51       }
    52     }
    53     def attrib(p: (String, String)) { s ++= " "; s ++= p._1; s ++= "=\""; text(p._2); s ++= "\"" }
    54     def elem(markup: Markup) { s ++= markup.name; markup.properties.foreach(attrib) }
    55     def tree(t: Tree): Unit =
    56       t match {
    57         case Elem(markup, Nil) =>
    58           s ++= "<"; elem(markup); s ++= "/>"
    59         case Elem(markup, ts) =>
    60           s ++= "<"; elem(markup); s ++= ">"
    61           ts.foreach(tree)
    62           s ++= "</"; s ++= markup.name; s ++= ">"
    63         case Text(txt) => text(txt)
    64       }
    65     body.foreach(tree)
    66     s.toString
    67   }
    68 
    69   def string_of_tree(tree: XML.Tree): String = string_of_body(List(tree))
    70 
    71 
    72   /* content -- text and markup */
    73 
    74   private def make_content(body: Body, record_markup: Boolean): (String, Markup_Tree) =
    75   {
    76     var text = new StringBuilder
    77     var markup_tree = Markup_Tree.empty
    78 
    79     def traverse(tree: Tree): Unit =
    80       tree match {
    81         case Elem(markup, trees) =>
    82           val offset = text.length
    83           trees.foreach(traverse)
    84           val end_offset = text.length
    85           if (record_markup)
    86             markup_tree +=
    87               isabelle.Text.Info(isabelle.Text.Range(offset, end_offset), Elem(markup, Nil))
    88         case Text(s) => text.append(s)
    89       }
    90 
    91     body.foreach(traverse)
    92     (text.toString, markup_tree.reverse_markup)
    93   }
    94 
    95   def content_markup(body: Body): (String, Markup_Tree) = make_content(body, true)
    96   def content(body: Body): String = make_content(body, false)._1
    97   def content(tree: Tree): String = make_content(List(tree), false)._1
    98 
    99 
   100 
   101   /** cache for partial sharing (weak table) **/
   102 
   103   class Cache(initial_size: Int = 131071, max_string: Int = 100)
   104   {
   105     private var table = new WeakHashMap[Any, WeakReference[Any]](initial_size)
   106 
   107     private def lookup[A](x: A): Option[A] =
   108     {
   109       val ref = table.get(x)
   110       if (ref == null) None
   111       else {
   112         val y = ref.asInstanceOf[WeakReference[A]].get
   113         if (y == null) None
   114         else Some(y)
   115       }
   116     }
   117     private def store[A](x: A): A =
   118     {
   119       table.put(x, new WeakReference[Any](x))
   120       x
   121     }
   122 
   123     private def trim_bytes(s: String): String = new String(s.toCharArray)
   124 
   125     private def _cache_string(x: String): String =
   126       lookup(x) match {
   127         case Some(y) => y
   128         case None =>
   129           val z = trim_bytes(x)
   130           if (z.length > max_string) z else store(z)
   131       }
   132     private def _cache_props(x: Properties.T): Properties.T =
   133       if (x.isEmpty) x
   134       else
   135         lookup(x) match {
   136           case Some(y) => y
   137           case None => store(x.map(p => (trim_bytes(p._1).intern, _cache_string(p._2))))
   138         }
   139     private def _cache_markup(x: Markup): Markup =
   140       lookup(x) match {
   141         case Some(y) => y
   142         case None =>
   143           x match {
   144             case Markup(name, props) =>
   145               store(Markup(_cache_string(name), _cache_props(props)))
   146           }
   147       }
   148     private def _cache_tree(x: XML.Tree): XML.Tree =
   149       lookup(x) match {
   150         case Some(y) => y
   151         case None =>
   152           x match {
   153             case XML.Elem(markup, body) =>
   154               store(XML.Elem(_cache_markup(markup), _cache_body(body)))
   155             case XML.Text(text) => store(XML.Text(_cache_string(text)))
   156           }
   157       }
   158     private def _cache_body(x: XML.Body): XML.Body =
   159       if (x.isEmpty) x
   160       else
   161         lookup(x) match {
   162           case Some(y) => y
   163           case None => x.map(_cache_tree(_))
   164         }
   165 
   166     // main methods
   167     def cache_string(x: String): String = synchronized { _cache_string(x) }
   168     def cache_markup(x: Markup): Markup = synchronized { _cache_markup(x) }
   169     def cache_tree(x: XML.Tree): XML.Tree = synchronized { _cache_tree(x) }
   170     def cache_body(x: XML.Body): XML.Body = synchronized { _cache_body(x) }
   171   }
   172 
   173 
   174 
   175   /** document object model (W3C DOM) **/
   176 
   177   def get_data(node: org.w3c.dom.Node): Option[XML.Tree] =
   178     node.getUserData(Markup.Data.name) match {
   179       case tree: XML.Tree => Some(tree)
   180       case _ => None
   181     }
   182 
   183   def document_node(doc: org.w3c.dom.Document, tree: Tree): org.w3c.dom.Node =
   184   {
   185     def DOM(tr: Tree): org.w3c.dom.Node = tr match {
   186       case Elem(Markup.Data, List(data, t)) =>
   187         val node = DOM(t)
   188         node.setUserData(Markup.Data.name, data, null)
   189         node
   190       case Elem(Markup(name, atts), ts) =>
   191         if (name == Markup.Data.name)
   192           error("Malformed data element: " + tr.toString)
   193         val node = doc.createElement(name)
   194         for ((name, value) <- atts) node.setAttribute(name, value)
   195         for (t <- ts) node.appendChild(DOM(t))
   196         node
   197       case Text(txt) => doc.createTextNode(txt)
   198     }
   199     DOM(tree)
   200   }
   201 
   202 
   203 
   204   /** XML as data representation language **/
   205 
   206   class XML_Atom(s: String) extends Exception(s)
   207   class XML_Body(body: XML.Body) extends Exception
   208 
   209   object Encode
   210   {
   211     type T[A] = A => XML.Body
   212 
   213 
   214     /* atomic values */
   215 
   216     def long_atom(i: Long): String = i.toString
   217 
   218     def int_atom(i: Int): String = i.toString
   219 
   220     def bool_atom(b: Boolean): String = if (b) "1" else "0"
   221 
   222     def unit_atom(u: Unit) = ""
   223 
   224 
   225     /* structural nodes */
   226 
   227     private def node(ts: XML.Body): XML.Tree = XML.Elem(Markup(":", Nil), ts)
   228 
   229     private def vector(xs: List[String]): XML.Attributes =
   230       xs.zipWithIndex.map({ case (x, i) => (int_atom(i), x) })
   231 
   232     private def tagged(tag: Int, data: (List[String], XML.Body)): XML.Tree =
   233       XML.Elem(Markup(int_atom(tag), vector(data._1)), data._2)
   234 
   235 
   236     /* representation of standard types */
   237 
   238     val properties: T[Properties.T] =
   239       (props => List(XML.Elem(Markup(":", props), Nil)))
   240 
   241     val string: T[String] = (s => if (s.isEmpty) Nil else List(XML.Text(s)))
   242 
   243     val long: T[Long] = (x => string(long_atom(x)))
   244 
   245     val int: T[Int] = (x => string(int_atom(x)))
   246 
   247     val bool: T[Boolean] = (x => string(bool_atom(x)))
   248 
   249     val unit: T[Unit] = (x => string(unit_atom(x)))
   250 
   251     def pair[A, B](f: T[A], g: T[B]): T[(A, B)] =
   252       (x => List(node(f(x._1)), node(g(x._2))))
   253 
   254     def triple[A, B, C](f: T[A], g: T[B], h: T[C]): T[(A, B, C)] =
   255       (x => List(node(f(x._1)), node(g(x._2)), node(h(x._3))))
   256 
   257     def list[A](f: T[A]): T[List[A]] =
   258       (xs => xs.map((x: A) => node(f(x))))
   259 
   260     def option[A](f: T[A]): T[Option[A]] =
   261     {
   262       case None => Nil
   263       case Some(x) => List(node(f(x)))
   264     }
   265 
   266     def variant[A](fs: List[PartialFunction[A, (List[String], XML.Body)]]): T[A] =
   267     {
   268       case x =>
   269         val (f, tag) = fs.iterator.zipWithIndex.find(p => p._1.isDefinedAt(x)).get
   270         List(tagged(tag, f(x)))
   271     }
   272   }
   273 
   274   object Decode
   275   {
   276     type T[A] = XML.Body => A
   277     type V[A] = (List[String], XML.Body) => A
   278 
   279 
   280     /* atomic values */
   281 
   282     def long_atom(s: String): Long =
   283       try { java.lang.Long.parseLong(s) }
   284       catch { case e: NumberFormatException => throw new XML_Atom(s) }
   285 
   286     def int_atom(s: String): Int =
   287       try { Integer.parseInt(s) }
   288       catch { case e: NumberFormatException => throw new XML_Atom(s) }
   289 
   290     def bool_atom(s: String): Boolean =
   291       if (s == "1") true
   292       else if (s == "0") false
   293       else throw new XML_Atom(s)
   294 
   295     def unit_atom(s: String): Unit =
   296       if (s == "") () else throw new XML_Atom(s)
   297 
   298 
   299     /* structural nodes */
   300 
   301     private def node(t: XML.Tree): XML.Body =
   302       t match {
   303         case XML.Elem(Markup(":", Nil), ts) => ts
   304         case _ => throw new XML_Body(List(t))
   305       }
   306 
   307     private def vector(atts: XML.Attributes): List[String] =
   308       atts.iterator.zipWithIndex.map(
   309         { case ((a, x), i) => if (int_atom(a) == i) x else throw new XML_Atom(a) }).toList
   310 
   311     private def tagged(t: XML.Tree): (Int, (List[String], XML.Body)) =
   312       t match {
   313         case XML.Elem(Markup(name, atts), ts) => (int_atom(name), (vector(atts), ts))
   314         case _ => throw new XML_Body(List(t))
   315       }
   316 
   317 
   318     /* representation of standard types */
   319 
   320     val properties: T[Properties.T] =
   321     {
   322       case List(XML.Elem(Markup(":", props), Nil)) => props
   323       case ts => throw new XML_Body(ts)
   324     }
   325 
   326     val string: T[String] =
   327     {
   328       case Nil => ""
   329       case List(XML.Text(s)) => s
   330       case ts => throw new XML_Body(ts)
   331     }
   332 
   333     val long: T[Long] = (x => long_atom(string(x)))
   334 
   335     val int: T[Int] = (x => int_atom(string(x)))
   336 
   337     val bool: T[Boolean] = (x => bool_atom(string(x)))
   338 
   339     val unit: T[Unit] = (x => unit_atom(string(x)))
   340 
   341     def pair[A, B](f: T[A], g: T[B]): T[(A, B)] =
   342     {
   343       case List(t1, t2) => (f(node(t1)), g(node(t2)))
   344       case ts => throw new XML_Body(ts)
   345     }
   346 
   347     def triple[A, B, C](f: T[A], g: T[B], h: T[C]): T[(A, B, C)] =
   348     {
   349       case List(t1, t2, t3) => (f(node(t1)), g(node(t2)), h(node(t3)))
   350       case ts => throw new XML_Body(ts)
   351     }
   352 
   353     def list[A](f: T[A]): T[List[A]] =
   354       (ts => ts.map(t => f(node(t))))
   355 
   356     def option[A](f: T[A]): T[Option[A]] =
   357     {
   358       case Nil => None
   359       case List(t) => Some(f(node(t)))
   360       case ts => throw new XML_Body(ts)
   361     }
   362 
   363     def variant[A](fs: List[V[A]]): T[A] =
   364     {
   365       case List(t) =>
   366         val (tag, (xs, ts)) = tagged(t)
   367         val f =
   368           try { fs(tag) }
   369           catch { case _: IndexOutOfBoundsException => throw new XML_Body(List(t)) }
   370         f(xs, ts)
   371       case ts => throw new XML_Body(ts)
   372     }
   373   }
   374 }