src/Pure/PIDE/xml.ML
author wenzelm
Wed Dec 03 14:04:38 2014 +0100 (2014-12-03 ago)
changeset 59083 88b0b1f28adc
parent 58854 b979c781c2db
child 60982 67e389f67073
permissions -rw-r--r--
tuned signature;
     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 -> TextIO.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
   108             val s' = s
   109               |> raw_explode
   110               |> take_prefix Symbol.is_blank |> #2
   111               |> take_suffix Symbol.is_blank |> #1
   112               |> implode;
   113           in if s' = "" then [] else [Text s'] end);
   114 
   115 
   116 
   117 (** string representation **)
   118 
   119 val header = "<?xml version=\"1.0\"?>\n";
   120 
   121 
   122 (* escaped text *)
   123 
   124 fun decode "&lt;" = "<"
   125   | decode "&gt;" = ">"
   126   | decode "&amp;" = "&"
   127   | decode "&apos;" = "'"
   128   | decode "&quot;" = "\""
   129   | decode c = c;
   130 
   131 fun encode "<" = "&lt;"
   132   | encode ">" = "&gt;"
   133   | encode "&" = "&amp;"
   134   | encode "'" = "&apos;"
   135   | encode "\"" = "&quot;"
   136   | encode c = c;
   137 
   138 val text = translate_string encode;
   139 
   140 
   141 (* elements *)
   142 
   143 fun elem name atts =
   144   space_implode " " (name :: map (fn (a, x) => a ^ "=\"" ^ text x ^ "\"") atts);
   145 
   146 fun element name atts body =
   147   let val b = implode body in
   148     if b = "" then enclose "<" "/>" (elem name atts)
   149     else enclose "<" ">" (elem name atts) ^ b ^ enclose "</" ">" name
   150   end;
   151 
   152 fun output_markup (markup as (name, atts)) =
   153   if Markup.is_empty markup then Markup.no_output
   154   else (enclose "<" ">" (elem name atts), enclose "</" ">" name);
   155 
   156 
   157 (* output *)
   158 
   159 fun buffer_of depth tree =
   160   let
   161     fun traverse _ (Elem ((name, atts), [])) =
   162           Buffer.add "<" #> Buffer.add (elem name atts) #> Buffer.add "/>"
   163       | traverse d (Elem ((name, atts), ts)) =
   164           Buffer.add "<" #> Buffer.add (elem name atts) #> Buffer.add ">" #>
   165           traverse_body d ts #>
   166           Buffer.add "</" #> Buffer.add name #> Buffer.add ">"
   167       | traverse _ (Text s) = Buffer.add (text s)
   168     and traverse_body 0 _ = Buffer.add "..."
   169       | traverse_body d ts = fold (traverse (d - 1)) ts;
   170   in Buffer.empty |> traverse depth tree end;
   171 
   172 val string_of = Buffer.content o buffer_of ~1;
   173 val output = Buffer.output o buffer_of ~1;
   174 
   175 fun pretty depth tree =
   176   Pretty.str (Buffer.content (buffer_of (Int.max (0, depth)) tree));
   177 
   178 
   179 
   180 (** XML parsing **)
   181 
   182 local
   183 
   184 fun err msg (xs, _) =
   185   fn () => "XML parsing error: " ^ msg () ^ "\nfound: " ^ quote (Symbol.beginning 100 xs);
   186 
   187 fun ignored _ = [];
   188 
   189 fun name_start_char c = Symbol.is_ascii_letter c orelse c = ":" orelse c = "_";
   190 fun name_char c = name_start_char c orelse Symbol.is_ascii_digit c orelse c = "-" orelse c = ".";
   191 val parse_name = Scan.one name_start_char ::: Scan.many name_char;
   192 
   193 val blanks = Scan.many Symbol.is_blank;
   194 val special = $$ "&" ^^ (parse_name >> implode) ^^ $$ ";" >> decode;
   195 val regular = Scan.one Symbol.not_eof;
   196 fun regular_except x = Scan.one (fn c => Symbol.not_eof c andalso c <> x);
   197 
   198 val parse_chars = Scan.repeat1 (special || regular_except "<") >> implode;
   199 
   200 val parse_cdata =
   201   Scan.this_string "<![CDATA[" |--
   202   (Scan.repeat (Scan.unless (Scan.this_string "]]>") regular) >> implode) --|
   203   Scan.this_string "]]>";
   204 
   205 val parse_att =
   206   ((parse_name >> implode) --| (blanks -- $$ "=" -- blanks)) --
   207   (($$ "\"" || $$ "'") :|-- (fn s =>
   208     (Scan.repeat (special || regular_except s) >> implode) --| $$ s));
   209 
   210 val parse_comment =
   211   Scan.this_string "<!--" --
   212   Scan.repeat (Scan.unless (Scan.this_string "-->") regular) --
   213   Scan.this_string "-->" >> ignored;
   214 
   215 val parse_processing_instruction =
   216   Scan.this_string "<?" --
   217   Scan.repeat (Scan.unless (Scan.this_string "?>") regular) --
   218   Scan.this_string "?>" >> ignored;
   219 
   220 val parse_doctype =
   221   Scan.this_string "<!DOCTYPE" --
   222   Scan.repeat (Scan.unless ($$ ">") regular) --
   223   $$ ">" >> ignored;
   224 
   225 val parse_misc =
   226   Scan.one Symbol.is_blank >> ignored ||
   227   parse_processing_instruction ||
   228   parse_comment;
   229 
   230 val parse_optional_text =
   231   Scan.optional (parse_chars >> (single o Text)) [];
   232 
   233 in
   234 
   235 val parse_comments =
   236   blanks -- Scan.repeat (parse_comment -- blanks >> K ()) >> K ();
   237 
   238 val parse_string = Scan.read Symbol.stopper parse_chars o raw_explode;
   239 
   240 fun parse_content xs =
   241   (parse_optional_text @@@
   242     (Scan.repeat
   243       ((parse_element >> single ||
   244         parse_cdata >> (single o Text) ||
   245         parse_processing_instruction ||
   246         parse_comment)
   247       @@@ parse_optional_text) >> flat)) xs
   248 
   249 and parse_element xs =
   250   ($$ "<" |-- parse_name -- Scan.repeat (blanks |-- parse_att) --| blanks :--
   251     (fn (name, _) =>
   252       !! (err (fn () => "Expected > or />"))
   253        ($$ "/" -- $$ ">" >> ignored ||
   254         $$ ">" |-- parse_content --|
   255           !! (err (fn () => "Expected </" ^ implode name ^ ">"))
   256               ($$ "<" -- $$ "/" -- Scan.this name -- blanks -- $$ ">")))
   257     >> (fn ((name, atts), body) => Elem ((implode name, atts), body))) xs;
   258 
   259 val parse_document =
   260   (Scan.repeat parse_misc -- Scan.option parse_doctype -- Scan.repeat parse_misc)
   261   |-- parse_element;
   262 
   263 fun parse s =
   264   (case Scan.finite Symbol.stopper (Scan.error (!! (err (fn () => "Malformed element"))
   265       (blanks |-- parse_document --| blanks))) (raw_explode s) of
   266     (x, []) => x
   267   | (_, ys) => error ("XML parsing error: unprocessed input\n" ^ Symbol.beginning 100 ys));
   268 
   269 end;
   270 
   271 
   272 
   273 (** XML as data representation language **)
   274 
   275 exception XML_ATOM of string;
   276 exception XML_BODY of tree list;
   277 
   278 
   279 structure Encode =
   280 struct
   281 
   282 type 'a A = 'a -> string;
   283 type 'a T = 'a -> body;
   284 type 'a V = 'a -> string list * body;
   285 
   286 
   287 (* atomic values *)
   288 
   289 fun int_atom i = signed_string_of_int i;
   290 
   291 fun bool_atom false = "0"
   292   | bool_atom true = "1";
   293 
   294 fun unit_atom () = "";
   295 
   296 
   297 (* structural nodes *)
   298 
   299 fun node ts = Elem ((":", []), ts);
   300 
   301 fun vector xs = map_index (fn (i, x) => (int_atom i, x)) xs;
   302 
   303 fun tagged (tag, (xs, ts)) = Elem ((int_atom tag, vector xs), ts);
   304 
   305 
   306 (* representation of standard types *)
   307 
   308 fun properties props = [Elem ((":", props), [])];
   309 
   310 fun string "" = []
   311   | string s = [Text s];
   312 
   313 val int = string o int_atom;
   314 
   315 val bool = string o bool_atom;
   316 
   317 val unit = string o unit_atom;
   318 
   319 fun pair f g (x, y) = [node (f x), node (g y)];
   320 
   321 fun triple f g h (x, y, z) = [node (f x), node (g y), node (h z)];
   322 
   323 fun list f xs = map (node o f) xs;
   324 
   325 fun option _ NONE = []
   326   | option f (SOME x) = [node (f x)];
   327 
   328 fun variant fs x =
   329   [tagged (the (get_index (fn f => SOME (f x) handle General.Match => NONE) fs))];
   330 
   331 end;
   332 
   333 
   334 structure Decode =
   335 struct
   336 
   337 type 'a A = string -> 'a;
   338 type 'a T = body -> 'a;
   339 type 'a V = string list * body -> 'a;
   340 
   341 
   342 (* atomic values *)
   343 
   344 fun int_atom s =
   345   Markup.parse_int s
   346     handle Fail _ => raise XML_ATOM s;
   347 
   348 fun bool_atom "0" = false
   349   | bool_atom "1" = true
   350   | bool_atom s = raise XML_ATOM s;
   351 
   352 fun unit_atom "" = ()
   353   | unit_atom s = raise XML_ATOM s;
   354 
   355 
   356 (* structural nodes *)
   357 
   358 fun node (Elem ((":", []), ts)) = ts
   359   | node t = raise XML_BODY [t];
   360 
   361 fun vector atts =
   362   map_index (fn (i, (a, x)) => if int_atom a = i then x else raise XML_ATOM a) atts;
   363 
   364 fun tagged (Elem ((name, atts), ts)) = (int_atom name, (vector atts, ts))
   365   | tagged t = raise XML_BODY [t];
   366 
   367 
   368 (* representation of standard types *)
   369 
   370 fun properties [Elem ((":", props), [])] = props
   371   | properties ts = raise XML_BODY ts;
   372 
   373 fun string [] = ""
   374   | string [Text s] = s
   375   | string ts = raise XML_BODY ts;
   376 
   377 val int = int_atom o string;
   378 
   379 val bool = bool_atom o string;
   380 
   381 val unit = unit_atom o string;
   382 
   383 fun pair f g [t1, t2] = (f (node t1), g (node t2))
   384   | pair _ _ ts = raise XML_BODY ts;
   385 
   386 fun triple f g h [t1, t2, t3] = (f (node t1), g (node t2), h (node t3))
   387   | triple _ _ _ ts = raise XML_BODY ts;
   388 
   389 fun list f ts = map (f o node) ts;
   390 
   391 fun option _ [] = NONE
   392   | option f [t] = SOME (f (node t))
   393   | option _ ts = raise XML_BODY ts;
   394 
   395 fun variant fs [t] =
   396       let
   397         val (tag, (xs, ts)) = tagged t;
   398         val f = nth fs tag handle General.Subscript => raise XML_BODY [t];
   399       in f (xs, ts) end
   400   | variant _ ts = raise XML_BODY ts;
   401 
   402 end;
   403 
   404 end;