|
| 1 | +(* TyXML |
| 2 | + * http://www.ocsigen.org/tyxml |
| 3 | + * Copyright (C) 2018 Gabriel Radanne |
| 4 | + * |
| 5 | + * This program is free software; you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU Lesser General Public License as published by |
| 7 | + * the Free Software Foundation, with linking exception; |
| 8 | + * either version 2.1 of the License, or (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU Lesser General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU Lesser General Public License |
| 16 | + * along with this program; if not, write to the Free Software |
| 17 | + * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02111-1307, USA. |
| 18 | +*) |
| 19 | + |
| 20 | +type name = string * string |
| 21 | + |
| 22 | +(** Input *) |
| 23 | + |
| 24 | +type signal = [ |
| 25 | + | `Comment of string |
| 26 | + | `End_element |
| 27 | + | `Start_element of name * (name * string) list |
| 28 | + | `Text of string list |
| 29 | +] |
| 30 | + |
| 31 | +exception Malformed_stream |
| 32 | + |
| 33 | +module Import |
| 34 | + (Xml : Xml_sigs.T) |
| 35 | += struct |
| 36 | + |
| 37 | + let of_list l = |
| 38 | + List.fold_right |
| 39 | + (fun a b -> Xml.W.(cons (return a) b)) |
| 40 | + l (Xml.W.nil ()) |
| 41 | + |
| 42 | + let mk_attribs attrs = |
| 43 | + (* TODO: This is not very structured *) |
| 44 | + let f ((_,name), v) = Xml.string_attrib name (Xml.W.return v) in |
| 45 | + List.map f attrs |
| 46 | + |
| 47 | + let rec mk children (seq : signal Seq.t) = match seq () with |
| 48 | + | Cons (`Comment s, q) -> |
| 49 | + mk (Xml.comment s :: children) q |
| 50 | + | Cons (`Text s, q) -> |
| 51 | + mk (List.map (fun x -> Xml.pcdata @@ Xml.W.return x) s @ children) q |
| 52 | + | Cons (`Start_element ((_, name), attrs), q) -> |
| 53 | + let a = mk_attribs attrs in |
| 54 | + let sub_children, rest = mk [] q in |
| 55 | + mk (Xml.node ~a name sub_children :: children) rest |
| 56 | + | Cons (`End_element, rest) -> |
| 57 | + of_list (List.rev children), rest |
| 58 | + | Nil -> |
| 59 | + of_list (List.rev children), Seq.empty |
| 60 | + |
| 61 | + let of_seq seq = |
| 62 | + let l, rest = mk [] seq in |
| 63 | + match rest () with |
| 64 | + | Seq.Nil -> l |
| 65 | + | _ -> raise Malformed_stream |
| 66 | + |
| 67 | +end |
0 commit comments