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