src/Pure/PIDE/xml.scala
author wenzelm
Tue Apr 09 20:27:27 2013 +0200 (2013-04-09 ago)
changeset 51663 098f3cf6c809
parent 51223 c6a8a05ff0a0
child 51987 7d8e0e3c553b
permissions -rw-r--r--
tuned signature;
     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.util.WeakHashMap
    11 import java.lang.ref.WeakReference
    12 import javax.xml.parsers.DocumentBuilderFactory
    13 
    14 
    15 object XML
    16 {
    17   /** XML trees **/
    18 
    19   /* datatype representation */
    20 
    21   type Attributes = Properties.T
    22 
    23   sealed abstract class Tree { override def toString = string_of_tree(this) }
    24   case class Elem(markup: Markup, body: List[Tree]) extends Tree
    25   case class Text(content: String) extends Tree
    26 
    27   def elem(name: String, body: List[Tree]) = Elem(Markup(name, Nil), body)
    28   def elem(name: String) = Elem(Markup(name, Nil), Nil)
    29 
    30   type Body = List[Tree]
    31 
    32 
    33   /* wrapped elements */
    34 
    35   val XML_ELEM = "xml_elem";
    36   val XML_NAME = "xml_name";
    37   val XML_BODY = "xml_body";
    38 
    39   object Wrapped_Elem
    40   {
    41     def apply(markup: Markup, body1: Body, body2: Body): XML.Elem =
    42       Elem(Markup(XML_ELEM, (XML_NAME, markup.name) :: markup.properties),
    43         Elem(Markup(XML_BODY, Nil), body1) :: body2)
    44 
    45     def unapply(tree: Tree): Option[(Markup, Body, Body)] =
    46       tree match {
    47         case
    48           Elem(Markup(XML_ELEM, (XML_NAME, name) :: props),
    49             Elem(Markup(XML_BODY, Nil), body1) :: body2) =>
    50           Some(Markup(name, props), body1, body2)
    51         case _ => None
    52       }
    53   }
    54 
    55 
    56   /* traverse text */
    57 
    58   def traverse_text[A](body: Body)(a: A)(op: (A, String) => A): A =
    59   {
    60     def traverse(x: A, t: Tree): A =
    61       t match {
    62         case Wrapped_Elem(_, _, ts) => (x /: ts)(traverse)
    63         case Elem(_, ts) => (x /: ts)(traverse)
    64         case Text(s) => op(x, s)
    65       }
    66     (a /: body)(traverse)
    67   }
    68 
    69   def text_length(body: Body): Int = traverse_text(body)(0) { case (n, s) => n + s.length }
    70 
    71 
    72   /* text content */
    73 
    74   def content(body: Body): String =
    75   {
    76     val text = new StringBuilder(text_length(body))
    77     traverse_text(body)(()) { case (_, s) => text.append(s) }
    78     text.toString
    79   }
    80 
    81   def content(tree: Tree): String = content(List(tree))
    82 
    83 
    84 
    85   /** string representation **/
    86 
    87   def string_of_body(body: Body): String =
    88   {
    89     val s = new StringBuilder
    90 
    91     def text(txt: String) {
    92       if (txt == null) s ++= txt
    93       else {
    94         for (c <- txt.iterator) c match {
    95           case '<' => s ++= "&lt;"
    96           case '>' => s ++= "&gt;"
    97           case '&' => s ++= "&amp;"
    98           case '"' => s ++= "&quot;"
    99           case '\'' => s ++= "&apos;"
   100           case _ => s += c
   101         }
   102       }
   103     }
   104     def attrib(p: (String, String)) { s ++= " "; s ++= p._1; s ++= "=\""; text(p._2); s ++= "\"" }
   105     def elem(markup: Markup) { s ++= markup.name; markup.properties.foreach(attrib) }
   106     def tree(t: Tree): Unit =
   107       t match {
   108         case Elem(markup, Nil) =>
   109           s ++= "<"; elem(markup); s ++= "/>"
   110         case Elem(markup, ts) =>
   111           s ++= "<"; elem(markup); s ++= ">"
   112           ts.foreach(tree)
   113           s ++= "</"; s ++= markup.name; s ++= ">"
   114         case Text(txt) => text(txt)
   115       }
   116     body.foreach(tree)
   117     s.toString
   118   }
   119 
   120   def string_of_tree(tree: XML.Tree): String = string_of_body(List(tree))
   121 
   122 
   123 
   124   /** cache for partial sharing (weak table) **/
   125 
   126   class Cache(initial_size: Int = 131071, max_string: Int = 100)
   127   {
   128     private var table = new WeakHashMap[Any, WeakReference[Any]](initial_size)
   129 
   130     private def lookup[A](x: A): Option[A] =
   131     {
   132       val ref = table.get(x)
   133       if (ref == null) None
   134       else {
   135         val y = ref.asInstanceOf[WeakReference[A]].get
   136         if (y == null) None
   137         else Some(y)
   138       }
   139     }
   140     private def store[A](x: A): A =
   141     {
   142       table.put(x, new WeakReference[Any](x))
   143       x
   144     }
   145 
   146     private def trim_bytes(s: String): String = new String(s.toCharArray)
   147 
   148     private def cache_string(x: String): String =
   149       lookup(x) match {
   150         case Some(y) => y
   151         case None =>
   152           val z = trim_bytes(x)
   153           if (z.length > max_string) z else store(z)
   154       }
   155     private def cache_props(x: Properties.T): Properties.T =
   156       if (x.isEmpty) x
   157       else
   158         lookup(x) match {
   159           case Some(y) => y
   160           case None => store(x.map(p => (trim_bytes(p._1).intern, cache_string(p._2))))
   161         }
   162     private def cache_markup(x: Markup): Markup =
   163       lookup(x) match {
   164         case Some(y) => y
   165         case None =>
   166           x match {
   167             case Markup(name, props) =>
   168               store(Markup(cache_string(name), cache_props(props)))
   169           }
   170       }
   171     private def cache_tree(x: XML.Tree): XML.Tree =
   172       lookup(x) match {
   173         case Some(y) => y
   174         case None =>
   175           x match {
   176             case XML.Elem(markup, body) =>
   177               store(XML.Elem(cache_markup(markup), cache_body(body)))
   178             case XML.Text(text) => store(XML.Text(cache_string(text)))
   179           }
   180       }
   181     private def cache_body(x: XML.Body): XML.Body =
   182       if (x.isEmpty) x
   183       else
   184         lookup(x) match {
   185           case Some(y) => y
   186           case None => x.map(cache_tree(_))
   187         }
   188 
   189     // main methods
   190     def string(x: String): String = synchronized { cache_string(x) }
   191     def props(x: Properties.T): Properties.T = synchronized { cache_props(x) }
   192     def markup(x: Markup): Markup = synchronized { cache_markup(x) }
   193     def tree(x: XML.Tree): XML.Tree = synchronized { cache_tree(x) }
   194     def body(x: XML.Body): XML.Body = synchronized { cache_body(x) }
   195     def elem(x: XML.Elem): XML.Elem = synchronized { cache_tree(x).asInstanceOf[XML.Elem] }
   196   }
   197 
   198 
   199 
   200   /** XML as data representation language **/
   201 
   202   class XML_Atom(s: String) extends Exception(s)
   203   class XML_Body(body: XML.Body) extends Exception
   204 
   205   object Encode
   206   {
   207     type T[A] = A => XML.Body
   208 
   209 
   210     /* atomic values */
   211 
   212     def long_atom(i: Long): String = i.toString
   213 
   214     def int_atom(i: Int): String = i.toString
   215 
   216     def bool_atom(b: Boolean): String = if (b) "1" else "0"
   217 
   218     def unit_atom(u: Unit) = ""
   219 
   220 
   221     /* structural nodes */
   222 
   223     private def node(ts: XML.Body): XML.Tree = XML.Elem(Markup(":", Nil), ts)
   224 
   225     private def vector(xs: List[String]): XML.Attributes =
   226       xs.zipWithIndex.map({ case (x, i) => (int_atom(i), x) })
   227 
   228     private def tagged(tag: Int, data: (List[String], XML.Body)): XML.Tree =
   229       XML.Elem(Markup(int_atom(tag), vector(data._1)), data._2)
   230 
   231 
   232     /* representation of standard types */
   233 
   234     val properties: T[Properties.T] =
   235       (props => List(XML.Elem(Markup(":", props), Nil)))
   236 
   237     val string: T[String] = (s => if (s.isEmpty) Nil else List(XML.Text(s)))
   238 
   239     val long: T[Long] = (x => string(long_atom(x)))
   240 
   241     val int: T[Int] = (x => string(int_atom(x)))
   242 
   243     val bool: T[Boolean] = (x => string(bool_atom(x)))
   244 
   245     val unit: T[Unit] = (x => string(unit_atom(x)))
   246 
   247     def pair[A, B](f: T[A], g: T[B]): T[(A, B)] =
   248       (x => List(node(f(x._1)), node(g(x._2))))
   249 
   250     def triple[A, B, C](f: T[A], g: T[B], h: T[C]): T[(A, B, C)] =
   251       (x => List(node(f(x._1)), node(g(x._2)), node(h(x._3))))
   252 
   253     def list[A](f: T[A]): T[List[A]] =
   254       (xs => xs.map((x: A) => node(f(x))))
   255 
   256     def option[A](f: T[A]): T[Option[A]] =
   257     {
   258       case None => Nil
   259       case Some(x) => List(node(f(x)))
   260     }
   261 
   262     def variant[A](fs: List[PartialFunction[A, (List[String], XML.Body)]]): T[A] =
   263     {
   264       case x =>
   265         val (f, tag) = fs.iterator.zipWithIndex.find(p => p._1.isDefinedAt(x)).get
   266         List(tagged(tag, f(x)))
   267     }
   268   }
   269 
   270   object Decode
   271   {
   272     type T[A] = XML.Body => A
   273     type V[A] = (List[String], XML.Body) => A
   274 
   275 
   276     /* atomic values */
   277 
   278     def long_atom(s: String): Long =
   279       try { java.lang.Long.parseLong(s) }
   280       catch { case e: NumberFormatException => throw new XML_Atom(s) }
   281 
   282     def int_atom(s: String): Int =
   283       try { Integer.parseInt(s) }
   284       catch { case e: NumberFormatException => throw new XML_Atom(s) }
   285 
   286     def bool_atom(s: String): Boolean =
   287       if (s == "1") true
   288       else if (s == "0") false
   289       else throw new XML_Atom(s)
   290 
   291     def unit_atom(s: String): Unit =
   292       if (s == "") () else throw new XML_Atom(s)
   293 
   294 
   295     /* structural nodes */
   296 
   297     private def node(t: XML.Tree): XML.Body =
   298       t match {
   299         case XML.Elem(Markup(":", Nil), ts) => ts
   300         case _ => throw new XML_Body(List(t))
   301       }
   302 
   303     private def vector(atts: XML.Attributes): List[String] =
   304       atts.iterator.zipWithIndex.map(
   305         { case ((a, x), i) => if (int_atom(a) == i) x else throw new XML_Atom(a) }).toList
   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 }