src/Pure/PIDE/xml.ML
author wenzelm
Mon Mar 13 21:37:35 2017 +0100 (2017-03-13 ago)
changeset 65214 a2ec0db555c7
parent 63806 c54a53ef1873
child 65333 289561ca4fa3
permissions -rw-r--r--
clarified modules;
     1 (*  Title:      Pure/PIDE/xml.ML
     2     Author:     David Aspinall
     3     Author:     Stefan Berghofer
     4     Author:     Makarius
     5 
     6 Untyped XML trees and representation of ML values.
     7 *)
     8 
     9 signature XML_DATA_OPS =
    10 sig
    11   type 'a A
    12   type 'a T
    13   type 'a V
    14   val int_atom: int A
    15   val bool_atom: bool A
    16   val unit_atom: unit A
    17   val properties: Properties.T T
    18   val string: string T
    19   val int: int T
    20   val bool: bool T
    21   val unit: unit T
    22   val pair: 'a T -> 'b T -> ('a * 'b) T
    23   val triple: 'a T -> 'b T -> 'c T -> ('a * 'b * 'c) T
    24   val list: 'a T -> 'a list T
    25   val option: 'a T -> 'a option T
    26   val variant: 'a V list -> 'a T
    27 end;
    28 
    29 signature XML =
    30 sig
    31   type attributes = (string * string) list
    32   datatype tree =
    33       Elem of (string * attributes) * tree list
    34     | Text of string
    35   type body = tree list
    36   val wrap_elem: ((string * attributes) * tree list) * tree list -> tree
    37   val unwrap_elem: tree -> (((string * attributes) * tree list) * tree list) option
    38   val add_content: tree -> Buffer.T -> Buffer.T
    39   val content_of: body -> string
    40   val trim_blanks: body -> body
    41   val header: string
    42   val text: string -> string
    43   val element: string -> attributes -> string list -> string
    44   val output_markup: Markup.T -> Output.output * Output.output
    45   val string_of: tree -> string
    46   val pretty: int -> tree -> Pretty.T
    47   val output: tree -> BinIO.outstream -> unit
    48   val parse_comments: string list -> unit * string list
    49   val parse_string : string -> string option
    50   val parse_element: string list -> tree * string list
    51   val parse_document: string list -> tree * string list
    52   val parse: string -> tree
    53   exception XML_ATOM of string
    54   exception XML_BODY of body
    55   structure Encode: XML_DATA_OPS
    56   structure Decode: XML_DATA_OPS
    57 end;
    58 
    59 structure XML: XML =
    60 struct
    61 
    62 (** XML trees **)
    63 
    64 type attributes = (string * string) list;
    65 
    66 datatype tree =
    67     Elem of (string * attributes) * tree list
    68   | Text of string;
    69 
    70 type body = tree list;
    71 
    72 
    73 (* wrapped elements *)
    74 
    75 val xml_elemN = "xml_elem";
    76 val xml_nameN = "xml_name";
    77 val xml_bodyN = "xml_body";
    78 
    79 fun wrap_elem (((a, atts), body1), body2) =
    80   Elem ((xml_elemN, (xml_nameN, a) :: atts), Elem ((xml_bodyN, []), body1) :: body2);
    81 
    82 fun unwrap_elem (Elem ((name, (n, a) :: atts), Elem ((name', atts'), body1) :: body2)) =
    83       if name = xml_elemN andalso n = xml_nameN andalso name' = xml_bodyN andalso null atts'
    84       then SOME (((a, atts), body1), body2) else NONE
    85   | unwrap_elem _ = NONE;
    86 
    87 
    88 (* text context *)
    89 
    90 fun add_content tree =
    91   (case unwrap_elem tree of
    92     SOME (_, ts) => fold add_content ts
    93   | NONE =>
    94       (case tree of
    95         Elem (_, ts) => fold add_content ts
    96       | Text s => Buffer.add s));
    97 
    98 fun content_of body = Buffer.empty |> fold add_content body |> Buffer.content;
    99 
   100 
   101 (* trim blanks *)
   102 
   103 fun trim_blanks trees =
   104   trees |> maps
   105     (fn Elem (markup, body) => [Elem (markup, trim_blanks body)]
   106       | Text s =>
   107           let val s' = s |> raw_explode |> trim Symbol.is_blank |> implode;
   108           in if s' = "" then [] else [Text s'] end);
   109 
   110 
   111 
   112 (** string representation **)
   113 
   114 val header = "<?xml version=\"1.0\"?>\n";
   115 
   116 
   117 (* escaped text *)
   118 
   119 fun decode "&lt;" = "<"
   120   | decode "&gt;" = ">"
   121   | decode "&amp;" = "&"
   122   | decode "&apos;" = "'"
   123   | decode "&quot;" = "\""
   124   | decode c = c;
   125 
   126 fun encode "<" = "&lt;"
   127   | encode ">" = "&gt;"
   128   | encode "&" = "&amp;"
   129   | encode "'" = "&apos;"
   130   | encode "\"" = "&quot;"
   131   | encode c = c;
   132 
   133 val text = translate_string encode;
   134 
   135 
   136 (* elements *)
   137 
   138 fun elem name atts =
   139   space_implode " " (name :: map (fn (a, x) => a ^ "=\"" ^ text x ^ "\"") atts);
   140 
   141 fun element name atts body =
   142   let val b = implode body in
   143     if b = "" then enclose "<" "/>" (elem name atts)
   144     else enclose "<" ">" (elem name atts) ^ b ^ enclose "</" ">" name
   145   end;
   146 
   147 fun output_markup (markup as (name, atts)) =
   148   if Markup.is_empty markup then Markup.no_output
   149   else (enclose "<" ">" (elem name atts), enclose "</" ">" name);
   150 
   151 
   152 (* output *)
   153 
   154 fun buffer_of depth tree =
   155   let
   156     fun traverse _ (Elem ((name, atts), [])) =
   157           Buffer.add "<" #> Buffer.add (elem name atts) #> Buffer.add "/>"
   158       | traverse d (Elem ((name, atts), ts)) =
   159           Buffer.add "<" #> Buffer.add (elem name atts) #> Buffer.add ">" #>
   160           traverse_body d ts #>
   161           Buffer.add "</" #> Buffer.add name #> Buffer.add ">"
   162       | traverse _ (Text s) = Buffer.add (text s)
   163     and traverse_body 0 _ = Buffer.add "..."
   164       | traverse_body d ts = fold (traverse (d - 1)) ts;
   165   in Buffer.empty |> traverse depth tree end;
   166 
   167 val string_of = Buffer.content o buffer_of ~1;
   168 val output = Buffer.output o buffer_of ~1;
   169 
   170 fun pretty depth tree =
   171   Pretty.str (Buffer.content (buffer_of (Int.max (0, depth)) tree));
   172 
   173 val _ = ML_system_pp (fn depth => fn _ => Pretty.to_polyml o pretty (FixedInt.toInt depth));
   174 
   175 
   176 
   177 (** XML parsing **)
   178 
   179 local
   180 
   181 fun err msg (xs, _) =
   182   fn () => "XML parsing error: " ^ msg () ^ "\nfound: " ^ quote (Symbol.beginning 100 xs);
   183 
   184 fun ignored _ = [];
   185 
   186 fun name_start_char c = Symbol.is_ascii_letter c orelse c = ":" orelse c = "_";
   187 fun name_char c = name_start_char c orelse Symbol.is_ascii_digit c orelse c = "-" orelse c = ".";
   188 val parse_name = Scan.one name_start_char ::: Scan.many name_char;
   189 
   190 val blanks = Scan.many Symbol.is_blank;
   191 val special = $$ "&" ^^ (parse_name >> implode) ^^ $$ ";" >> decode;
   192 val regular = Scan.one Symbol.not_eof;
   193 fun regular_except x = Scan.one (fn c => Symbol.not_eof c andalso c <> x);
   194 
   195 val parse_chars = Scan.repeat1 (special || regular_except "<") >> implode;
   196 
   197 val parse_cdata =
   198   Scan.this_string "<![CDATA[" |--
   199   (Scan.repeat (Scan.unless (Scan.this_string "]]>") regular) >> implode) --|
   200   Scan.this_string "]]>";
   201 
   202 val parse_att =
   203   ((parse_name >> implode) --| (blanks -- $$ "=" -- blanks)) --
   204   (($$ "\"" || $$ "'") :|-- (fn s =>
   205     (Scan.repeat (special || regular_except s) >> implode) --| $$ s));
   206 
   207 val parse_comment =
   208   Scan.this_string "<!--" --
   209   Scan.repeat (Scan.unless (Scan.this_string "-->") regular) --
   210   Scan.this_string "-->" >> ignored;
   211 
   212 val parse_processing_instruction =
   213   Scan.this_string "<?" --
   214   Scan.repeat (Scan.unless (Scan.this_string "?>") regular) --
   215   Scan.this_string "?>" >> ignored;
   216 
   217 val parse_doctype =
   218   Scan.this_string "<!DOCTYPE" --
   219   Scan.repeat (Scan.unless ($$ ">") regular) --
   220   $$ ">" >> ignored;
   221 
   222 val parse_misc =
   223   Scan.one Symbol.is_blank >> ignored ||
   224   parse_processing_instruction ||
   225   parse_comment;
   226 
   227 val parse_optional_text =
   228   Scan.optional (parse_chars >> (single o Text)) [];
   229 
   230 in
   231 
   232 val parse_comments =
   233   blanks -- Scan.repeat (parse_comment -- blanks >> K ()) >> K ();
   234 
   235 val parse_string = Scan.read Symbol.stopper parse_chars o raw_explode;
   236 
   237 fun parse_content xs =
   238   (parse_optional_text @@@
   239     Scan.repeats
   240       ((parse_element >> single ||
   241         parse_cdata >> (single o Text) ||
   242         parse_processing_instruction ||
   243         parse_comment)
   244       @@@ parse_optional_text)) xs
   245 
   246 and parse_element xs =
   247   ($$ "<" |-- parse_name -- Scan.repeat (blanks |-- parse_att) --| blanks :--
   248     (fn (name, _) =>
   249       !! (err (fn () => "Expected > or />"))
   250        ($$ "/" -- $$ ">" >> ignored ||
   251         $$ ">" |-- parse_content --|
   252           !! (err (fn () => "Expected </" ^ implode name ^ ">"))
   253               ($$ "<" -- $$ "/" -- Scan.this name -- blanks -- $$ ">")))
   254     >> (fn ((name, atts), body) => Elem ((implode name, atts), body))) xs;
   255 
   256 val parse_document =
   257   (Scan.repeat parse_misc -- Scan.option parse_doctype -- Scan.repeat parse_misc)
   258   |-- parse_element;
   259 
   260 fun parse s =
   261   (case Scan.finite Symbol.stopper (Scan.error (!! (err (fn () => "Malformed element"))
   262       (blanks |-- parse_document --| blanks))) (raw_explode s) of
   263     (x, []) => x
   264   | (_, ys) => error ("XML parsing error: unprocessed input\n" ^ Symbol.beginning 100 ys));
   265 
   266 end;
   267 
   268 
   269 
   270 (** XML as data representation language **)
   271 
   272 exception XML_ATOM of string;
   273 exception XML_BODY of tree list;
   274 
   275 
   276 structure Encode =
   277 struct
   278 
   279 type 'a A = 'a -> string;
   280 type 'a T = 'a -> body;
   281 type 'a V = 'a -> string list * body;
   282 
   283 
   284 (* atomic values *)
   285 
   286 fun int_atom i = signed_string_of_int i;
   287 
   288 fun bool_atom false = "0"
   289   | bool_atom true = "1";
   290 
   291 fun unit_atom () = "";
   292 
   293 
   294 (* structural nodes *)
   295 
   296 fun node ts = Elem ((":", []), ts);
   297 
   298 fun vector xs = map_index (fn (i, x) => (int_atom i, x)) xs;
   299 
   300 fun tagged (tag, (xs, ts)) = Elem ((int_atom tag, vector xs), ts);
   301 
   302 
   303 (* representation of standard types *)
   304 
   305 fun properties props = [Elem ((":", props), [])];
   306 
   307 fun string "" = []
   308   | string s = [Text s];
   309 
   310 val int = string o int_atom;
   311 
   312 val bool = string o bool_atom;
   313 
   314 val unit = string o unit_atom;
   315 
   316 fun pair f g (x, y) = [node (f x), node (g y)];
   317 
   318 fun triple f g h (x, y, z) = [node (f x), node (g y), node (h z)];
   319 
   320 fun list f xs = map (node o f) xs;
   321 
   322 fun option _ NONE = []
   323   | option f (SOME x) = [node (f x)];
   324 
   325 fun variant fs x =
   326   [tagged (the (get_index (fn f => SOME (f x) handle General.Match => NONE) fs))];
   327 
   328 end;
   329 
   330 
   331 structure Decode =
   332 struct
   333 
   334 type 'a A = string -> 'a;
   335 type 'a T = body -> 'a;
   336 type 'a V = string list * body -> 'a;
   337 
   338 
   339 (* atomic values *)
   340 
   341 fun int_atom s =
   342   Value.parse_int s
   343     handle Fail _ => raise XML_ATOM s;
   344 
   345 fun bool_atom "0" = false
   346   | bool_atom "1" = true
   347   | bool_atom s = raise XML_ATOM s;
   348 
   349 fun unit_atom "" = ()
   350   | unit_atom s = raise XML_ATOM s;
   351 
   352 
   353 (* structural nodes *)
   354 
   355 fun node (Elem ((":", []), ts)) = ts
   356   | node t = raise XML_BODY [t];
   357 
   358 fun vector atts =
   359   map_index (fn (i, (a, x)) => if int_atom a = i then x else raise XML_ATOM a) atts;
   360 
   361 fun tagged (Elem ((name, atts), ts)) = (int_atom name, (vector atts, ts))
   362   | tagged t = raise XML_BODY [t];
   363 
   364 
   365 (* representation of standard types *)
   366 
   367 fun properties [Elem ((":", props), [])] = props
   368   | properties ts = raise XML_BODY ts;
   369 
   370 fun string [] = ""
   371   | string [Text s] = s
   372   | string ts = raise XML_BODY ts;
   373 
   374 val int = int_atom o string;
   375 
   376 val bool = bool_atom o string;
   377 
   378 val unit = unit_atom o string;
   379 
   380 fun pair f g [t1, t2] = (f (node t1), g (node t2))
   381   | pair _ _ ts = raise XML_BODY ts;
   382 
   383 fun triple f g h [t1, t2, t3] = (f (node t1), g (node t2), h (node t3))
   384   | triple _ _ _ ts = raise XML_BODY ts;
   385 
   386 fun list f ts = map (f o node) ts;
   387 
   388 fun option _ [] = NONE
   389   | option f [t] = SOME (f (node t))
   390   | option _ ts = raise XML_BODY ts;
   391 
   392 fun variant fs [t] =
   393       let
   394         val (tag, (xs, ts)) = tagged t;
   395         val f = nth fs tag handle General.Subscript => raise XML_BODY [t];
   396       in f (xs, ts) end
   397   | variant _ ts = raise XML_BODY ts;
   398 
   399 end;
   400 
   401 end;