text
stringlengths
0
601k
let take_data node = let rec aux = function | [ ] -> [ ] , [ ] | D d :: xs -> let ds , xs = aux xs in ( d :: ds ) , xs | n :: xs -> let ds , xs = aux xs in ds , ( n :: xs ) in let chosen , rest = aux node . children in node . children <- rest ; match chosen with | [ ] -> " " | [ d ] -> d | _ -> Fmt . failwith " Element % a has multiple data nodes ( mixed content ) " pp node
let take_attr_opt name n = let ( let ) + x f = Option . map f x in let rec extract = function | [ ] -> None | ( ( " " , k ) , v ) :: xs when k = name -> Some ( v , xs ) | x :: xs -> let + r , xs = extract xs in r , ( x :: xs ) in let + r , xs = extract n . attrs in n . attrs <- xs ; r
let take_attr name node = match take_attr_opt name node with | Some x -> x | None -> Fmt . failwith " Missing attribute % S on % a " name pp node
let parse ~ name ch f = let input = Xmlm . make_input ( ` Channel ch ) in let rec aux ~ level = let pos = name , Xmlm . pos input in match Xmlm . input input with | ` El_start ( name , attrs ) -> let children = aux ~ level ( : succ level ) in let rest = if level = 0 then [ ] else aux ~ level in E { pos ; name ; attrs ; children } :: rest | ` Data d -> D d :: aux ~ level | ` Dtd _ -> aux ~ level | ` El_end -> [ ] in match aux ~ level : 0 with | [ E e ] -> f e | _ -> Fmt . failwith " Malformed XML in % s " name
type readyState = | UNSENT | OPENED | HEADERS_RECEIVED | LOADING | DONE
type _ response = | ArrayBuffer : Typed_array . arrayBuffer t Opt . t response | Blob : # File . blob t Opt . t response | Document : Dom . element Dom . document t Opt . t response | JSON : ' a Opt . t response | Text : js_string t response | Default : string response object ( ' self ) method onreadystatechange : ( unit -> unit ) Js . callback Js . writeonly_prop method readyState : readyState readonly_prop method _open : js_string t -> js_string t -> bool t -> unit meth method _open_full : js_string t -> js_string t -> bool t -> js_string t opt -> js_string t opt -> unit meth method setRequestHeader : js_string t -> js_string t -> unit meth method overrideMimeType : js_string t -> unit meth method send : js_string t opt -> unit meth method send_blob : # File . blob t -> unit meth method send_document : Dom . element Dom . document t -> unit meth method send_formData : Form . formData t -> unit meth method abort : unit meth method status : int readonly_prop method statusText : js_string t readonly_prop method getResponseHeader : js_string t -> js_string t opt meth method getAllResponseHeaders : js_string t meth method response : File . file_any readonly_prop method responseText : js_string t opt readonly_prop method responseXML : Dom . element Dom . document t opt readonly_prop method responseType : js_string t prop method withCredentials : bool t writeonly_prop inherit File . progressEventTarget method ontimeout : ( ' self t , ' self File . progressEvent t ) Dom . event_listener writeonly_prop method upload : xmlHttpRequestUpload t optdef readonly_prop end object ( ' self ) inherit File . progressEventTarget end
module Event = struct type typ = xmlHttpRequest File . progressEvent t Dom . Event . typ let readystatechange = Dom . Event . make " readystatechange " let loadstart = Dom . Event . make " loadstart " let progress = Dom . Event . make " progress " let abort = Dom . Event . make " abort " let error = Dom . Event . make " error " let load = Dom . Event . make " load " let timeout = Dom . Event . make " timeout " let loadend = Dom . Event . make " loadend " end
module type String = sig type t val empty : t val length : t -> int val append : t -> t -> t val lowercase : t -> t val iter : ( int -> unit ) -> t -> unit val of_string : std_string -> t val to_utf_8 : ( ' a -> std_string -> ' a ) -> ' a -> t -> ' a val compare : t -> t -> int end
module type Buffer = sig type string type t exception Full val create : int -> t val add_uchar : t -> int -> unit val clear : t -> unit val contents : t -> string val length : t -> int end
module type S = sig type string type encoding = [ | ` UTF_8 | ` UTF_16 | ` UTF_16BE | ` UTF_16LE | ` ISO_8859_1 | ` US_ASCII ] type dtd = string option type name = string * string type attribute = name * string type tag = name * attribute list type signal = [ ` Dtd of dtd | ` El_start of tag | ` El_end | ` Data of string ] val ns_xml : string val ns_xmlns : string type pos = int * int type error = [ | ` Max_buffer_size | ` Unexpected_eoi | ` Malformed_char_stream | ` Unknown_encoding of string | ` Unknown_entity_ref of string | ` Unknown_ns_prefix of string | ` Illegal_char_ref of string | ` Illegal_char_seq of string | ` Expected_char_seqs of string list * string | ` Expected_root_element ] exception Error of pos * error val error_message : error -> string type source = [ | ` Channel of in_channel | ` String of int * std_string | ` Fun of ( unit -> int ) ] type input val make_input : ? enc : encoding option -> ? strip : bool -> ? ns ( : string -> string option ) -> ? entity : ( string -> string option ) -> source -> input val input : input -> signal val input_tree : el ( : tag -> ' a list -> ' a ) -> data ( : string -> ' a ) -> input -> ' a val input_doc_tree : el ( : tag -> ' a list -> ' a ) -> data ( : string -> ' a ) -> input -> ( dtd * ' a ) val peek : input -> signal val eoi : input -> bool val pos : input -> pos type ' a frag = [ ` El of tag * ' a list | ` Data of string ] type dest = [ | ` Channel of out_channel | ` Buffer of std_buffer | ` Fun of ( int -> unit ) ] type output val make_output : ? decl : bool -> ? nl : bool -> ? indent : int option -> ? ns_prefix ( : string -> string option ) -> dest -> output val output_depth : output -> int val output : output -> signal -> unit val output_tree : ( ' a -> ' a frag ) -> output -> ' a -> unit val output_doc_tree : ( ' a -> ' a frag ) -> output -> ( dtd * ' a ) -> unit end
let utf8_len = [ | 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 1 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 2 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 3 ; 4 ; 4 ; 4 ; 4 ; 4 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ; 0 ] |
let uchar_utf8 i = let b0 = i ( ) in begin match utf8_len . ( b0 ) with | 0 -> raise Malformed | 1 -> b0 | 2 -> let b1 = i ( ) in if b1 lsr 6 != 0b10 then raise Malformed else ( ( b0 land 0x1F ) lsl 6 ) lor ( b1 land 0x3F ) | 3 -> let b1 = i ( ) in let b2 = i ( ) in if b2 lsr 6 != 0b10 then raise Malformed else begin match b0 with | 0xE0 -> if b1 < 0xA0 || 0xBF < b1 then raise Malformed else ( ) | 0xED -> if b1 < 0x80 || 0x9F < b1 then raise Malformed else ( ) | _ -> if b1 lsr 6 != 0b10 then raise Malformed else ( ) end ; ( ( b0 land 0x0F ) lsl 12 ) lor ( ( b1 land 0x3F ) lsl 6 ) lor ( b2 land 0x3F ) | 4 -> let b1 = i ( ) in let b2 = i ( ) in let b3 = i ( ) in if b3 lsr 6 != 0b10 || b2 lsr 6 != 0b10 then raise Malformed else begin match b0 with | 0xF0 -> if b1 < 0x90 || 0xBF < b1 then raise Malformed else ( ) | 0xF4 -> if b1 < 0x80 || 0x8F < b1 then raise Malformed else ( ) | _ -> if b1 lsr 6 != 0b10 then raise Malformed else ( ) end ; ( ( b0 land 0x07 ) lsl 18 ) lor ( ( b1 land 0x3F ) lsl 12 ) lor ( ( b2 land 0x3F ) lsl 6 ) lor ( b3 land 0x3F ) | _ -> assert false end
let int16_be i = let b0 = i ( ) in let b1 = i ( ) in ( b0 lsl 8 ) lor b1
let int16_le i = let b0 = i ( ) in let b1 = i ( ) in ( b1 lsl 8 ) lor b0
let uchar_utf16 int16 i = let c0 = int16 i in if c0 < 0xD800 || c0 > 0xDFFF then c0 else if c0 > 0xDBFF then raise Malformed else let c1 = int16 i in ( ( ( c0 land 0x3FF ) lsl 10 ) lor ( c1 land 0x3FF ) ) + 0x10000
let uchar_utf16be = uchar_utf16 int16_be
let uchar_utf16le = uchar_utf16 int16_le
let uchar_byte i = i ( )
let uchar_iso_8859_1 i = i ( )
let uchar_ascii i = let b = i ( ) in if b > 127 then raise Malformed else b
module Make ( String : String ) ( Buffer : Buffer with type string = String . t ) = struct type string = String . t let str = String . of_string let str_eq s s ' = ( compare s s ' ) = 0 let str_empty s = ( compare s String . empty ) = 0 let cat = String . append let str_of_char u = let b = Buffer . create 4 in Buffer . add_uchar b u ; Buffer . contents b module Ht = Hashtbl . Make ( struct type t = string let equal = str_eq let hash = Hashtbl . hash end ) let u_nl = 0x000A let u_cr = 0x000D let u_space = 0x0020 let u_quot = 0x0022 let u_sharp = 0x0023 let u_amp = 0x0026 let u_apos = 0x0027 let u_minus = 0x002D let u_slash = 0x002F let u_colon = 0x003A let u_scolon = 0x003B let u_lt = 0x003C let u_eq = 0x003D let u_gt = 0x003E let u_qmark = 0x003F let u_emark = 0x0021 let u_lbrack = 0x005B let u_rbrack = 0x005D let u_x = 0x0078 let u_bom = 0xFEFF let u_9 = 0x0039 let u_F = 0x0046 let u_D = 0X0044 let s_cdata = str " CDATA [ " let ns_xml = str " http :// www . w3 . org / XML / 1998 / namespace " let ns_xmlns = str " http :// www . w3 . org / 2000 / xmlns " / let n_xml = str " xml " let n_xmlns = str " xmlns " let n_space = str " space " let n_version = str " version " let n_encoding = str " encoding " let n_standalone = str " standalone " let v_yes = str " yes " let v_no = str " no " let v_preserve = str " preserve " let v_default = str " default " let v_version_1_0 = str " 1 . 0 " let v_version_1_1 = str " 1 . 1 " let v_utf_8 = str " utf - 8 " let v_utf_16 = str " utf - 16 " let v_utf_16be = str " utf - 16be " let v_utf_16le = str " utf - 16le " let v_iso_8859_1 = str " iso - 8859 - 1 " let v_us_ascii = str " us - ascii " let v_ascii = str " ascii " let name_str ( p , l ) = if str_empty p then l else cat p ( cat ( str " " ) : l ) type encoding = [ | ` UTF_8 | ` UTF_16 | ` UTF_16BE | ` UTF_16LE | ` ISO_8859_1 | ` US_ASCII ] type dtd = string option type name = string * string type attribute = name * string type tag = name * attribute list type signal = [ ` Dtd of dtd | ` El_start of tag | ` El_end | ` Data of string ] type pos = int * int type error = [ | ` Max_buffer_size | ` Unexpected_eoi | ` Malformed_char_stream | ` Unknown_encoding of string | ` Unknown_entity_ref of string | ` Unknown_ns_prefix of string | ` Illegal_char_ref of string | ` Illegal_char_seq of string | ` Expected_char_seqs of string list * string | ` Expected_root_element ] exception Error of pos * error let error_message e = let bracket l v r = cat ( str l ) ( cat v ( str r ) ) in match e with | ` Expected_root_element -> str " expected root element " | ` Max_buffer_size -> str " maximal buffer size exceeded " | ` Unexpected_eoi -> str " unexpected end of input " | ` Malformed_char_stream -> str " malformed character stream " | ` Unknown_encoding e -> bracket " unknown encoding ( " e " ) " | ` Unknown_entity_ref e -> bracket " unknown entity reference ( " e " ) " | ` Unknown_ns_prefix e -> bracket " unknown namespace prefix ( " e " ) " | ` Illegal_char_ref s -> bracket " illegal character reference ( " # s " ) " | ` Illegal_char_seq s -> bracket " character sequence illegal here ( " " \ s " " ) " \ | ` Expected_char_seqs ( exps , fnd ) -> let exps = let exp acc v = cat acc ( bracket " " " \ v " " , \ " ) in List . fold_left exp String . empty exps in cat ( str " expected one of these character sequence : " ) ( cat exps ( bracket " found " " \ fnd " " " ) ) \ type limit = | Stag of name | Etag of name | Pi of name | Comment | Cdata | Dtd | Text | Eoi type source = [ | ` Channel of in_channel | ` String of int * std_string | ` Fun of ( unit -> int ) ] type input = { enc : encoding option ; strip : bool ; fun_ns : string -> string option ; fun_entity : string -> string option ; i : unit -> int ; mutable uchar : ( unit -> int ) -> int ; mutable c : int ; mutable cr : bool ; mutable line : int ; mutable col : int ; mutable limit : limit ; mutable peek : signal ; mutable stripping : bool ; mutable last_white : bool ; mutable scopes : ( name * string list * bool ) list ; ns : string Ht . t ; ident : Buffer . t ; data : Buffer . t ; } let err_input_tree = " input signal not ` El_start or ` Data " let err_input_doc_tree = " input signal not ` Dtd " let err i e = raise ( Error ( ( i . line , i . col ) , e ) ) let err_illegal_char i u = err i ( ` Illegal_char_seq ( str_of_char u ) ) let err_expected_seqs i exps s = err i ( ` Expected_char_seqs ( exps , s ) ) let err_expected_chars i exps = err i ( ` Expected_char_seqs ( List . map str_of_char exps , str_of_char i . c ) ) let u_eoi = max_int let u_start_doc = u_eoi - 1 let u_end_doc = u_start_doc - 1 let signal_start_stream = ` Data String . empty let make_input ( ? enc = None ) ( ? strip = false ) ( ? ns = fun _ -> None ) ( ? entity = fun _ -> None ) src = let i = match src with | ` Fun f -> f | ` Channel ic -> fun ( ) -> input_byte ic | ` String ( pos , s ) -> let len = Std_string . length s in let pos = ref ( pos - 1 ) in fun ( ) -> incr pos ; if ! pos = len then raise End_of_file else Char . code ( Std_string . get s ! pos ) in let bindings = let h = Ht . create 15 in Ht . add h String . empty String . empty ; Ht . add h n_xml ns_xml ; Ht . add h n_xmlns ns_xmlns ; h in { enc = enc ; strip = strip ; fun_ns = ns ; fun_entity = entity ; i = i ; uchar = uchar_byte ; c = u_start_doc ; cr = false ; line = 1 ; col = 0 ; limit = Text ; peek = signal_start_stream ; stripping = strip ; last_white = true ; scopes = [ ] ; ns = bindings ; ident = Buffer . create 64 ; data = Buffer . create 1024 ; } let r : int -> int -> int -> bool = fun u a b -> a <= u && u <= b let is_white = function 0x0020 | 0x0009 | 0x000D | 0x000A -> true | _ -> false let is_char = function | u when r u 0x0020 0xD7FF -> true | 0x0009 | 0x000A | 0x000D -> true | u when r u 0xE000 0xFFFD || r u 0x10000 0x10FFFF -> true | _ -> false let is_digit u = r u 0x0030 0x0039 let is_hex_digit u = r u 0x0030 0x0039 || r u 0x0041 0x0046 || r u 0x0061 0x0066 let comm_range u = r u 0x00C0 0x00D6 || r u 0x00D8 0x00F6 || r u 0x00F8 0x02FF || r u 0x0370 0x037D || r u 0x037F 0x1FFF || r u 0x200C 0x200D || r u 0x2070 0x218F || r u 0x2C00 0x2FEF || r u 0x3001 0xD7FF || r u 0xF900 0xFDCF || r u 0xFDF0 0xFFFD || r u 0x10000 0xEFFFF let is_name_start_char = function | u when r u 0x0061 0x007A || r u 0x0041 0x005A -> true | u when is_white u -> false | 0x005F -> true | u when comm_range u -> true | _ -> false let is_name_char = function | u when r u 0x0061 0x007A || r u 0x0041 0x005A -> true | u when is_white u -> false | u when r u 0x0030 0x0039 -> true | 0x005F | 0x002D | 0x002E | 0x00B7 -> true | u when comm_range u || r u 0x0300 0x036F || r u 0x203F 0x2040 -> true | _ -> false let rec nextc i = if i . c = u_eoi then err i ` Unexpected_eoi ; if i . c = u_nl then ( i . line <- i . line + 1 ; i . col <- 1 ) else i . col <- i . col + 1 ; i . c <- i . uchar i . i ; if not ( is_char i . c ) then raise Malformed ; if i . cr && i . c = u_nl then i . c <- i . uchar i . i ; if i . c = u_cr then ( i . cr <- true ; i . c <- u_nl ) else i . cr <- false let nextc_eof i = try nextc i with End_of_file -> i . c <- u_eoi let skip_white i = while ( is_white i . c ) do nextc i done let skip_white_eof i = while ( is_white i . c ) do nextc_eof i done let accept i c = if i . c = c then nextc i else err_expected_chars i [ c ] let clear_ident i = Buffer . clear i . ident let clear_data i = Buffer . clear i . data let addc_ident i c = Buffer . add_uchar i . ident c let addc_data i c = Buffer . add_uchar i . data c let addc_data_strip i c = if is_white c then i . last_white <- true else begin if i . last_white && Buffer . length i . data <> 0 then addc_data i u_space ; i . last_white <- false ; addc_data i c end let expand_name i ( prefix , local ) = let external_ prefix = match i . fun_ns prefix with | None -> err i ( ` Unknown_ns_prefix prefix ) | Some uri -> uri in try let uri = Ht . find i . ns prefix in if not ( str_empty uri ) then ( uri , local ) else if str_empty prefix then String . empty , local else ( external_ prefix ) , local with Not_found -> external_ prefix , local let find_encoding i = let reset uchar i = i . uchar <- uchar ; i . col <- 0 ; nextc i in match i . enc with | None -> begin match nextc i ; i . c with | 0xFE -> nextc i ; if i . c <> 0xFF then err i ` Malformed_char_stream ; reset uchar_utf16be i ; true | 0xFF -> nextc i ; if i . c <> 0xFE then err i ` Malformed_char_stream ; reset uchar_utf16le i ; true | 0xEF -> nextc i ; if i . c <> 0xBB then err i ` Malformed_char_stream ; nextc i ; if i . c <> 0xBF then err i ` Malformed_char_stream ; reset uchar_utf8 i ; true | 0x3C | _ -> i . uchar <- uchar_utf8 ; false end | Some e -> begin match e with | ` US_ASCII -> reset uchar_ascii i | ` ISO_8859_1 -> reset uchar_iso_8859_1 i | ` UTF_8 -> reset uchar_utf8 i ; if i . c = u_bom then ( i . col <- 0 ; nextc i ) | ` UTF_16 -> let b0 = nextc i ; i . c in let b1 = nextc i ; i . c in begin match b0 , b1 with | 0xFE , 0xFF -> reset uchar_utf16be i | 0xFF , 0xFE -> reset uchar_utf16le i | _ -> err i ` Malformed_char_stream ; end | ` UTF_16BE -> reset uchar_utf16be i ; if i . c = u_bom then ( i . col <- 0 ; nextc i ) | ` UTF_16LE -> reset uchar_utf16le i ; if i . c = u_bom then ( i . col <- 0 ; nextc i ) end ; true let p_ncname i = clear_ident i ; if not ( is_name_start_char i . c ) then err_illegal_char i i . c else begin addc_ident i i . c ; nextc i ; while is_name_char i . c do addc_ident i i . c ; nextc i done ; Buffer . contents i . ident end let p_qname i = let n = p_ncname i in if i . c <> u_colon then ( String . empty , n ) else ( nextc i ; ( n , p_ncname i ) ) let p_charref i = let c = ref 0 in clear_ident i ; nextc i ; if i . c = u_scolon then err i ( ` Illegal_char_ref String . empty ) else begin try if i . c = u_x then begin addc_ident i i . c ; nextc i ; while ( i . c <> u_scolon ) do addc_ident i i . c ; if not ( is_hex_digit i . c ) then raise Exit else c := ! c * 16 + ( if i . c <= u_9 then i . c - 48 else if i . c <= u_F then i . c - 55 else i . c - 87 ) ; nextc i ; done end else while ( i . c <> u_scolon ) do addc_ident i i . c ; if not ( is_digit i . c ) then raise Exit else c := ! c * 10 + ( i . c - 48 ) ; nextc i done with Exit -> c := - 1 ; while i . c <> u_scolon do addc_ident i i . c ; nextc i done end ; nextc i ; if is_char ! c then ( clear_ident i ; addc_ident i ! c ; Buffer . contents i . ident ) else err i ( ` Illegal_char_ref ( Buffer . contents i . ident ) ) let predefined_entities = let h = Ht . create 5 in let e k v = Ht . add h ( str k ) ( str v ) in e " lt " " " ; < e " gt " " " ; > e " amp " " " ; & e " apos " " ' " ; e " quot " " " " ; \ h let p_entity_ref i = let ent = p_ncname i in accept i u_scolon ; try Ht . find predefined_entities ent with Not_found -> match i . fun_entity ent with | Some s -> s | None -> err i ( ` Unknown_entity_ref ent ) let p_reference i = nextc i ; if i . c = u_sharp then p_charref i else p_entity_ref i let p_attr_value i = skip_white i ; let delim = if i . c = u_quot || i . c = u_apos then i . c else err_expected_chars i [ u_quot ; u_apos ] in nextc i ; skip_white i ; clear_data i ; i . last_white <- true ; while ( i . c <> delim ) do if i . c = u_lt then err_illegal_char i u_lt else if i . c = u_amp then String . iter ( addc_data_strip i ) ( p_reference i ) else ( addc_data_strip i i . c ; nextc i ) done ; nextc i ; Buffer . contents i . data let p_attributes i = let rec aux i pre_acc acc = if not ( is_white i . c ) then pre_acc , acc else begin skip_white i ; if i . c = u_slash || i . c = u_gt then pre_acc , acc else begin let ( prefix , local ) as n = p_qname i in let v = skip_white i ; accept i u_eq ; p_attr_value i in let att = n , v in if str_empty prefix && str_eq local n_xmlns then begin Ht . add i . ns String . empty v ; aux i ( String . empty :: pre_acc ) ( att :: acc ) end else if str_eq prefix n_xmlns then begin Ht . add i . ns local v ; aux i ( local :: pre_acc ) ( att :: acc ) end else if str_eq prefix n_xml && str_eq local n_space then begin if str_eq v v_preserve then i . stripping <- false else if str_eq v v_default then i . stripping <- i . strip else ( ) ; aux i pre_acc ( att :: acc ) end else aux i pre_acc ( att :: acc ) end end in aux i [ ] [ ] let p_limit i = i . limit <- if i . c = u_eoi then Eoi else if i . c <> u_lt then Text else begin nextc i ; if i . c = u_qmark then ( nextc i ; Pi ( p_qname i ) ) else if i . c = u_slash then begin nextc i ; let n = p_qname i in skip_white i ; Etag n end else if i . c = u_emark then begin nextc i ; if i . c = u_minus then ( nextc i ; accept i u_minus ; Comment ) else if i . c = u_D then Dtd else if i . c = u_lbrack then begin nextc i ; clear_ident i ; for k = 1 to 6 do ( addc_ident i i . c ; nextc i ) done ; let cdata = Buffer . contents i . ident in if str_eq cdata s_cdata then Cdata else err_expected_seqs i [ s_cdata ] cdata end else err i ( ` Illegal_char_seq ( cat ( str " " ) <! ( str_of_char i . c ) ) ) end else Stag ( p_qname i ) end let rec skip_comment i = while ( i . c <> u_minus ) do nextc i done ; nextc i ; if i . c <> u_minus then skip_comment i else begin nextc i ; if i . c <> u_gt then err_expected_chars i [ u_gt ] ; nextc_eof i end let rec skip_pi i = while ( i . c <> u_qmark ) do nextc i done ; nextc i ; if i . c <> u_gt then skip_pi i else nextc_eof i let rec skip_misc i ~ allow_xmlpi = match i . limit with | Pi ( p , l ) when ( str_empty p && str_eq n_xml ( String . lowercase l ) ) -> if allow_xmlpi then ( ) else err i ( ` Illegal_char_seq l ) | Pi _ -> skip_pi i ; p_limit i ; skip_misc i ~ allow_xmlpi | Comment -> skip_comment i ; p_limit i ; skip_misc i ~ allow_xmlpi | Text when is_white i . c -> skip_white_eof i ; p_limit i ; skip_misc i ~ allow_xmlpi | _ -> ( ) let p_chardata addc i = while ( i . c <> u_lt ) do if i . c = u_amp then String . iter ( addc i ) ( p_reference i ) else if i . c = u_rbrack then begin addc i i . c ; nextc i ; if i . c = u_rbrack then begin addc i i . c ; nextc i ; while ( i . c = u_rbrack ) do addc i i . c ; nextc i done ; if i . c = u_gt then err i ( ` Illegal_char_seq ( str " ] ] " ) ) ; > end end else ( addc i i . c ; nextc i ) done let rec p_cdata addc i = try while ( true ) do if i . c = u_rbrack then begin nextc i ; while i . c = u_rbrack do nextc i ; if i . c = u_gt then ( nextc i ; raise Exit ) ; addc i u_rbrack done ; addc i u_rbrack ; end ; addc i i . c ; nextc i ; done with Exit -> ( ) let p_xml_decl i ~ ignore_enc ~ ignore_utf16 = let yes_no = [ v_yes ; v_no ] in let p_val i = skip_white i ; accept i u_eq ; skip_white i ; p_attr_value i in let p_val_exp i exp = let v = p_val i in if not ( List . exists ( str_eq v ) exp ) then err_expected_seqs i exp v in match i . limit with | Pi ( p , l ) when ( str_empty p && str_eq l n_xml ) -> let v = skip_white i ; p_ncname i in if not ( str_eq v n_version ) then err_expected_seqs i [ n_version ] v ; p_val_exp i [ v_version_1_0 ; v_version_1_1 ] ; skip_white i ; if i . c <> u_qmark then begin let n = p_ncname i in if str_eq n n_encoding then begin let enc = String . lowercase ( p_val i ) in if not ignore_enc then begin if str_eq enc v_utf_8 then i . uchar <- uchar_utf8 else if str_eq enc v_utf_16be then i . uchar <- uchar_utf16be else if str_eq enc v_utf_16le then i . uchar <- uchar_utf16le else if str_eq enc v_iso_8859_1 then i . uchar <- uchar_iso_8859_1 else if str_eq enc v_us_ascii then i . uchar <- uchar_ascii else if str_eq enc v_ascii then i . uchar <- uchar_ascii else if str_eq enc v_utf_16 then if ignore_utf16 then ( ) else ( err i ` Malformed_char_stream ) else err i ( ` Unknown_encoding enc ) end ; skip_white i ; if i . c <> u_qmark then begin let n = p_ncname i in if str_eq n n_standalone then p_val_exp i yes_no else err_expected_seqs i [ n_standalone ; str " " ?> ] n end end else if str_eq n n_standalone then p_val_exp i yes_no else err_expected_seqs i [ n_encoding ; n_standalone ; str " " ?> ] n end ; skip_white i ; accept i u_qmark ; accept i u_gt ; p_limit i | _ -> ( ) let p_dtd_signal i = skip_misc i ~ allow_xmlpi : false ; if i . limit <> Dtd then ` Dtd None else begin let buf = addc_data i in let nest = ref 1 in clear_data i ; buf u_lt ; buf u_emark ; while ( ! nest > 0 ) do if i . c = u_lt then begin nextc i ; if i . c <> u_emark then ( buf u_lt ; incr nest ) else begin nextc i ; if i . c <> u_minus then ( buf u_lt ; buf u_emark ; incr nest ) else begin nextc i ; if i . c <> u_minus then ( buf u_lt ; buf u_emark ; buf u_minus ; incr nest ) else ( nextc i ; skip_comment i ) end end end else if i . c = u_quot || i . c = u_apos then begin let c = i . c in buf c ; nextc i ; while ( i . c <> c ) do ( buf i . c ; nextc i ) done ; buf c ; nextc i end else if i . c = u_gt then ( buf u_gt ; nextc i ; decr nest ) else ( buf i . c ; nextc i ) done ; let dtd = Buffer . contents i . data in p_limit i ; skip_misc i ~ allow_xmlpi : false ; ` Dtd ( Some dtd ) ; end let p_data i = let rec bufferize addc i = match i . limit with | Text -> p_chardata addc i ; p_limit i ; bufferize addc i | Cdata -> p_cdata addc i ; p_limit i ; bufferize addc i | ( Stag _ | Etag _ ) -> ( ) | Pi _ -> skip_pi i ; p_limit i ; bufferize addc i | Comment -> skip_comment i ; p_limit i ; bufferize addc i | Dtd -> err i ( ` Illegal_char_seq ( str " <! D " ) ) | Eoi -> err i ` Unexpected_eoi in clear_data i ; i . last_white <- true ; bufferize ( if i . stripping then addc_data_strip else addc_data ) i ; let d = Buffer . contents i . data in d let p_el_start_signal i n = let expand_att ( ( ( prefix , local ) as n , v ) as att ) = if not ( str_eq prefix String . empty ) then expand_name i n , v else if str_eq local n_xmlns then ( ns_xmlns , n_xmlns ) , v else att in let strip = i . stripping in let prefixes , atts = p_attributes i in i . scopes <- ( n , prefixes , strip ) :: i . scopes ; ` El_start ( ( expand_name i n ) , List . rev_map expand_att atts ) let p_el_end_signal i n = match i . scopes with | ( n ' , prefixes , strip ) :: scopes -> if i . c <> u_gt then err_expected_chars i [ u_gt ] ; if not ( str_eq n n ' ) then err_expected_seqs i [ name_str n ' ] ( name_str n ) ; i . scopes <- scopes ; i . stripping <- strip ; List . iter ( Ht . remove i . ns ) prefixes ; if scopes = [ ] then i . c <- u_end_doc else ( nextc i ; p_limit i ) ; ` El_end | _ -> assert false let p_signal i = if i . scopes = [ ] then match i . limit with | Stag n -> p_el_start_signal i n | _ -> err i ` Expected_root_element else let rec find i = match i . limit with | Stag n -> p_el_start_signal i n | Etag n -> p_el_end_signal i n | Text | Cdata -> let d = p_data i in if str_empty d then find i else ` Data d | Pi _ -> skip_pi i ; p_limit i ; find i | Comment -> skip_comment i ; p_limit i ; find i | Dtd -> err i ( ` Illegal_char_seq ( str " <! D " ) ) | Eoi -> err i ` Unexpected_eoi in begin match i . peek with | ` El_start ( n , _ ) -> skip_white i ; if i . c = u_gt then ( accept i u_gt ; p_limit i ) else if i . c = u_slash then begin let tag = match i . scopes with | ( tag , _ , _ ) :: _ -> tag | _ -> assert false in ( nextc i ; i . limit <- Etag tag ) end else err_expected_chars i [ u_slash ; u_gt ] | _ -> ( ) end ; find i let eoi i = try if i . c = u_eoi then true else if i . c <> u_start_doc then false else if i . peek <> ` El_end then begin let ignore_enc = find_encoding i in p_limit i ; p_xml_decl i ~ ignore_enc ~ ignore_utf16 : false ; i . peek <- p_dtd_signal i ; false end else begin nextc_eof i ; p_limit i ; if i . c = u_eoi then true else begin skip_misc i ~ allow_xmlpi : true ; if i . c = u_eoi then true else begin p_xml_decl i ~ ignore_enc : false ~ ignore_utf16 : true ; i . peek <- p_dtd_signal i ; false end end end with | Buffer . Full -> err i ` Max_buffer_size | Malformed -> err i ` Malformed_char_stream | End_of_file -> err i ` Unexpected_eoi let peek i = if eoi i then err i ` Unexpected_eoi else i . peek let input i = try if i . c = u_end_doc then ( i . c <- u_start_doc ; i . peek ) else let s = peek i in i . peek <- p_signal i ; s with | Buffer . Full -> err i ` Max_buffer_size | Malformed -> err i ` Malformed_char_stream | End_of_file -> err i ` Unexpected_eoi let input_tree ~ el ~ data i = match input i with | ` Data d -> data d | ` El_start tag -> let rec aux i tags context = match input i with | ` El_start tag -> aux i ( tag :: tags ) ( [ ] :: context ) | ` El_end -> begin match tags , context with | tag :: tags ' , childs :: context ' -> let el = el tag ( List . rev childs ) in begin match context ' with | parent :: context ' ' -> aux i tags ' ( ( el :: parent ) :: context ' ' ) | [ ] -> el end | _ -> assert false end | ` Data d -> begin match context with | childs :: context ' -> aux i tags ( ( ( data d ) :: childs ) :: context ' ) | [ ] -> assert false end | ` Dtd _ -> assert false in aux i ( tag :: [ ] ) ( [ ] :: [ ] ) | _ -> invalid_arg err_input_tree let input_doc_tree ~ el ~ data i = match input i with | ` Dtd d -> d , input_tree ~ el ~ data i | _ -> invalid_arg err_input_doc_tree let pos i = i . line , i . col type ' a frag = [ ` El of tag * ' a list | ` Data of string ] type dest = [ | ` Channel of out_channel | ` Buffer of std_buffer | ` Fun of ( int -> unit ) ] type output = { decl : bool ; nl : bool ; indent : int option ; fun_prefix : string -> string option ; prefixes : string Ht . t ; outs : std_string -> int -> int -> unit ; outc : char -> unit ; mutable last_el_start : bool ; mutable scopes : ( name * ( string list ) ) list ; mutable depth : int ; } let err_prefix uri = " unbound namespace ( " ^ uri ^ " ) " let err_dtd = " dtd signal not allowed here " let err_el_start = " start signal not allowed here " let err_el_end = " end signal without matching start signal " let err_data = " data signal not allowed here " let make_output ( ? decl = true ) ( ? nl = false ) ( ? indent = None ) ( ? ns_prefix = fun _ -> None ) d = let outs , outc = match d with | ` Channel c -> ( output_substring c ) , ( output_char c ) | ` Buffer b -> ( Std_buffer . add_substring b ) , ( Std_buffer . add_char b ) | ` Fun f -> let os s p l = for i = p to p + l - 1 do f ( Char . code ( Std_string . get s i ) ) done in let oc c = f ( Char . code c ) in os , oc in let prefixes = let h = Ht . create 10 in Ht . add h String . empty String . empty ; Ht . add h ns_xml n_xml ; Ht . add h ns_xmlns n_xmlns ; h in { decl = decl ; outs = outs ; outc = outc ; nl = nl ; indent = indent ; last_el_start = false ; prefixes = prefixes ; scopes = [ ] ; depth = - 1 ; fun_prefix = ns_prefix ; } let output_depth o = o . depth let outs o s = o . outs s 0 ( Std_string . length s ) let str_utf_8 s = String . to_utf_8 ( fun _ s -> s ) " " s let out_utf_8 o s = ignore ( String . to_utf_8 ( fun o s -> outs o s ; o ) o s ) let prefix_name o ( ns , local ) = try if str_eq ns ns_xmlns && str_eq local n_xmlns then ( String . empty , n_xmlns ) else ( Ht . find o . prefixes ns , local ) with Not_found -> match o . fun_prefix ns with | None -> invalid_arg ( err_prefix ( str_utf_8 ns ) ) | Some prefix -> prefix , local let bind_prefixes o atts = let add acc ( ( ns , local ) , uri ) = if not ( str_eq ns ns_xmlns ) then acc else begin let prefix = if str_eq local n_xmlns then String . empty else local in Ht . add o . prefixes uri prefix ; uri :: acc end in List . fold_left add [ ] atts let out_data o s = let out ( ) s = let len = Std_string . length s in let start = ref 0 in let last = ref 0 in let escape e = o . outs s ! start ( ! last - ! start ) ; outs o e ; incr last ; start := ! last in while ( ! last < len ) do match Std_string . get s ! last with | ' ' < -> escape " & lt ; " | ' ' > -> escape " & gt ; " | ' ' & -> escape " & amp ; " | ' \ x22 ' -> escape " & quot ; " | ' \ n ' | ' \ t ' | ' \ r ' -> incr last | c when c < ' ' -> escape " \ xEF \ xBF \ xBD " | _ -> incr last done ; o . outs s ! start ( ! last - ! start ) in String . to_utf_8 out ( ) s let out_qname o ( p , l ) = if not ( str_empty p ) then ( out_utf_8 o p ; o . outc ' ' ) ; : out_utf_8 o l let out_attribute o ( n , v ) = o . outc ' ' ; out_qname o ( prefix_name o n ) ; outs o " =\ x22 " ; out_data o v ; o . outc ' \ x22 ' let output o s = let indent o = match o . indent with | None -> ( ) | Some c -> for i = 1 to ( o . depth * c ) do o . outc ' ' done in let unindent o = match o . indent with None -> ( ) | Some _ -> o . outc ' \ n ' in if o . depth = - 1 then begin match s with | ` Dtd d -> if o . decl then outs o " <? xml version " =\ 1 . 0 " \ encoding " =\ UTF - 8 " \?>\ n " ; begin match d with | Some dtd -> out_utf_8 o dtd ; o . outc ' \ n ' | None -> ( ) end ; o . depth <- 0 | ` Data _ -> invalid_arg err_data | ` El_start _ -> invalid_arg err_el_start | ` El_end -> invalid_arg err_el_end end else begin match s with | ` El_start ( n , atts ) -> if o . last_el_start then ( outs o " " ; > unindent o ) ; indent o ; let uris = bind_prefixes o atts in let qn = prefix_name o n in o . outc ' ' ; < out_qname o qn ; List . iter ( out_attribute o ) atts ; o . scopes <- ( qn , uris ) :: o . scopes ; o . depth <- o . depth + 1 ; o . last_el_start <- true | ` El_end -> begin match o . scopes with | ( n , uris ) :: scopes ' -> o . depth <- o . depth - 1 ; if o . last_el_start then outs o " " /> else begin indent o ; outs o " " ; </ out_qname o n ; o . outc ' ' ; > end ; o . scopes <- scopes ' ; List . iter ( Ht . remove o . prefixes ) uris ; o . last_el_start <- false ; if o . depth = 0 then ( if o . nl then o . outc ' \ n ' ; o . depth <- - 1 ; ) else unindent o | [ ] -> invalid_arg err_el_end end | ` Data d -> if o . last_el_start then ( outs o " " ; > unindent o ) ; indent o ; out_data o d ; unindent o ; o . last_el_start <- false | ` Dtd _ -> failwith err_dtd end let output_tree frag o v = let rec aux o = function | ( v :: rest ) :: context -> begin match frag v with | ` El ( tag , childs ) -> output o ( ` El_start tag ) ; aux o ( childs :: rest :: context ) | ( ` Data d ) as signal -> output o signal ; aux o ( rest :: context ) end | [ ] :: [ ] -> ( ) | [ ] :: context -> output o ` El_end ; aux o context | [ ] -> assert false in aux o ( [ v ] :: [ ] ) let output_doc_tree frag o ( dtd , v ) = output o ( ` Dtd dtd ) ; output_tree frag o v end
module String = struct type t = string let empty = " " let length = String . length let append = ( ^ ) let lowercase = String . lowercase_ascii let iter f s = let len = Std_string . length s in let pos = ref ~- 1 in let i ( ) = incr pos ; if ! pos = len then raise Exit else Char . code ( Std_string . get s ! pos ) in try while true do f ( uchar_utf8 i ) done with Exit -> ( ) let of_string s = s let to_utf_8 f v x = f v x let compare = String . compare end
module Buffer = struct type string = String . t type t = Buffer . t exception Full let create = Buffer . create let add_uchar b u = try let buf c = Buffer . add_char b ( Char . chr c ) in if u <= 0x007F then ( buf u ) else if u <= 0x07FF then ( buf ( 0xC0 lor ( u lsr 6 ) ) ; buf ( 0x80 lor ( u land 0x3F ) ) ) else if u <= 0xFFFF then ( buf ( 0xE0 lor ( u lsr 12 ) ) ; buf ( 0x80 lor ( ( u lsr 6 ) land 0x3F ) ) ; buf ( 0x80 lor ( u land 0x3F ) ) ) else ( buf ( 0xF0 lor ( u lsr 18 ) ) ; buf ( 0x80 lor ( ( u lsr 12 ) land 0x3F ) ) ; buf ( 0x80 lor ( ( u lsr 6 ) land 0x3F ) ) ; buf ( 0x80 lor ( u land 0x3F ) ) ) with Failure _ -> raise Full let clear b = Buffer . clear b let contents = Buffer . contents let length = Buffer . length end
let rec pp_list ( ? pp_sep = Format . pp_print_cut ) pp_v ppf = function pp_v ppf v ; if vs <> [ ] then ( pp_sep ppf ( ) ; pp_list ~ pp_sep pp_v ppf vs )
let pp_name ppf ( p , l ) = if p <> " " then pp ppf " % s :% s " p l else pp ppf " % s " l
let pp_attribute ppf ( n , v ) = pp ppf " [ @< 1 ( >% a , , @% S ) ] " @ pp_name n v
let pp_tag ppf ( name , atts ) = let pp_sep ppf ( ) = pp ppf " ; @ " in pp ppf " [ @< 1 ( >% a , , [ @@< 1 [ >% a ] ] ) ] " @@ pp_name name ( pp_list ~ pp_sep pp_attribute ) atts
let pp_dtd ppf = function
let pp_signal ppf = function
let encode = let translate = function | ' > ' -> Some " & gt ; " | ' < ' -> Some " & lt ; " | ' & ' -> Some " & amp ; " | ' " ' -> Some " & quot ; " | c when ( c >= ' \ x20 ' && c <= ' \ xff ' ) xff ' || c = ' \ x09 ' || c = ' \ x0a ' || c = ' \ x0d ' -> None | _ -> Some " " in Internals . encode translate
let rec add_value ( ? strict = false ) false f = function | Null -> f " < value >< nil /></ value " > | Int i -> f " < value " ; > if strict then f " < i8 " ; > f ( Int64 . to_string i ) i ; if strict then f " </ i8 " ; > f " </ value " > | Int32 i -> f " < value >< i4 " ; > f ( Int32 . to_string i ) i ; f " </ i4 ></ value " > | Bool b -> f " < value >< boolean " ; > f ( if b then " 1 " else " 0 ) " ; f " </ boolean ></ value " > | Float d -> f " < value >< double " ; > f ( Printf . sprintf " . % 16g " d ) d ; f " </ double ></ value " > | String s -> f " < value " ; > f ( encode s ) s ; f " </ value " > | DateTime s -> f " < value >< dateTime . iso8601 " ; > f s ; f " </ dateTime . iso8601 ></ value " > | Base64 s -> f " < value >< base64 " ; > f ( Base64 . encode_exn s ) s ; f " </ base64 ></ value " > | Enum l -> f " < value >< array >< data " ; > List . iter ( add_value ~ strict f ) f l ; f " </ data ></ array ></ value " > | Dict d -> let add_member ( name , value ) value = f " < member >< name " ; > f name ; f " </ name " ; > add_value ~ strict f value ; f " </ member " > in f " < value >< struct " ; > List . iter add_member d ; f " </ struct ></ value " >
let to_string ( ? strict = false ) false x = let buf = Buffer . create 128 in add_value ~ strict ( Buffer . add_string buf ) buf x ; Buffer . contents buf
let to_a ( ? strict = false ) false ~ empty ~ append x = let buf = empty ( ) in add_value ~ strict ( fun s -> append buf s ) s x ; buf
let string_of_call ( ? strict = false ) false call = let module B = Buffer in let buf = B . create 1024 in let add = B . add_string buf in add " <? xml version " =\ 1 . 0 " " ; \?> add " < methodCall >< methodName " ; > add ( encode call . name ) name ; add " </ methodName >< params " ; > List . iter ( fun p -> add " < param " ; > add ( to_string ~ strict p ) p ; add " </ param ) " > call . params ; add " </ params ></ methodCall " ; > B . contents buf
let add_response ( ? strict = false ) false add response = let v = if response . success then Dict [ " Status " , String " Success " ; " Value " , response . contents ] else Dict [ " Status " , String " Failure " ; " ErrorDescription " , response . contents ] in add " <? xml version " =\ 1 . 0 " \?>< methodResponse >< params >< param " ; > to_a ~ strict ~ empty ( : fun ( ) -> ( ) ) ~ append ( : fun _ s -> add s ) s v ; add " </ param ></ params ></ methodResponse " >
let string_of_response ( ? strict = false ) false response = let module B = Buffer in let buf = B . create 256 in let add = B . add_string buf in add_response ~ strict add response ; B . contents buf
let a_of_response ( ? strict = false ) false ~ empty ~ append response = let buf = empty ( ) in let add s = append buf s in add_response ~ strict add response ; buf
let debug_input input = let buf = Buffer . create 1024 in let rec aux tags = if not ( Xmlm . eoi input ) input then ( match Xmlm . input input with | ` El_start ( ( _ , tag ) tag , _ ) _ -> Buffer . add_string buf " " ; < Buffer . add_string buf tag ; Buffer . add_string buf " " ; > aux ( tag :: tags ) tags | ` El_end -> ( match tags with | [ ] -> Buffer . add_string buf " " ; <?/> aux tags | h :: t -> Buffer . add_string buf " " ; </ Buffer . add_string buf h ; Buffer . add_string buf " " ; > aux t ) t | ` Data d -> Buffer . add_string buf d ; aux tags | ` Dtd _ -> aux tags ) tags in aux [ ] ; Buffer . contents buf
let pretty_string_of_error got expected input = sprintf " Error : got ' % s ' while ' % s ' was expected when processing ' % s ' \ n " got expected ( debug_input input ) input
let parse_error got expected input = raise ( Parse_error ( got , expected , input ) input ) input
module Parser = struct let is_empty s = let is_empty = ref true in for i = 0 to String . length s - 1 do if s [ . i ] i <> ' \ n ' && s [ . i ] i <> ' ' && s [ . i ] i <> ' \ t ' then is_empty := false done ; ! is_empty let rec skip_empty input = match Xmlm . peek input with | ` Data d when is_empty d -> let _ = Xmlm . input input in skip_empty input | _ -> ( ) let get_data input = match Xmlm . input input with | ` Dtd _ -> parse_error " dtd " " data " input | ` Data d -> d | ` El_start ( ( _ , tag ) tag , _ ) _ -> parse_error ( sprintf " open_tag ( open_tag % s ) s " tag ) tag " data " input | ` El_end -> " " let rec open_tag input = match Xmlm . input input with | ` Dtd _ -> open_tag input | ` El_start ( ( _ , tag ) tag , _ ) _ -> tag | ` Data d when is_empty d -> open_tag input | ` Data d -> parse_error ( sprintf " data ( data % s ) s " ( String . escaped d ) d ) d " open_tag " input | ` El_end -> parse_error " close_tag " " open_tag " input let rec close_tag tag input = match Xmlm . input input with | ` Dtd _ -> parse_error " dtd " ( sprintf " close_tag ( close_tag % s ) s " tag ) tag input | ` El_end -> ( ) | ` El_start ( ( _ , t ) t , _ ) _ -> parse_error ( sprintf " open_tag ( open_tag % s ) s " t ) t ( sprintf " close_tag ( close_tag % s ) s " tag ) tag input | ` Data d when is_empty d -> close_tag tag input | ` Data d -> parse_error ( sprintf " data ( data % s ) s " ( String . escaped d ) d ) d ( sprintf " close_tag ( close_tag % s ) s " tag ) tag input let empty_tag input = function | " string " -> String " " | " array " -> Enum [ ] | " struct " -> Dict [ ] | " nil " -> Null | " value " -> String " " | tag -> parse_error ( sprintf " empty_ % s " tag ) tag tag input let map_tags f input = let tag = open_tag input in let r = if Xmlm . peek input = ` El_end then empty_tag input tag else f input tag in close_tag tag input ; r let map_tag tag f input = let t = open_tag input in if t = tag then ( let r = f input in close_tag tag input ; r ) r else parse_error ( sprintf " open_tag ( open_tag % s ) s " t ) t ( sprintf " open_tag ( open_tag % s ) s " tag ) tag input let name input = map_tag " name " get_data input let data f input = map_tag " data " f input let value f input = let t = open_tag input in if t = " value " then ( let r = match Xmlm . peek input with | ` El_end -> Rpc . String " " | ` Data d -> let _ = Xmlm . input input in if is_empty d && match Xmlm . peek input with | ` El_start _ -> true | _ -> false then f input else Rpc . String d | _ -> f input in close_tag " value " input ; r ) r else parse_error " open_tag ( open_tagvalue ) open_tagvalue " ( sprintf " open_tag ( open_tag % s ) s " t ) t input let members f input = let g input = let name = name input in let value = f name input in name , value in let r = ref [ ] in skip_empty input ; while Xmlm . peek input <> ` El_end do r := map_tag " member " g input :: ! r ; skip_empty input done ; List . rev ! r let make fn ? callback accu data = let r = fn data in match callback with | Some f -> f ( List . rev accu ) accu r ; r | None -> r let make_null = make ( fun ( ) -> Null ) Null let make_int = make ( fun data -> Int ( Int64 . of_string data ) data ) data let make_bool = make ( fun data -> Bool ( if data = " 1 " then true else false ) false ) false let make_float = make ( fun data -> Float ( float_of_string data ) data ) data let make_string = make ( fun data -> String data ) data let make_dateTime = make ( fun data -> DateTime data ) data let make_base64 ( ? base64_decoder = fun s -> Base64 . decode_exn s ) s = make ( fun data -> Base64 ( base64_decoder data ) data ) data let make_enum = make ( fun data -> Enum data ) data let make_dict = make ( fun data -> Dict data ) data let rec of_xml ? callback ? base64_decoder accu input = try value ( map_tags ( basic_types ? callback ? base64_decoder accu ) accu ) accu input with | Xmlm . Error ( ( a , b ) b , e ) e as exn -> eprintf " Characters % i --% i : % s \ n " %! a b ( Xmlm . error_message e ) e ; raise exn | e -> eprintf " % s \ n " %! ( Printexc . to_string e ) e ; raise e and basic_types ? callback ? base64_decoder accu input = function | " int " | " i8 " | " i4 " -> make_int ? callback accu ( get_data input ) input | " boolean " -> make_bool ? callback accu ( get_data input ) input | " double " -> make_float ? callback accu ( get_data input ) input | " string " -> make_string ? callback accu ( get_data input ) input | " dateTime . iso8601 " -> make_dateTime ? callback accu ( get_data input ) input | " base64 " -> make_base64 ? callback ? base64_decoder accu ( get_data input ) input | " array " -> make_enum ? callback accu ( data ( of_xmls ? callback accu ) accu input ) input | " struct " -> make_dict ? callback accu ( members ( fun name -> of_xml ? callback ( name :: accu ) accu ) accu input ) input | " nil " -> make_null ? callback accu ( ) | tag -> parse_error ( sprintf " open_tag ( open_tag % s ) s " tag ) tag " open_tag ( open_tagint / i8 / i4 / boolean / double / string / dateTime . iso8601 / array / struct / nil ) nil " input and of_xmls ? callback accu input = let r = ref [ ] in skip_empty input ; while Xmlm . peek input <> ` El_end do r := of_xml ? callback accu input :: ! r ; skip_empty input done ; List . rev ! r end
let of_string ? callback ? base64_decoder str = let input = Xmlm . make_input ( ` String ( 0 , str ) str ) str in ( match Xmlm . peek input with | ` Dtd _ -> ignore ( Xmlm . input input ) input | _ -> ( ) ) ; Parser . of_xml ? callback ? base64_decoder [ ] input
let of_a ? callback ? base64_decoder ~ next_char b = let aux ( ) = match next_char b with | Some c -> int_of_char c | None -> raise End_of_file in let input = Xmlm . make_input ( ` Fun aux ) aux in Parser . of_xml ? callback ? base64_decoder [ ] input
let call_of_string ? callback ? base64_decoder str = let input = Xmlm . make_input ( ` String ( 0 , str ) str ) str in ( match Xmlm . peek input with | ` Dtd _ -> ignore ( Xmlm . input input ) input | _ -> ( ) ) ; let name = ref " " in let params = ref [ ] in Parser . map_tag " methodCall " ( fun input -> name := Parser . map_tag " methodName " Parser . get_data input ; Parser . map_tag " params " ( fun input -> Parser . skip_empty input ; while Xmlm . peek input <> ` El_end do Parser . map_tag " param " ( fun input -> params := Parser . of_xml ? callback ? base64_decoder [ ] input :: ! params ) params input ; Parser . skip_empty input done ) done input ) input input ; call ! name ( List . rev ! params ) params
let response_of_fault ? callback ? base64_decoder input = Parser . map_tag " fault " ( fun input -> match Parser . of_xml ? callback ? base64_decoder [ ] input with | Dict d -> let fault_code = List . assoc " faultCode " d in let fault_string = List . assoc " faultString " d in failure ( Rpc . Enum [ String " fault " ; fault_code ; fault_string ] ) | r -> parse_error ( to_string r ) r " fault " input ) input input
let response_of_success ? callback ? base64_decoder input = Parser . map_tag " params " ( fun input -> Parser . map_tag " param " ( fun input -> match Parser . of_xml ? callback ? base64_decoder [ ] input with | Dict d -> if List . mem_assoc " Status " d && List . assoc " Status " d = String " Success " && List . mem_assoc " Value " d then success ( List . assoc " Value " d ) d else if List . mem_assoc " Status " d && List . assoc " Status " d = String " Failure " && List . mem_assoc " ErrorDescription " d then failure ( List . assoc " ErrorDescription " d ) d else success ( Dict d ) d | v -> success v ) v input ) input input
let response_of_input ? callback ? base64_decoder input = ( match Xmlm . peek input with | ` Dtd _ -> ignore ( Xmlm . input input ) input | _ -> ( ) ) ; Parser . map_tag " methodResponse " ( fun input -> Parser . skip_empty input ; match Xmlm . peek input with | ` El_start ( ( _ , " params ) " , _ ) _ -> response_of_success ? callback ? base64_decoder input | ` El_start ( ( _ , " fault ) " , _ ) _ -> response_of_fault ? callback ? base64_decoder input | ` El_start ( ( _ , tag ) tag , _ ) _ -> parse_error ( sprintf " open_tag ( open_tag % s ) s " tag ) tag " open_tag ( open_tagfault / params ) params " input | ` Data d -> parse_error ( String . escaped d ) d " open_tag ( open_tagfault / params ) params " input | ` El_end -> parse_error " close_tag " " open_tag ( open_tagfault / params ) params " input | ` Dtd _ -> parse_error " dtd " " open_tag ( open_tagfault / params ) params " input ) input input
let response_of_string ? callback ? base64_decoder str = let input = Xmlm . make_input ( ` String ( 0 , str ) str ) str in response_of_input ? callback ? base64_decoder input
let response_of_in_channel ? callback ? base64_decoder chan = let input = Xmlm . make_input ( ` Channel chan ) chan in response_of_input ? callback ? base64_decoder input
let is_whitespace_only strings = List . for_all is_whitespace_only strings
let parse context namespace report tokens = let open_elements = ref [ ] in let namespaces = Namespace . Parsing . init namespace in let is_fragment = ref false in let fragment_allowed = ref true in let throw = ref ( fun _ -> ( ) ) in let ended = ref ( fun _ -> ( ) ) in let output = ref ( fun _ -> ( ) ) in let rec current_state = ref ( fun ( ) -> match context with | None -> initial_state [ ] | Some ` Document -> fragment_allowed := false ; document_state ( ) | Some ` Fragment -> is_fragment := false ; content_state ( ) ) and emit l signal state = current_state := state ; ! output ( l , signal ) and push_and_emit l { name = raw_name ; attributes } state = Namespace . Parsing . push ( fun ( ) -> report l ) namespaces raw_name attributes ! throw ( fun ( expanded_name , attributes ) -> let rec deduplicate acc attributes k = match attributes with | [ ] -> k ( List . rev acc ) | ( ( n , _ ) as attr ) :: more -> if acc |> List . exists ( fun ( n ' , _ ) -> n ' = n ) then report l ( ` Bad_token ( snd n , " tag " , " duplicate attribute " ) ) ! throw ( fun ( ) -> deduplicate acc more k ) else deduplicate ( attr :: acc ) more k in deduplicate [ ] attributes ( fun attributes -> open_elements := ( l , expanded_name , raw_name ) ::! open_elements ; emit l ( ` Start_element ( expanded_name , attributes ) ) state ) ) and pop l state = match ! open_elements with | [ ] -> state ( ) | _ :: more -> Namespace . Parsing . pop namespaces ; open_elements := more ; emit l ` End_element state and emit_end ( ) = current_state := ( fun ( ) -> ! ended ( ) ) ; ! ended ( ) and initial_state leading = next_expected tokens ! throw begin function | _ , ( ` Xml _ | ` Doctype _ | ` Start _ | ` End _ ) as v -> push tokens v ; push_list tokens ( List . rev leading ) ; document_state ( ) | _ , ` Chars s as v when is_whitespace_only s -> initial_state ( v :: leading ) | _ , ( ` Comment _ | ` PI _ ) as v -> initial_state ( v :: leading ) | _ , ( ` Chars _ | ` EOF ) as v -> is_fragment := true ; push tokens v ; push_list tokens ( List . rev leading ) ; content_state ( ) end and document_state ( ) = next_expected tokens ! throw begin function | l , ` Xml declaration -> fragment_allowed := false ; emit l ( ` Xml declaration ) doctype_state | v -> push tokens v ; doctype_state ( ) end and doctype_state ( ) = next_expected tokens ! throw begin function | l , ` Doctype d -> fragment_allowed := false ; emit l ( ` Doctype d ) root_state | _ , ` Chars s when is_whitespace_only s -> doctype_state ( ) | l , ` Comment s -> emit l ( ` Comment s ) doctype_state | l , ` PI s -> emit l ( ` PI s ) doctype_state | l , ` Xml _ -> report l ( ` Bad_document " XML declaration must be first " ) ! throw doctype_state | l , ` Chars _ -> report l ( ` Bad_document " text at top level " ) ! throw doctype_state | v -> push tokens v ; root_state ( ) end and root_state ( ) = next_expected tokens ! throw begin function | l , ` Start t -> if t . self_closing then push_and_emit l t ( fun ( ) -> pop l after_root_state ) else push_and_emit l t content_state | _ , ` Chars s when is_whitespace_only s -> root_state ( ) | l , ` Comment s -> emit l ( ` Comment s ) root_state | l , ` PI s -> emit l ( ` PI s ) root_state | l , ` Xml _ -> report l ( ` Bad_document " XML declaration must be first " ) ! throw root_state | l , ` EOF -> report l ( ` Unexpected_eoi " document before root element " ) ! throw emit_end | l , _ -> report l ( ` Bad_document " expected root element " ) ! throw root_state end and after_root_state ( ) = next_expected tokens ! throw begin function | _ , ` Chars s when is_whitespace_only s -> after_root_state ( ) | l , ` Comment s -> emit l ( ` Comment s ) after_root_state | l , ` PI s -> emit l ( ` PI s ) after_root_state | _ , ` EOF -> emit_end ( ) | _ , ( ` Chars _ | ` Start _ | ` End _ ) as v when ! fragment_allowed -> is_fragment := true ; push tokens v ; content_state ( ) | l , _ as v -> report l ( ` Bad_document " not allowed after root element " ) ! throw ( fun ( ) -> is_fragment := true ; push tokens v ; content_state ( ) ) end and content_state ( ) = next_expected tokens ! throw begin function | l , ` Start t -> if t . self_closing then push_and_emit l t ( fun ( ) -> pop l content_state ) else push_and_emit l t content_state | l , ` End { name = raw_name } -> Namespace . Parsing . expand_element ( fun ( ) -> report l ) namespaces raw_name ! throw ( fun expanded_name -> let is_on_stack = ! open_elements |> List . exists ( fun ( _ , name , _ ) -> name = expanded_name ) in if not is_on_stack then report l ( ` Unmatched_end_tag raw_name ) ! throw content_state else let rec pop_until_match ( ) = match ! open_elements with | ( _ , name , _ ) :: _ when name = expanded_name -> pop l ( fun ( ) -> match ! open_elements with | [ ] when not ! is_fragment -> after_root_state ( ) | _ -> content_state ( ) ) | ( l ' , _ , name ) :: _ -> report l ' ( ` Unmatched_start_tag name ) ! throw ( fun ( ) -> pop l pop_until_match ) | _ -> failwith " impossible " in pop_until_match ( ) ) | l , ` Chars s -> emit l ( ` Text s ) content_state | l , ` PI s -> emit l ( ` PI s ) content_state | l , ` Comment s -> emit l ( ` Comment s ) content_state | l , ` EOF -> let rec pop_stack ( ) = match ! open_elements with | [ ] -> emit_end ( ) | ( l ' , _ , raw_name ) :: _ -> report l ' ( ` Unmatched_start_tag raw_name ) ! throw ( fun ( ) -> pop l pop_stack ) in pop_stack ( ) | l , ` Xml _ -> report l ( ` Bad_document " XML declaration should be at top level " ) ! throw content_state | l , ` Doctype _ -> report l ( ` Bad_document " doctype should be at top level " ) ! throw content_state end in ( fun throw_ e k -> throw := throw_ ; ended := e ; output := k ; ! current_state ( ) ) |> make
module Xml = struct type xml = | PCData of string | Tag of string * xml | Seq of xml * xml | Empty end
module Stax = struct type token = | Text of string | Open of string | Close of string let pp ppf = function | Text s -> Format . fprintf ppf " text % s " s | Open s -> Format . fprintf ppf " open % s " s | Close s -> Format . fprintf ppf " close % s " s ; ; let equal f d1 d2 = match ( d1 , d2 ) with | Text t1 , Text t2 -> f t1 t2 | Open t1 , Open t2 -> f t1 t2 | Close t1 , Close t2 -> f t1 t2 | _ -> false ; ; end
module Monoid = Preface_stdlib . List . Monoid ( struct type t = Stax . token end )
module Writer = Preface . Writer . Over ( Monoid )
let rec sax_like = let open Xml in let open Stax in let open Writer in function | PCData s -> tell [ Text s ] | Tag ( n , x ) -> let * _ = tell [ Open n ] in let * _ = sax_like x in let * _ = tell [ Close n ] in return ( ) | Seq ( x1 , x2 ) -> let * _ = sax_like x1 in let * _ = sax_like x2 in return ( ) | Empty -> return ( ) ; ;
let sax = Alcotest . testable Stax . pp ( Stax . equal ( = ) )
let should_transform_a_pcdata ( ) = let open Writer in let expected = Stax . [ Text " Hello World " ] and _ , computed = run_identity ( sax_like Xml . ( PCData " Hello World " ) ) in Alcotest . ( check ( list sax ) ) " transform_a_pcdata " expected computed ; ;
let should_transform_a_tag ( ) = let open Writer in let expected = Stax . [ Open " A " ; Close " A " ] and _ , computed = run_identity ( sax_like Xml . ( Tag ( " A " , Empty ) ) ) in Alcotest . ( check ( list sax ) ) " transform_a_tag " expected computed ; ;
let should_transform_a_sequence ( ) = let open Writer in let expected = Stax . [ Open " A " ; Close " A " ; Text " Hello World " ] and _ , computed = run_identity ( sax_like Xml . ( Seq ( Tag ( " A " , Empty ) , PCData " Hello World " ) ) ) in Alcotest . ( check ( list sax ) ) " transform_a_sequence " expected computed ; ;
let should_transform_empty ( ) = let open Writer in let expected = [ ] and _ , computed = run_identity ( sax_like Xml . Empty ) in Alcotest . ( check ( list sax ) ) " transform_empty " expected computed ; ;
let cases = let open Alcotest in [ ( " Xml to Stax reader " , [ test_case " Should transform a pcdata " ` Quick should_transform_a_pcdata ; test_case " Should transform a tag " ` Quick should_transform_a_tag ; test_case " Should transform a sequence " ` Quick should_transform_a_sequence ; test_case " Should transform empty " ` Quick should_transform_empty ] ) ] ; ;
type token = [ ` Xml of xml_declaration | ` Doctype of doctype | ` Start of Token_tag . t | ` End of Token_tag . t | ` Chars of string list | ` PI of string * string | ` Comment of string | ` EOF ]
let is_name_start_char c = is_in_range 0x0041 0x005A c || is_in_range 0x0061 0x007A c || c = 0x003A || c = 0x005F || is_in_range 0x00C0 0x00D6 c || is_in_range 0x00D8 0x00F6 c || is_in_range 0x00F8 0x02FF c || is_in_range 0x0370 0x037D c || is_in_range 0x037F 0x1FFF c || is_in_range 0x200C 0x200D c || is_in_range 0x2070 0x218F c || is_in_range 0x2C00 0x2FEF c || is_in_range 0x3001 0xD7EF c || is_in_range 0xF900 0xFDCF c || is_in_range 0xFDF0 0xFFFD c || is_in_range 0x10000 0xEFFFF c
let is_name_char c = is_name_start_char c || is_in_range 0x0030 0x0039 c || c = 0x002D || c = 0x002E || c = 0x00B7 || is_in_range 0x0300 0x036F c || is_in_range 0x203F 0x2040 c
let resolve_builtin_reference = function | " quot " -> Some " " " \ | " amp " -> Some " " & | " apos " -> Some " ' " | " lt " -> Some " " < | " gt " -> Some " " > | _ -> None
let tokenize report resolve_reference ( input , get_location ) = let resolve_reference s = match resolve_builtin_reference s with | Some _ as v -> v | None -> resolve_reference s in let report_if = Error . report_if report in let throw = ref ( fun _ -> ( ) ) in let ended = ref ( fun _ -> ( ) ) in let output = ref ( fun _ -> ( ) ) in let parse_reference l ' k = let input , restore = checkpoint input in let unresolved ( ) = restore ( ) ; k None in let k s = k ( Some s ) in let unexpected_eoi ( ) = report ( get_location ( ) ) ( ` Unexpected_eoi " reference " ) ! throw ( fun ( ) -> unresolved ( ) ) in let character_reference filter notation_prefix reference_prefix = let buffer = Buffer . create 32 in let rec read ( ) = next input ! throw unexpected_eoi begin function | _ , 0x003B -> if Buffer . length buffer = 0 then report l ' ( ` Bad_token ( Printf . sprintf " &#% s ; " reference_prefix , " reference " , " empty character reference " ) ) ! throw unresolved else let s = Buffer . contents buffer in let maybe_n = try Some ( int_of_string ( notation_prefix ^ s ) ) with Failure _ -> None in begin match maybe_n with | None -> report l ' ( ` Bad_token ( Printf . sprintf " &#% s % s ; " reference_prefix s , " reference " , " number out of range " ) ) ! throw unresolved | Some n -> let utf_8_encoded = Buffer . create 8 in add_utf_8 utf_8_encoded n ; k ( Buffer . contents utf_8_encoded ) end | _ , c when filter c -> add_utf_8 buffer c ; read ( ) | l , c -> report l ( ` Bad_token ( char c , " reference " , " expected digit " ) ) ! throw unresolved end in read ( ) in next input ! throw unexpected_eoi begin function | _ , 0x003B -> report l ' ( ` Bad_token ( " ; " , & " reference " , " empty reference " ) ) ! throw unresolved | _ , 0x0023 -> next input ! throw unexpected_eoi begin function | _ , 0x0078 -> character_reference is_hex_digit " 0x " " x " | _ , c as v when is_digit c || c = 0x003B -> push input v ; character_reference is_digit " " " " | l , c -> report l ( ` Bad_token ( char c , " reference " , " expected digit " ) ) ! throw unresolved end | _ , c when is_name_start_char c -> let buffer = Buffer . create 32 in add_utf_8 buffer c ; let rec read ( ) = next input ! throw unexpected_eoi begin function | _ , 0x003B -> let s = Buffer . contents buffer in begin match resolve_reference s with | Some s -> k s | None -> report l ' ( ` Bad_token ( s , " reference " , " unknown entity " ) ) ! throw unresolved end | _ , c when is_name_char c -> add_utf_8 buffer c ; read ( ) | l , c -> report l ( ` Bad_token ( char c , " reference " , " invalid name character " ) ) ! throw unresolved end in read ( ) | l , c -> report l ( ` Bad_token ( char c , " reference " , " invalid start character " ) ) ! throw unresolved end in let extra_whitespace where l c k = report l ( ` Bad_token ( char c , where , " whitespace not allowed here " ) ) ! throw k in let rec consume_whitespace k = next input ! throw k ( function | _ , c when is_whitespace c -> consume_whitespace k | v -> push input v ; k ( ) ) in let parse_attribute with_references terminators l k ' = let name_buffer = Buffer . create 32 in let value_buffer = Buffer . create 256 in let quote_opened = ref false in let quote_closed = ref false in let finish ( ) = if Buffer . length name_buffer = 0 then k ' None else let emit ( ) = k ' ( Some ( Buffer . contents name_buffer , Buffer . contents value_buffer ) ) in if ! quote_opened then if not ! quote_closed then report ( get_location ( ) ) ( ` Unexpected_eoi " attribute value " ) ! throw emit else emit ( ) else if Buffer . length value_buffer = 0 then report l ( ` Bad_token ( Buffer . contents name_buffer , " attribute " , " has no value " ) ) ! throw emit else emit ( ) in let next ' f = next input ! throw finish begin function | _ , c as v when List . mem c terminators -> push input v ; finish ( ) ; | v -> f v end in let rec name_start_state ( ) = next ' begin function | l , c -> report_if ( not @@ is_name_start_char c ) l ( fun ( ) -> ` Bad_token ( char c , " attribute " , " invalid start character " ) ) ! throw ( fun ( ) -> add_utf_8 name_buffer c ; name_state ( ) ) end and name_state ( ) = next ' begin function | _ , 0x003D -> value_state ( ) | l , c when is_whitespace c -> extra_whitespace " attribute " l c ( fun ( ) -> consume_whitespace equals_state ) | l , c -> report_if ( not @@ is_name_char c ) l ( fun ( ) -> ` Bad_token ( char c , " attribute " , " invalid name character " ) ) ! throw ( fun ( ) -> add_utf_8 name_buffer c ; name_state ( ) ) end and equals_state ( ) = next ' begin function | _ , 0x003D -> value_state ( ) | v -> push input v ; finish ( ) end and value_state ( ) = next ' begin function | l , c when is_whitespace c -> extra_whitespace " attribute " l c ( fun ( ) -> consume_whitespace value_state ) | _ , ( 0x0022 | 0x0027 as c ) -> quote_opened := true ; quoted_value_state c | l , c as v -> push input v ; report l ( ` Bad_token ( char c , " attribute " , " unquoted value " ) ) ! throw unquoted_value_state end and handle_ampersand l state = parse_reference l begin function | Some s -> Buffer . add_string value_buffer s ; state ( ) | None -> report l ( ` Bad_token ( " " , & " attribute " , " replace with ' & amp ; ' " ) ) ! throw ( fun ( ) -> add_utf_8 value_buffer 0x0026 ; state ( ) ) end and handle_lt l state = report l ( ` Bad_token ( " " , < " attribute " , " replace with ' & lt ; ' " ) ) ! throw ( fun ( ) -> add_utf_8 value_buffer 0x003C ; state ( ) ) and quoted_value_state quote = next input ! throw finish begin function | _ , c when c = quote -> quote_closed := true ; finish ( ) | l , 0x0026 when with_references -> handle_ampersand l ( fun ( ) -> quoted_value_state quote ) | l , 0x003C -> handle_lt l ( fun ( ) -> quoted_value_state quote ) | _ , c -> add_utf_8 value_buffer c ; quoted_value_state quote end and unquoted_value_state ( ) = next ' begin function | _ , c as v when is_whitespace c -> push input v ; finish ( ) | l , 0x0026 when with_references -> handle_ampersand l unquoted_value_state | l , 0x003C -> handle_lt l unquoted_value_state | _ , c -> add_utf_8 value_buffer c ; unquoted_value_state ( ) end in name_start_state ( ) in let parse_declaration_or_processing_instruction l k = let pi = " processing instruction " in let xml = " xml declaration " in let target_buffer = Buffer . create 32 in let text_buffer = Buffer . create 512 in let attributes = ref [ ] in let next ' context finish f = let rec initial_state ( ) = next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi context ) ! throw finish ) begin function | l , 0x003F -> question_mark_state l | v -> f v end and question_mark_state l = next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi context ) ! throw finish ) begin function | _ , 0x003E -> finish ( ) | v -> push input v ; f ( l , 0x003F ) end in initial_state ( ) in let rec target_start_state ( ) = next ' pi finish_pi begin function | l , c when is_whitespace c -> extra_whitespace pi l c ( fun ( ) -> consume_whitespace target_start_state ) | l , c -> report_if ( not @@ is_name_start_char c ) l ( fun ( ) -> ` Bad_token ( char c , pi , " invalid start character " ) ) ! throw ( fun ( ) -> add_utf_8 target_buffer c ; target_state ( ) ) end and target_state ( ) = next ' pi finish_pi begin function | _ , c when is_whitespace c -> if String . lowercase_ascii ( Buffer . contents target_buffer ) = " xml " then xml_declaration_state ( ) else text_state ( ) | l , c -> report_if ( not @@ is_name_char c ) l ( fun ( ) -> ` Bad_token ( char c , pi , " invalid name character " ) ) ! throw ( fun ( ) -> add_utf_8 target_buffer c ; target_state ( ) ) end and text_state ( ) = next ' pi finish_pi ( fun ( _ , c ) -> add_utf_8 text_buffer c ; text_state ( ) ) and xml_declaration_state ( ) = next ' xml finish_xml begin function | _ , c when is_whitespace c -> xml_declaration_state ( ) | _ , 0x003F -> xml_declaration_state ( ) | l , _ as v -> push input v ; parse_attribute false [ 0x003F ] l ( function | None -> xml_declaration_state ( ) | Some ( name , value ) -> attributes := ( l , name , value ) ::! attributes ; xml_declaration_state ( ) ) end and finish_pi ( ) = if Buffer . length target_buffer = 0 then report l ( ` Bad_token ( " . . . " , <? pi , " empty " ) ) ! throw ( fun ( ) -> k None ) else if String . lowercase_ascii ( Buffer . contents target_buffer ) = " xml " then finish_xml ( ) else k ( Some ( ` PI ( Buffer . contents target_buffer , Buffer . contents text_buffer ) ) ) and finish_xml ( ) = let split f l = let rec scan prefix = function | x :: suffix when f x -> Some ( List . rev prefix , x , suffix ) | x :: suffix -> scan ( x :: prefix ) suffix | [ ] -> None in scan [ ] l in let matches s ( _ , name , _ ) = String . lowercase_ascii name = s in let version_valid s = String . length s = 3 && s . [ 0 ] = ' 1 ' && s . [ 1 ] = ' . ' && is_digit ( Char . code s . [ 2 ] ) in let rec check_name attributes = let target = Buffer . contents target_buffer in report_if ( target <> " xml " ) l ( fun ( ) -> ` Bad_token ( target , xml , " must be ' xml ' " ) ) ! throw ( fun ( ) -> version_state attributes ) and version_state attributes = match split ( matches " version " ) attributes with | None -> report l ( ` Bad_token ( " <? xml . . . " , xml , " missing version " ) ) ! throw ( fun ( ) -> encoding_state " 1 . 0 " attributes ) | Some ( prefix , ( l , name , value ) , suffix ) -> report_if ( name <> " version " ) l ( fun ( ) -> ` Bad_token ( name , xml , " must be ' version ' " ) ) ! throw ( fun ( ) -> report_if ( List . length prefix <> 0 ) l ( fun ( ) -> ` Bad_token ( name , xml , " must be first " ) ) ! throw ( fun ( ) -> report_if ( not @@ version_valid value ) l ( fun ( ) -> ` Bad_token ( value , xml , " must match 1 . x " ) ) ! throw ( fun ( ) -> encoding_state value ( prefix @ suffix ) ) ) ) and encoding_state version attributes = match split ( matches " encoding " ) attributes with | None -> standalone_state version None 0 attributes | Some ( prefix , ( l , name , value ) , suffix ) -> report_if ( name <> " encoding " ) l ( fun ( ) -> ` Bad_token ( name , xml , " must be ' encoding ' " ) ) ! throw ( fun ( ) -> standalone_state version ( Some value ) ( List . length prefix ) ( prefix @ suffix ) ) and standalone_state version encoding encoding_index attributes = match split ( matches " standalone " ) attributes with | None -> final_state version encoding None attributes | Some ( prefix , ( l , name , value ) , suffix ) -> report_if ( name <> " standalone " ) l ( fun ( ) -> ` Bad_token ( name , xml , " must be ' standalone ' " ) ) ! throw ( fun ( ) -> report_if ( List . length prefix < encoding_index ) l ( fun ( ) -> ` Bad_token ( name , xml , " must come after ' encoding ' " ) ) ! throw ( fun ( ) -> ( fun k -> match value with | " yes " -> k ( Some true ) | " no " -> k ( Some false ) | _ -> report l ( ` Bad_token ( value , xml , " must be ' yes ' or ' no ' " ) ) ! throw ( fun ( ) -> match String . lowercase_ascii value with | " yes " -> k ( Some true ) | " no " -> k ( Some false ) | _ -> k None ) ) ( fun v -> final_state version encoding v ( prefix @ suffix ) ) ) ) and final_state version encoding standalone attributes = ( fun k -> match attributes with | ( l , name , _ ) :: _ -> report l ( ` Bad_token ( name , xml , " not allowed here " ) ) ! throw k | [ ] -> k ( ) ) ( fun ( ) -> k ( Some ( ` Xml { version ; encoding ; standalone } ) ) ) in check_name ( List . rev ! attributes ) in target_start_state ( ) in let text = Text . prepare ( ) in let note_character_location = Text . note_location text in let add_character = Text . add text in let add_string = Text . add_string text in let rec current_state = ref initial_state and emit ' l t s = current_state := s ; ! output ( l , t ) and emit_chars state = match Text . emit text with | None -> state ( ) | Some ( l , strings ) -> emit ' l ( ` Chars strings ) state and emit l t state = emit_chars ( fun ( ) -> emit ' l t state ) and emit_eoi ? during ( ) = let l = get_location ( ) in emit_chars ( fun ( ) -> ( fun k ' -> match during with | None -> k ' ( ) | Some production -> report l ( ` Unexpected_eoi production ) ! throw k ' ) ( fun ( ) -> emit ' l ` EOF ( fun ( ) -> ! ended ( ) ) ) ) and emit_start l name self_closing attributes state = let tag = { name = name ; self_closing ; attributes = List . rev attributes } in emit l ( ` Start tag ) state and emit_end l name state = let tag = { name = name ; self_closing = false ; attributes = [ ] } in emit l ( ` End tag ) state and emit_doctype l buffer s = let doctype = { doctype_name = None ; public_identifier = None ; system_identifier = None ; raw_text = Some ( Buffer . contents buffer ) ; force_quirks = false } in emit l ( ` Doctype doctype ) s and lt_in_text l k = report l ( ` Bad_token ( " " , < " text " , " replace with ' & lt ; ' " ) ) ! throw k and initial_state ( ) = next input ! throw ( fun ( ) -> emit_eoi ( ) ) begin function | l , ( 0x005D as c ) -> add_character l c ; one_bracket_state l | l , 0x003C -> begin_markup_state l | l , ( 0x0026 as c ) -> parse_reference l ( function | None -> report l ( ` Bad_token ( char c , " text " , " replace with ' & amp ; ' " ) ) ! throw ( fun ( ) -> add_character l c ; initial_state ( ) ) | Some s -> add_string l s ; initial_state ( ) ) | l , c -> add_character l c ; initial_state ( ) end and one_bracket_state l ' = next_option input ! throw begin function | Some ( l , ( 0x005D as c ) ) -> add_character l c ; two_brackets_state l ' l | v -> push_option input v ; initial_state ( ) end and two_brackets_state l ' l ' ' = next_option input ! throw begin function | Some ( l , ( 0x003E as c ) ) -> report l ' ( ` Bad_token ( " ] ] " , > " text " , " must end a CDATA section " ) ) ! throw ( fun ( ) -> add_character l c ; initial_state ( ) ) | Some ( l , ( 0x005D as c ) ) -> add_character l c ; two_brackets_state l ' ' l | v -> push_option input v ; initial_state ( ) end and begin_markup_state l ' = let recover v = lt_in_text l ' ( fun ( ) -> add_character l ' 0x003C ; push_option input v ; initial_state ( ) ) in next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi " tag " ) ! throw ( fun ( ) -> recover None ) ) begin function | _ , 0x0021 -> comment_cdata_or_doctype_state l ' | _ , 0x003F -> parse_declaration_or_processing_instruction l ' ( function | None -> initial_state ( ) | Some token -> emit l ' token initial_state ) | _ , 0x002F -> end_tag_state l ' | _ , c when is_name_start_char c -> let tag_name_buffer = Buffer . create 32 in add_utf_8 tag_name_buffer c ; start_tag_state l ' tag_name_buffer | l , c as v -> report l ( ` Bad_token ( char c , " tag " , " invalid start character " ) ) ! throw ( fun ( ) -> recover ( Some v ) ) end and start_tag_state l ' buffer = let recover v = lt_in_text l ' ( fun ( ) -> add_character l ' 0x003C ; add_string l ' ( Buffer . contents buffer ) ; push_option input v ; initial_state ( ) ) in next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi " tag " ) ! throw ( fun ( ) -> recover None ) ) begin function | _ , 0x003E -> emit_start l ' ( Buffer . contents buffer ) false [ ] initial_state | l , 0x002F -> close_empty_element_state l ' l ( Buffer . contents buffer ) [ ] | _ , c when is_whitespace c -> attributes_state l ' ( Buffer . contents buffer ) [ ] | _ , c when is_name_char c -> add_utf_8 buffer c ; start_tag_state l ' buffer | l , c as v -> report l ( ` Bad_token ( char c , " tag " , " invalid name character " ) ) ! throw ( fun ( ) -> recover ( Some v ) ) end and attributes_state l ' tag_name attributes = next input ! throw begin fun ( ) -> emit_start l ' tag_name false attributes ( fun ( ) -> emit_eoi ~ during " : tag " ( ) ) end begin function | _ , c when is_whitespace c -> attributes_state l ' tag_name attributes | _ , 0x003E -> emit_start l ' tag_name false attributes initial_state | l , 0x002F -> close_empty_element_state l ' l tag_name attributes | l , _ as v -> push input v ; parse_attribute true [ 0x003E ; 0x002F ] l ( function | None -> attributes_state l ' tag_name attributes | Some ( name , value ) -> attributes_state l ' tag_name ( ( name , value ) :: attributes ) ) end and close_empty_element_state l ' l ' ' name attributes = next input ! throw begin fun ( ) -> emit_start l ' name true attributes ( fun ( ) -> emit_eoi ~ during " : tag " ( ) ) end begin function | _ , 0x003E -> emit_start l ' name true attributes initial_state | v -> report l ' ' ( ` Bad_token ( char 0x002F , " tag " , " should be part of ' ' " ) ) /> ! throw ( fun ( ) -> push input v ; attributes_state l ' name attributes ) end and end_tag_state l ' = let recover v = lt_in_text l ' ( fun ( ) -> add_character l ' 0x003C ; add_character l ' 0x002F ; push_option input v ; initial_state ( ) ) in next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi " tag " ) ! throw ( fun ( ) -> recover None ) ) begin function | _ , c when is_name_start_char c -> let name_buffer = Buffer . create 32 in add_utf_8 name_buffer c ; end_tag_name_state l ' name_buffer | l , c as v -> report l ( ` Bad_token ( char c , " tag " , " invalid start character " ) ) ! throw ( fun ( ) -> recover ( Some v ) ) end and end_tag_name_state l ' buffer = let recover v = lt_in_text l ' ( fun ( ) -> add_character l ' 0x003C ; add_character l ' 0x002F ; add_string l ' ( Buffer . contents buffer ) ; push_option input v ; initial_state ( ) ) in next input ! throw ( fun ( ) -> report ( get_location ( ) ) ( ` Unexpected_eoi " tag " ) ! throw ( fun ( ) -> recover None ) ) begin function | _ , 0x003E -> emit_end l ' ( Buffer . contents buffer ) initial_state | _ , c when is_whitespace c -> end_tag_whitespace_state false l ' ( Buffer . contents buffer ) | _ , c when is_name_char c -> add_utf_8 buffer c ; end_tag_name_state l ' buffer | l , c as v -> report l ( ` Bad_token ( char c , " tag " , " invalid name character " ) ) ! throw ( fun ( ) -> recover ( Some v ) ) end and end_tag_whitespace_state reported l ' name = next input ! throw begin fun ( ) -> emit_end l ' name ( fun ( ) -> emit_eoi ~ during " : tag " ( ) ) end begin function | _ , 0x003E -> emit_end l ' name initial_state | _ , c when is_whitespace c -> end_tag_whitespace_state reported l ' name | l , c -> if not reported then report l ( ` Bad_token ( char c , " tag " , " attribute in end tag " ) ) ! throw ( fun ( ) -> end_tag_whitespace_state true l ' name ) else end_tag_whitespace_state reported l ' name end and bad_comment_start s l k ' = report l ( ` Bad_token ( s , " comment " , " should start with ' ' " ) ) <!-- ! throw ( fun ( ) -> lt_in_text l k ' ) and comment_cdata_or_doctype_state l ' = next_option input ! throw begin function | Some ( _ , 0x002D ) -> comment_start_state l ' | Some ( _ , 0x005B ) -> cdata_start_state l ' | Some ( _ , 0x0044 ) -> doctype_start_state l ' | v -> bad_comment_start " " <! l ' ( fun ( ) -> add_character l ' 0x003C ; add_character l ' 0x0021 ; push_option input v ; initial_state ( ) ) end and comment_start_state l ' = next_option input ! throw begin function | Some ( _ , 0x002D ) -> comment_state l ' ( Buffer . create 256 ) | v -> bad_comment_start " " <!- l ' ( fun ( ) -> add_character l ' 0x003C ; add_character l ' 0x0021 ; add_character l ' 0x002D ; push_option input v ; initial_state ( ) ) end and unterminated_comment l buffer = emit l ( ` Comment ( Buffer . contents buffer ) ) ( fun ( ) -> emit_eoi ~ during " : comment " ( ) ) and comment_state l ' buffer = next input ! throw ( fun ( ) -> unterminated_comment l ' buffer ) begin function | l , 0x002D -> comment_one_dash_state l ' l buffer | _ , c -> add_utf_8 buffer c ; comment_state l ' buffer end and comment_one_dash_state l ' l ' ' buffer = next input ! throw ( fun ( ) -> unterminated_comment l ' buffer ) begin function | _ , 0x002D -> comment_two_dashes_state false l ' l ' ' buffer | _ , c -> add_utf_8 buffer 0x002D ; add_utf_8 buffer c ; comment_state l ' buffer end and comment_two_dashes_state reported l ' l ' ' buffer = let recover k ' = if reported then k ' ( ) else report l ' ' ( ` Bad_token ( " " , -- " comment " , " should be followed by ' ' " ) ) > ! throw k ' in next input ! throw ( fun ( ) -> unterminated_comment l ' buffer ) begin function | _ , 0x003E -> emit l ' ( ` Comment ( Buffer . contents buffer ) ) initial_state | _ , 0x002D -> recover ( fun ( ) -> add_utf_8 buffer 0x002D ; comment_two_dashes_state true l ' l ' ' buffer ) | _ , c -> recover ( fun ( ) -> add_utf_8 buffer 0x002D ; add_utf_8 buffer 0x002D ; add_utf_8 buffer c ; comment_state l ' buffer ) end and cdata_start_state l ' = next_n 6 input ! throw begin function | [ _ , 0x43 ; _ , 0x44 ; _ , 0x41 ; _ , 0x54 ; _ , 0x41 ; _ , 0x005B ] -> note_character_location l ' ; cdata_state l ' | cs -> report l ' ( ` Bad_token ( " [ " , <! " cdata " , " should start with ' [ <! CDATA [ ' " ) ) ! throw ( fun ( ) -> lt_in_text l ' ( fun ( ) -> push_list input cs ; add_character l ' 0x003C ; add_character l ' 0x0021 ; add_character l ' 0x005B ; initial_state ( ) ) ) end and cdata_state l ' = next input ! throw ( fun ( ) -> emit_eoi ~ during " : cdata " ( ) ) begin function | l , 0x005D -> cdata_one_bracket_state l ' l | l , c -> add_character l c ; cdata_state l ' end and cdata_one_bracket_state l ' l ' ' = next input ! throw ( fun ( ) -> emit_eoi ~ during " : cdata " ( ) ) begin function | l , 0x005D -> cdata_two_brackets_state l ' l ' ' l | l , c -> add_character l ' ' 0x005D ; add_character l c ; cdata_state l ' end and cdata_two_brackets_state l ' l ' ' l ' ' ' = next input ! throw ( fun ( ) -> emit_eoi ~ during " : cdata " ( ) ) begin function | _ , 0x003E -> initial_state ( ) | l , 0x005D -> add_character l ' ' 0x005D ; cdata_two_brackets_state l ' l ' ' ' l | l , c -> add_character l ' ' 0x005D ; add_character l ' ' ' 0x005D ; add_character l c ; cdata_state l ' end and doctype_start_state l ' = next_n 7 input ! throw begin function | [ _ , 0x4F ; _ , 0x43 ; _ , 0x54 ; _ , 0x59 ; _ , 0x50 ; _ , 0x45 ; _ , c ] when is_whitespace c -> doctype_state l ' ( Buffer . create 512 ) | cs -> report l ' ( ` Bad_token ( " <! D " , " doctype " , " should start with ' <! DOCTYPE ' " ) ) ! throw ( fun ( ) -> lt_in_text l ' ( fun ( ) -> push_list input cs ; add_character l ' 0x003C ; add_character l ' 0x0021 ; add_character l ' 0x0044 ; initial_state ( ) ) ) end and unterminated_doctype l buffer = emit_doctype l buffer ( fun ( ) -> emit_eoi ~ during " : doctype " ( ) ) and doctype_state l ' buffer = next input ! throw ( fun ( ) -> unterminated_doctype l ' buffer ) begin function | _ , 0x003E -> emit_doctype l ' buffer initial_state | _ , ( 0x0022 | 0x0027 as c ) -> add_utf_8 buffer c ; doctype_quoted_state ( fun ( ) -> doctype_state l ' buffer ) c l ' buffer | _ , ( 0x003C as c ) -> add_utf_8 buffer c ; doctype_item_state ( fun ( ) -> doctype_state l ' buffer ) l ' buffer | _ , c -> add_utf_8 buffer c ; doctype_state l ' buffer end and doctype_quoted_state state quote l ' buffer = next input ! throw ( fun ( ) -> unterminated_doctype l ' buffer ) begin function | _ , c when c = quote -> add_utf_8 buffer c ; state ( ) | _ , c -> add_utf_8 buffer c ; doctype_quoted_state state quote l ' buffer end and doctype_item_state state l ' buffer = next input ! throw ( fun ( ) -> unterminated_doctype l ' buffer ) begin function | _ , ( 0x0021 as c ) -> add_utf_8 buffer c ; doctype_declaration_state state l ' buffer | l , ( 0x003F as c ) -> add_utf_8 buffer c ; let undo = tap ( fun ( _ , c ) -> add_utf_8 buffer c ) input in parse_declaration_or_processing_instruction l ( fun _ -> undo ( ) ; state ( ) ) | _ , c -> add_utf_8 buffer c ; state ( ) end and doctype_declaration_state state l ' buffer = next input ! throw ( fun ( ) -> unterminated_doctype l ' buffer ) begin function | _ , ( 0x003E as c ) -> add_utf_8 buffer c ; state ( ) | _ , ( 0x0022 | 0x0027 as c ) -> add_utf_8 buffer c ; doctype_quoted_state ( fun ( ) -> doctype_declaration_state state l ' buffer ) c l ' buffer | _ , c -> add_utf_8 buffer c ; doctype_declaration_state state l ' buffer end in ( fun throw_ e k -> throw := throw_ ; ended := e ; output := k ; ! current_state ( ) ) |> make
let escape s = let buffer = Buffer . create ( String . length s ) in String . iter ( function | ' " ' -> Buffer . add_string buffer " & quot ; " | ' ' & -> Buffer . add_string buffer " & amp ; " | ' ' ' \ -> Buffer . add_string buffer " & apos ; " | ' ' < -> Buffer . add_string buffer " & lt ; " | ' ' > -> Buffer . add_string buffer " & gt ; " | c -> Buffer . add_char buffer c ) s ; Buffer . contents buffer
let attribute_strings end_ attributes = let rec prepend_attributes words = function | [ ] -> words | ( name , value ) :: more -> prepend_attributes ( " " :: name " " " ( ::=\:: escape value ) " " " ::\:: words ) more in prepend_attributes [ end_ ] ( List . rev attributes )
let write report prefix signals = let signals = enumerate signals in let open_elements = ref [ ] in let namespaces = Namespace . Writing . init prefix in let rec queue = ref next_signal and emit_list l throw e k = match l with | [ ] -> next_signal throw e k | s :: more -> queue := emit_list more ; k s and next_signal throw e k = next signals throw e begin function | i , ( ` Start_element ( name , attributes ) as signal ) -> ( fun k ' -> next signals throw ( fun ( ) -> k ' false ) ( fun s -> match s with | _ , ` End_element -> k ' true | _ , ( ` Text _ | ` Start_element _ | ` Comment _ | ` PI _ | ` Doctype _ | ` Xml _ ) -> push signals s ; k ' false ) ) ( fun self_closing -> Namespace . Writing . push ( fun ( ) -> report ( signal , i ) ) namespaces name attributes throw ( fun ( formatted_name , formatted_attributes ) -> open_elements := formatted_name ::! open_elements ; if self_closing then begin Namespace . Writing . pop namespaces ; open_elements := match ! open_elements with | [ ] -> [ ] | _ :: rest -> rest end ; let end_ = if self_closing then " " /> else " " > in let tag = " " <:: formatted_name ( :: attribute_strings end_ formatted_attributes ) in emit_list tag throw e k ) ) | _ , ` End_element -> Namespace . Writing . pop namespaces ; begin match ! open_elements with | [ ] -> next_signal throw e k | name :: rest -> open_elements := rest ; emit_list [ " " ; </ name ; " " ] > throw e k end | _ , ` Text ss -> if List . for_all ( fun s -> String . length s = 0 ) ss then next_signal throw e k else emit_list ( List . map escape ss ) throw e k | _ , ` Xml { version ; encoding ; standalone } -> let attributes = match standalone with | None -> [ ] | Some true -> [ " standalone " , " yes " ] | Some false -> [ " standalone " , " no " ] in let attributes = match encoding with | None -> attributes | Some encoding -> ( " encoding " , encoding ) :: attributes in let attributes = ( " version " , version ) :: attributes in let declaration = " <? xml " ( :: attribute_strings " " ?> attributes ) in emit_list declaration throw e k | _ , ` Doctype { raw_text } -> begin match raw_text with | None -> next_signal throw e k | Some text -> emit_list [ " <! DOCTYPE " ; text ; " " ] > throw e k end | _ , ` PI ( target , s ) -> emit_list [ " " ; <? target ; " " ; s ; " " ] ?> throw e k | _ , ` Comment s -> emit_list [ " " ; <!-- s ; " " ] --> throw e k end in ( fun throw e k -> ! queue throw e k ) |> make
let array_call = " < methodCall >\ n \ \ < methodName > event . register </ methodName >\ n \ \ < params >\ n \ \ < param >\ n \ \ < value > OpaqueRef : 8ecbbb2a - a905 - d422 - 1153 - fadc00639b12 </ value >\ n \ \ </ param >\ n \ \ < param >\ n \ \ < value >\ n \ \ < array >\ n \ \ < data >\ n \ \ < value > pbd </ value >\ n \ \ </ data >\ n \ \ </ array >\ n \ \ </ value >\ n \ \ </ param >\ n \ \ </ params >\ n \ </ methodCall >\ n "
let simple_call = " < methodCall >\ n \ \ < methodName > session . login_with_password </ methodName >\ n \ \ < params >\ n \ \ < param >\ n \ \ < value />\ n \ \ </ param >\ n \ \ < param >\ n \ \ < value />\ n \ \ </ param >\ n \ \ < param >\ n \ \ < value > 1 . 4 </ value >\ n \ \ </ param >\ n \ \ </ params >\ n \ </ methodCall >\ n "
let error = " < methodResponse >\ n \ < fault >\ n \ < value >< struct >\ n \ < member >\ n \ < name > faultCode </ name >\ n \ < value >< int > 143 </ int ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > faultString </ name >\ n \ < value >< string > Failed to parse the request </ string ></ value >\ n \ </ member >\ n \ </ struct ></ value >\ n \ </ fault >\ n \ </ methodResponse >\ n "
let sm = " <? xml version = ' 1 . 0 ' ?>\ n \ < methodResponse >\ n \ < params >\ n \ < param >\ n \ < value >< struct >\ n \ < member >\ n \ < name > required_api_version </ name >\ n \ < value >< string > 1 . 0 </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > vendor </ name >\ n \ < value >< string > Citrix Systems Inc </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > name </ name >\ n \ < value >< string > Local EXT3 VHD </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > copyright </ name >\ n \ < value >< string ( > C ) C 2008 Citrix Systems Inc </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > capabilities </ name >\ n \ < value >< array >< data >\ n \ < value >< string > SR_PROBE </ string ></ value >\ n \ < value >< string > SR_UPDATE </ string ></ value >\ n \ < value >< string > VDI_CREATE </ string ></ value >\ n \ < value >< string > VDI_DELETE </ string ></ value >\ n \ < value >< string > VDI_ATTACH </ string ></ value >\ n \ < value >< string > VDI_DETACH </ string ></ value >\ n \ < value >< string > VDI_UPDATE </ string ></ value >\ n \ < value >< string > VDI_CLONE </ string ></ value >\ n \ < value >< string > VDI_SNAPSHOT </ string ></ value >\ n \ < value >< string > VDI_RESIZE </ string ></ value >\ n \ < value >< string > VDI_RESIZE_ONLINE </ string ></ value >\ n \ </ data ></ array ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > driver_version </ name >\ n \ < value >< string > 1 . 0 </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > configuration </ name >\ n \ < value >< array >< data >\ n \ < value >< struct >\ n \ < member >\ n \ < name > description </ name >\ n \ < value >< string > local device path ( required ) required ( e . g . / dev / sda3 ) sda3 </ string ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > key </ name >\ n \ < value >< string > device </ string ></ value >\ n \ </ member >\ n \ </ struct ></ value >\ n \ </ data ></ array ></ value >\ n \ </ member >\ n \ < member >\ n \ < name > description </ name >\ n \ < value >< string > SR plugin which represents disks as VHD files stored on a local EXT3 \ filesystem , created inside an LVM volume </ string ></ value >\ n \ </ member >\ n \ </ struct ></ value >\ n \ </ param >\ n \ </ params >\ n \ </ methodResponse >\ n "
let base64 = " \ n \ \ < methodResponse >\ n \ < params >\ n \ < param >\ n \ < value >< base64 > SGVsbG8sIHdvcmxkIQ ==</ base64 ></ value >\ n \ </ param >\ n \ </ params >\ n \ </ methodResponse >\ n \ n "
let base64_call = " < methodCall >\ n \ \ < methodName > send_file </ methodName >\ n \ \ < params >\ n \ \ < param >\ n \ \ < value >\ n \ \ < base64 > SGVsbG8sIHdvcmxkIQ ==</ base64 > </ value >\ n \ \ </ param >\ n \ \ </ params >\ n \ </ methodCall >\ n "
let run ( ) = Printf . printf " Parsing SM XML . . . " ; %! let _ = Xmlrpc . response_of_string sm in Printf . printf " OK \ nParsing empty tags . . . " ; %! let _ = Xmlrpc . of_string empty in Printf . printf " OK \ nParsing error . . . " ; %! let _ = Xmlrpc . response_of_string error in Printf . printf " OK \ nParsing simple call . . . " ; %! let _ = Xmlrpc . call_of_string simple_call in Printf . printf " OK \ nParsing array call . . . " ; %! let _ = Xmlrpc . call_of_string array_call in Printf . printf " OK \ n " ; %! let b64 = Xmlrpc . response_of_string base64 in Printf . printf " Base64 response : % s \ n " ( Rpc . to_string b64 . contents ) contents ; assert ( b64 . contents = Rpc . Base64 " Hello , world ) " ; ! let b64_req = Xmlrpc . call_of_string base64_call in Printf . printf " Base64 request : % s \ n " ( Rpc . string_of_call b64_req ) b64_req ; assert ( List . hd b64_req . params = Rpc . Base64 " Hello , world ) " !
let tests = [ " Xapi XML tests " , ` Quick , run ]
module ID = struct type t = string let compare = String . compare end
module XMPPClient = XMPP . Make ( Lwt ) Lwt ( Xmlstream . XmlStream ) XmlStream ( IDCallback ) IDCallback
let stanza_error_to_str se = String . concat " " [ string_of_error_type se . err_type ; string_of_condition se . err_condition ; se . err_text ; se . err_lang ]
let presence_to_xmpp = function | ` Offline -> ( Some Unavailable , None ) None | ` Online -> ( None , None ) None | ` Free -> ( None , Some ShowChat ) ShowChat | ` Away -> ( None , Some ShowAway ) ShowAway | ` DoNotDisturb -> ( None , Some ShowDND ) ShowDND | ` ExtendedAway -> ( None , Some ShowXA ) ShowXA
let xmpp_to_presence = function | None -> ` Online | Some ShowChat -> ` Free | Some ShowAway -> ` Away | Some ShowDND -> ` DoNotDisturb | Some ShowXA -> ` ExtendedAway
module Version = XEP_version . Make ( XMPPClient ) XMPPClient
module Disco = XEP_disco . Make ( XMPPClient ) XMPPClient
module Roster = Roster . Make ( XMPPClient ) XMPPClient
module Xep_muc = XEP_muc . Make ( XMPPClient ) XMPPClient
type user_data = { log : ? kind : User . chatkind -> User . direction -> string -> unit Lwt . t ; locallog : ? kind : User . chatkind -> string -> string -> unit Lwt . t ; message : Xjid . bare_jid -> string option -> ? timestamp : Ptime . t -> string -> unit Lwt . t ; group_message : Xjid . t -> Ptime . t option -> string option -> string option -> Xep_muc . User . data option -> string option -> unit Lwt . t ; received_receipts : Xjid . t -> string list -> unit Lwt . t ; update_receipt_state : Xjid . t -> User . receipt_state -> unit Lwt . t ; subscription : Xjid . t -> User . subscription_mod -> string option -> unit Lwt . t ; presence : Xjid . t -> User . presence -> int -> string option -> unit Lwt . t ; group_presence : Xjid . t -> User . presence -> string option -> Xep_muc . User . data -> unit Lwt . t ; create_room : Xjid . bare_jid -> bool -> unit Lwt . t ; reset_users : unit -> unit Lwt . t ; update_users : ( Xjid . t * string option * string list * User . subscription * User . property list ) list list -> bool -> unit Lwt . t ; }
let request_disco t jid = let callback ev jid_from _jid_to _lang ( ) = let receipt = match ev with | IQError _ -> ` Unsupported | IQResult el -> match el with | Some ( Xml . Xmlelement ( ( ns , " query ) " , _ , els ) els ) els when ns = Disco . ns_disco_info -> let receipt = match ns_receipts with None -> assert false | Some x -> x in let tst = function | Xml . Xmlelement ( ( _ , " feature ) " , attrs , _ ) _ -> Xml . safe_get_attr_value " var " attrs = receipt | _ -> false in if List . exists tst els then ` Supported else ` Unsupported | _ -> ` Unsupported in match jid_from with | None -> fail BadRequest | Some x -> match Xjid . string_to_jid x with | None -> fail BadRequest | Some jid -> t . user_data . update_receipt_state jid receipt in t . user_data . update_receipt_state jid ` Requested >>= fun ( ) -> let jid_to = Xjid . jid_to_xmpp_jid jid in make_iq_request t ~ jid_to ( IQGet ( Disco . make_disco_query [ ] ) ) callback
module Keepalive = struct let ping_urn = " urn : xmpp : ping " let keepalive_running : bool ref = ref false let keepalive_ping t = let callback _ev _jid_from _jid_to _lang ( ) = keepalive_running := false ; Lwt . return_unit in if ! keepalive_running then fail ( Invalid_argument " ping timeout ) " else let jid_to = JID . of_string ( t . myjid . JID . ldomain ) ldomain in keepalive_running := true ; make_iq_request t ~ jid_to ( IQGet ( Xml . make_element ( Some ping_urn , " ping ) " [ ] [ ] ) ) callback let keepalive : Lwt_engine . event option ref = ref None let cancel_keepalive ( ) = match ! keepalive with | None -> ( ) | Some x -> Lwt_engine . stop_event x ; keepalive := None let rec restart_keepalive t = cancel_keepalive ( ) ; let doit ( ) = keepalive_ping t >|= fun ( ) -> restart_keepalive t in keepalive := Some ( Lwt_engine . on_timer 45 . false ( fun _ -> Lwt . async doit ) doit ) doit end
let send_msg t ( ? kind = Chat ) Chat jid receipt id body = let x = match receipt , id with | true , Some _ -> [ Xml . Xmlelement ( ( ns_receipts , " request ) " , [ ] , [ ] ) ] | _ -> [ ] in let jid_to = Xjid . jid_to_xmpp_jid jid in send_message t ~ kind ~ jid_to ~ body ~ x ? id ( )
let delayed_timestamp = function | None -> None | Some delay -> match Ptime . of_rfc3339 delay . delay_stamp with | Ok ( time , _ , _ ) _ -> Some time | Error _ -> None
let receipt_id = function | Xml . Xmlelement ( ( ns_rec , " received ) " , attrs , _ ) _ when ns_rec = ns_receipts -> ( match Xml . safe_get_attr_value " id " attrs with | " " -> [ ] | id -> [ id ] id ) id | _ -> [ ]
let answer_receipt stanza_id = function | Xml . Xmlelement ( ( ns_rec , " request ) " , _ , _ ) _ when ns_rec = ns_receipts -> let qname = ( ns_receipts , " received ) " in [ Xml . Xmlelement ( qname , [ Xml . make_attr " id " stanza_id ] stanza_id , [ ] ) ] | _ -> [ ]
let maybe_element qname x = try Some ( Xml . get_element qname x ) x with Not_found -> None
let message_callback ( t : user_data session_data ) session_data stanza = Keepalive . restart_keepalive t ; match stanza . jid_from with | None -> t . user_data . locallog " error " " no from in stanza " | Some jidt -> let jid = Xjid . xmpp_jid_to_jid jidt in match stanza . content . message_type with | Some Groupchat -> let timestamp = delayed_timestamp stanza . content . message_delay and data = match maybe_element ( Xep_muc . ns_muc_user , " x ) " stanza . x with | None -> None | Some e -> Some ( Xep_muc . User . decode e ) e and id = stanza . id in t . user_data . group_message jid timestamp stanza . content . subject stanza . content . body data id | _ -> let receipts = List . flatten ( List . map receipt_id stanza . x ) x in t . user_data . received_receipts jid receipts >>= fun ( ) -> match stanza . content . body , delayed_timestamp stanza . content . message_delay , jid with | None , _ , _ -> Lwt . return_unit | Some v , timestamp , ` Bare b -> t . user_data . message b None ? timestamp v | Some v , Some timestamp , ` Full ( bare , r ) r -> t . user_data . message bare ( Some r ) r ~ timestamp v | Some v , None , ` Full ( bare , r ) r -> t . user_data . message bare ( Some r ) r v >>= fun ( ) -> let answer_receipts = match stanza . id with | None -> [ ] | Some id -> List . flatten ( List . map ( answer_receipt id ) id stanza . x ) x in let jid_to = stanza . jid_from in Lwt_list . iter_s ( fun x -> send_message t ? jid_to ~ kind : Chat ~ x [ : x ] x ( ) ) answer_receipts
let message_error t ? id ? jid_from ? jid_to ? lang error = Keepalive . restart_keepalive t ; ignore id ; ignore jid_to ; ignore lang ; let jid = match jid_from with | None -> ` Bare ( " unknown " , " host ) " | Some x -> Xjid . xmpp_jid_to_jid x in let msg = let con = " error ; reason : " ^ ( string_of_condition error . err_condition ) err_condition in match error . err_text with | x when x = " " -> con | x -> con ^ " , message : " ^ x in t . user_data . log ( ` From jid ) jid msg
let presence_callback t stanza = Keepalive . restart_keepalive t ; match stanza . jid_from with | None -> t . user_data . locallog " error " " presence received without sending jid , ignoring " | Some jidt -> let jid = Xjid . xmpp_jid_to_jid jidt and status = match stanza . content . status with | None -> None | Some x when x = " " -> None | Some x -> Some x in match maybe_element ( Xep_muc . ns_muc_user , " x ) " stanza . x with | Some el -> let pres = match stanza . content . presence_type with | Some Unavailable -> ` Offline | None -> xmpp_to_presence stanza . content . show | _ -> assert false and data = Xep_muc . User . decode el in t . user_data . group_presence jid pres status data | None -> let priority = match stanza . content . priority with | None -> 0 | Some x -> x and to_u = function | Unavailable -> assert false | Probe -> ` Probe | Subscribe -> ` Subscribe | Subscribed -> ` Subscribed | Unsubscribe -> ` Unsubscribe | Unsubscribed -> ` Unsubscribed in match stanza . content . presence_type with | None -> t . user_data . presence jid ( xmpp_to_presence stanza . content . show ) show priority status | Some Unavailable -> t . user_data . presence jid ` Offline priority status | Some x -> t . user_data . subscription jid ( to_u x ) x status
let presence_error t ? id ? jid_from ? jid_to ? lang error = Keepalive . restart_keepalive t ; ignore id ; ignore jid_to ; ignore lang ; let jid = match jid_from with | None -> ` Bare ( " unknown " , " host ) " | Some x -> Xjid . xmpp_jid_to_jid x in let msg = let con = " presence error ; reason : " ^ ( string_of_condition error . err_condition ) err_condition in match error . err_text with | x when x = " " -> con | x -> con ^ " , message : " ^ x in t . user_data . log ( ` From jid ) jid msg
let roster_callback item = try let subscription = match item . Roster . subscription with | Roster . SubscriptionRemove -> ` Remove | Roster . SubscriptionBoth -> ` Both | Roster . SubscriptionNone -> ` None | Roster . SubscriptionFrom -> ` From | Roster . SubscriptionTo -> ` To in let properties = let app = if item . Roster . approved then [ ` PreApproved ] else [ ] in let ask = match item . Roster . ask with | Some _ -> [ ` Pending ] | None -> [ ] in app @ ask in let name = if item . Roster . name = " " then None else Some item . Roster . name in let groups = item . Roster . group in let jid = Xjid . xmpp_jid_to_jid item . Roster . jid in Some ( jid , name , groups , subscription , properties ) properties with _ -> None