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