text
stringlengths
12
786k
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
let session_callback ( kind , show , status , priority ) priority mvar t = let err txt = t . user_data . locallog " handling error " txt in register_iq_request_handler t Roster . ns_roster ( fun ev jid_from jid_to _lang ( ) -> match ev with | IQGet _el -> fail BadRequest | IQSet el -> ( match jid_from , jid_to with | None , _ -> Lwt . return_unit | Some x , Some y -> ( try let from_jid = JID . of_string x and to_jid = JID . of_string y in if JID . is_bare from_jid && JID . equal ( JID . bare_jid to_jid ) to_jid from_jid then Lwt . return_unit else fail BadRequest with _ -> fail BadRequest ) BadRequest | _ -> fail BadRequest ) BadRequest >>= fun ( ) -> match el with | Xml . Xmlelement ( ( ns_roster , " query ) " , attrs , els ) els when ns_roster = Roster . ns_roster -> begin match snd ( Roster . decode attrs els ) els with | [ item ] -> let users = match roster_callback item with | None -> [ ] | Some x -> [ x ] x in t . user_data . update_users users true >|= fun ( ) -> IQResult None | _ -> fail BadRequest end | _ -> fail BadRequest ) BadRequest ; register_stanza_handler t ( ns_client , " message ) " ( fun t attrs eles -> ( try parse_message ~ callback : message_callback ~ callback_error : message_error t attrs eles with _ -> err " during message parsing , ignoring ) ) " ; register_stanza_handler t ( ns_client , " presence ) " ( fun t attrs eles -> ( try parse_presence ~ callback : presence_callback ~ callback_error : presence_error t attrs eles with _ -> err " during presence parsing , ignoring ) ) " ; register_iq_request_handler t Disco . ns_disco_info ( fun ev _jid_from _jid_to _lang ( ) -> match ev with | IQSet _el -> fail BadRequest | IQGet _ -> match ns_receipts with | None -> fail BadRequest | Some x -> let feature = Disco . make_feature_var x in let query = Disco . make_disco_query [ feature ] feature in return ( IQResult ( Some query ) query ) query ) ; Roster . get t ( fun ? jid_from ? jid_to ? lang ? ver items -> ignore jid_from ; ignore jid_to ; ignore lang ; ignore ver ; let mods = List . map roster_callback items in t . user_data . reset_users ( ) >>= fun ( ) -> let users = List . fold_left ( fun acc -> function None -> acc | Some x -> x :: acc ) acc [ ] mods in t . user_data . update_users users false ) false >>= fun ( ) -> send_presence t ? kind ? show ? status ? priority ( ) >>= fun ( ) -> Keepalive . restart_keepalive t ; mvar t
let tls_epoch_to_line t = let open Tls in match Tls_lwt . Unix . epoch t with | Ok epoch -> let version = epoch . Core . protocol_version and cipher = epoch . Core . ciphersuite in Ok Sexplib . Sexp ( . to_string_hum ( List [ Core . sexp_of_tls_version version ; Ciphersuite . sexp_of_ciphersuite cipher ] ) ) | Error ( ) -> Error " error while fetching TLS parameters "
let connect socket_data myjid ? host password presence authenticator user_data mvar = let module Socket_module = struct type t = PlainSocket . socket let socket = socket_data include PlainSocket end in let tls_socket ( ) = TLSSocket . switch socket_data ? host authenticator >>= fun socket_data -> ( match tls_epoch_to_line socket_data with | Ok str -> user_data . locallog ~ kind ` : Success " TLS session info " str | Error str -> user_data . locallog ~ kind ` : Error " TLS session info " str ) str >>= fun ( ) -> let module TLS_module = struct type t = Tls_lwt . Unix . t let socket = socket_data include TLSSocket end in return ( module TLS_module : XMPPClient . Socket ) Socket in let myjid = Xjid . jid_to_xmpp_jid ( ` Full myjid ) myjid in XMPPClient . setup_session ~ user_data ~ myjid ~ plain_socket ( : module Socket_module : XMPPClient . Socket ) Socket ~ tls_socket ~ password ( session_callback presence mvar ) mvar
let close session_data = let module S = ( val session_data . socket : Socket ) Socket in S . close S . socket
let parse_loop session_data = XMPPClient . parse session_data >>= fun ( ) -> close session_data
let ( debug_out : Lwt_unix . file_descr option ref ) ref = ref None
let dbg data = match ! debug_out with | None -> Lwt . return ( ) | Some x -> let now = Unix . localtime ( Unix . time ( ) ) in let msg = Printf . sprintf [ " % 02d :% 02d :% 02d ] 02d % s \ n " now . Unix . tm_hour now . Unix . tm_min now . Unix . tm_sec data in Persistency . write_data x ( Bytes . of_string msg ) msg
module PlainSocket = struct type ' a z = ' a Lwt . t type fd = Lwt_unix . file_descr type socket = fd let read fd buf start len = Lwt_unix . read fd buf start len >>= fun size -> dbg ( " IN : " ^ Bytes . to_string ( Bytes . sub buf start size ) size ) size >|= fun ( ) -> size let write fd str = dbg ( " OUT : " ^ Bytes . to_string str ) str >>= fun ( ) -> let len = Bytes . length str in let rec aux_send start = Lwt_unix . write fd str start ( len - start ) start >>= fun sent -> if sent = 0 then Lwt . return ( ) else aux_send ( start + sent ) sent in aux_send 0 let close fd = Lwt_unix . close fd end
module TLSSocket = struct let read s buf start len = let cs = Cstruct . create len in Tls_lwt . Unix . read s cs >>= fun size -> ( if size > 0 then ( Cstruct . blit_to_bytes cs start buf 0 size ; dbg ( " IN TLS : " ^ Bytes . to_string ( Bytes . sub buf start size ) size ) size ) size else Lwt . return ( ) ) >|= fun ( ) -> size let write s bs = let str = Bytes . to_string bs in dbg ( " OUT TLS : " ^ str ) str >>= fun ( ) -> Tls_lwt . Unix . write s ( Cstruct . of_string str ) str let switch fd ? host authenticator = let config = Tls . Config . client ~ authenticator ( ) in Tls_lwt . Unix . client_of_fd config ? host fd let close s = Tls_lwt . Unix . close s end
let cautious f ppf arg = try f ppf arg with Ellipsis -> fprintf ppf " . . . "
let parenthesized_ident name = ( List . mem name [ " or " ; " mod " ; " land " ; " lor " ; " lxor " ; " lsl " ; " lsr " ; " asr " ] ) || ( match name . [ 0 ] with | ' a ' . . ' z ' | ' A ' . . ' Z ' | ' \ 223 ' . . ' \ 246 ' | ' \ 248 ' . . ' \ 255 ' | ' _ ' | ' { ' | ' ( ' -> false | _ -> true )
let value_ident ppf name = if parenthesized_ident name then fprintf ppf " ( % s ) " name else pp_print_string ppf name
let rec print_ident ppf = function | Oide_ident " " -> assert false | Oide_ident s when Some ps <-- Packpath . parse s -> begin match ps with | [ ] -> assert false | p :: _ -> let s = if String . length s <= String . length p + 6 then s else " { " ^ p ^ " , . . . } " in pp_print_string ppf s end | Oide_ident s -> value_ident ppf s | Oide_dot ( id , s ) -> print_ident ppf id ; pp_print_char ppf ' . ' ; value_ident ppf s | Oide_apply ( id1 , id2 ) -> fprintf ppf " % a ( % a ) " print_ident id1 print_ident id2
let valid_float_lexeme s = let l = String . length s in let rec loop i = if i >= l then s ^ " . " else match s . [ i ] with | ' 0 ' . . ' 9 ' | ' ' - -> loop ( i + 1 ) | _ -> s in loop 0
let float_repres f = match classify_float f with FP_nan -> " nan " | FP_infinite -> if f < 0 . 0 then " neg_infinity " else " infinity " | _ -> let float_val = let s1 = Printf . sprintf " . % 12g " f in if f = float_of_string s1 then s1 else let s2 = Printf . sprintf " . % 15g " f in if f = float_of_string s2 then s2 else Printf . sprintf " . % 18g " f in valid_float_lexeme float_val
let parenthesize_if_neg ppf fmt v isneg = if isneg then pp_print_char ppf ' ( ' ; fprintf ppf fmt v ; if isneg then pp_print_char ppf ' ) '
let print_out_value ppf tree = let rec print_tree_1 ppf = function | Oval_constr ( name , [ param ] ) -> fprintf ppf " [ @< 1 >% a @ % a ] " @ print_ident name print_constr_param param | Oval_constr ( name , ( _ :: _ as params ) ) -> fprintf ppf " [ @< 1 >% a @ ( % a ) ] " @ print_ident name ( print_tree_list print_tree_1 " , " ) params | Oval_variant ( name , Some param ) -> fprintf ppf " [ @< 2 ` >% s @ % a ] " @ name print_constr_param param | tree -> print_simple_tree ppf tree and print_constr_param ppf = function | Oval_int i -> parenthesize_if_neg ppf " % i " i ( i < 0 ) | Oval_int32 i -> parenthesize_if_neg ppf " % lil " i ( i < 0l ) | Oval_int64 i -> parenthesize_if_neg ppf " % LiL " i ( i < 0L ) | Oval_nativeint i -> parenthesize_if_neg ppf " % nin " i ( i < 0n ) | Oval_float f -> parenthesize_if_neg ppf " % s " ( float_repres f ) ( f < 0 . 0 ) | tree -> print_simple_tree ppf tree and print_simple_tree ppf = function Oval_int i -> fprintf ppf " % i " i | Oval_int32 i -> fprintf ppf " % lil " i | Oval_int64 i -> fprintf ppf " % LiL " i | Oval_nativeint i -> fprintf ppf " % nin " i | Oval_float f -> pp_print_string ppf ( float_repres f ) | Oval_char c -> fprintf ppf " % C " c | Oval_string s -> begin try fprintf ppf " % S " s with Invalid_argument _ -> fprintf ppf " < huge string " > end | Oval_list tl -> fprintf ppf " [ @< 1 [ >% a ] ] " @ ( print_tree_list print_tree_1 " ; " ) tl | Oval_array tl -> fprintf ppf " [ @< 2 [ >|% a ] ] " |@ ( print_tree_list print_tree_1 " ; " ) tl | Oval_constr ( name , [ ] ) -> print_ident ppf name | Oval_variant ( name , None ) -> fprintf ppf " ` % s " name | Oval_stuff s -> pp_print_string ppf s | Oval_record fel -> fprintf ppf " [ @< 1 { >% a } ] " @ ( cautious ( print_fields true ) ) fel | Oval_ellipsis -> raise Ellipsis | Oval_printer f -> f ppf | Oval_tuple tree_list -> fprintf ppf " [ @< 1 ( >% a ) ] " @ ( print_tree_list print_tree_1 " , " ) tree_list | tree -> fprintf ppf " [ @< 1 ( >% a ) ] " @ ( cautious print_tree_1 ) tree and print_fields first ppf = function [ ] -> ( ) | ( name , tree ) :: fields -> if not first then fprintf ppf " ; @ " ; fprintf ppf " [ @< 1 >% a @ =@ % a ] " @ print_ident name ( cautious print_tree_1 ) tree ; print_fields false ppf fields and print_tree_list print_item sep ppf tree_list = let rec print_list first ppf = function [ ] -> ( ) | tree :: tree_list -> if not first then fprintf ppf " % s @ " sep ; print_item ppf tree ; print_list false ppf tree_list in cautious ( print_list true ) ppf tree_list in cautious print_tree_1 ppf tree
let out_value = ref print_out_value
let rec print_list_init pr sep ppf = function [ ] -> ( ) | a :: l -> sep ppf ; pr ppf a ; print_list_init pr sep ppf l
let rec print_list pr sep ppf = function [ ] -> ( ) | [ a ] -> pr ppf a | a :: l -> pr ppf a ; sep ppf ; print_list pr sep ppf l
let pr_present = print_list ( fun ppf s -> fprintf ppf " ` % s " s ) ( fun ppf -> fprintf ppf " @ " )
let pr_vars = print_list ( fun ppf s -> fprintf ppf " ' % s " s ) ( fun ppf -> fprintf ppf " @ " )
let rec print_out_type ppf = function | Otyp_alias ( ty , s ) -> fprintf ppf " [ @% a @ as ' % s ] " @ print_out_type ty s | Otyp_poly ( sl , ty ) -> fprintf ppf " [ @< hov 2 >% a . @ % a ] " @ pr_vars sl print_out_type ty | ty -> print_out_type_1 ppf ty function Otyp_arrow ( lab , ty1 , ty2 ) -> pp_open_box ppf 0 ; if lab <> " " then ( pp_print_string ppf lab ; pp_print_char ppf ' ' ) ; : print_out_type_2 ppf ty1 ; pp_print_string ppf " " ; -> pp_print_space ppf ( ) ; print_out_type_1 ppf ty2 ; pp_close_box ppf ( ) | ty -> print_out_type_2 ppf ty function Otyp_tuple tyl -> fprintf ppf " [ @< 0 >% a ] " @ ( print_typlist print_simple_out_type " " ) * tyl | ty -> print_simple_out_type ppf ty function Otyp_class ( ng , id , tyl ) -> fprintf ppf " [ @% a % s #% a ] " @ print_typargs tyl ( if ng then " _ " else " " ) print_ident id | Otyp_constr ( id , tyl ) -> pp_open_box ppf 0 ; print_typargs ppf tyl ; print_ident ppf id ; pp_close_box ppf ( ) | Otyp_object ( fields , rest ) -> fprintf ppf " [ @< 2 >< % a ] " >@ ( print_fields rest ) fields | Otyp_stuff s -> pp_print_string ppf s | Otyp_var ( ng , s ) -> fprintf ppf " ' % s % s " ( if ng then " _ " else " " ) s | Otyp_variant ( non_gen , row_fields , closed , tags ) -> let print_present ppf = function None | Some [ ] -> ( ) | Some l -> fprintf ppf " ; @< 1 - 2 >> [ @< hov >% a ] " @ pr_present l in let print_fields ppf = function Ovar_fields fields -> print_list print_row_field ( fun ppf -> fprintf ppf " ; @< 1 - 2 >| " ) ppf fields | Ovar_name ( id , tyl ) -> fprintf ppf " [ @% a % a ] " @ print_typargs tyl print_ident id in fprintf ppf " % s [ % s [ @< hv [ >@< hv >% a ] @% a ] ] " @ ( if non_gen then " _ " else " " ) ( if closed then if tags = None then " " else " < " else if tags = None then " > " else " ? " ) print_fields row_fields print_present tags | Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty -> pp_open_box ppf 1 ; pp_print_char ppf ' ( ' ; print_out_type ppf ty ; pp_print_char ppf ' ) ' ; pp_close_box ppf ( ) | Otyp_abstract | Otyp_open | Otyp_sum _ | Otyp_manifest ( _ , _ ) -> ( ) | Otyp_record lbls -> print_record_decl ppf lbls | Otyp_module ( p , n , tyl ) -> fprintf ppf " [ @< 1 ( > module % s " p ; let first = ref true in List . iter2 ( fun s t -> let sep = if ! first then ( first := false ; " with " ) else " and " in fprintf ppf " % s type % s = % a " sep s print_out_type t ) n tyl ; fprintf ppf " ) ] " @ | Otyp_attribute ( t , attr ) -> fprintf ppf " [ @< 1 ( >% a [ @@% s ] ) ] " @ print_out_type t attr . oattr_name fprintf ppf " { % a ; @< 1 - 2 } " > ( print_list_init print_out_label ( fun ppf -> fprintf ppf " @ " ) ) lbls function [ ] -> begin match rest with Some non_gen -> fprintf ppf " % s . . " ( if non_gen then " _ " else " " ) | None -> ( ) end | [ s , t ] -> fprintf ppf " % s : % a " s print_out_type t ; begin match rest with Some _ -> fprintf ppf " ; @ " | None -> ( ) end ; print_fields rest ppf [ ] | ( s , t ) :: l -> fprintf ppf " % s : % a ; @ % a " s print_out_type t ( print_fields rest ) l let pr_of ppf = if opt_amp then fprintf ppf " of @ &@ " else if tyl <> [ ] then fprintf ppf " of @ " else fprintf ppf " " in fprintf ppf " [ @< hv 2 ` >% s % t % a ] " @ l pr_of ( print_typlist print_out_type " " ) & tyl function [ ] -> ( ) | [ ty ] -> print_elem ppf ty | ty :: tyl -> print_elem ppf ty ; pp_print_string ppf sep ; pp_print_space ppf ( ) ; print_typlist print_elem sep ppf tyl function [ ] -> ( ) | [ ty1 ] -> print_simple_out_type ppf ty1 ; pp_print_space ppf ( ) | tyl -> pp_open_box ppf 1 ; pp_print_char ppf ' ( ' ; print_typlist print_out_type " , " ppf tyl ; pp_print_char ppf ' ) ' ; pp_close_box ppf ( ) ; pp_print_space ppf ( ) fprintf ppf " [ @< 2 >% s % s :@ % a ] ; " @ ( if mut then " mutable " else " " ) name print_out_type arg
let out_type = ref print_out_type
let type_parameter ppf ( ty , ( co , cn ) ) = fprintf ppf " % s % s " ( if not cn then " " + else if not co then " " - else " " ) ( if ty = " _ " then ty else " ' " ^ ty )
let print_out_class_params ppf = function [ ] -> ( ) | tyl -> fprintf ppf " [ @< 1 [ >% a ] ] @@ " ( print_list type_parameter ( fun ppf -> fprintf ppf " , " ) ) tyl
let rec print_out_class_type ppf = function Octy_constr ( id , tyl ) -> let pr_tyl ppf = function [ ] -> ( ) | tyl -> fprintf ppf " [ @< 1 [ >% a ] ] @@ " ( print_typlist ! out_type " , " ) tyl in fprintf ppf " [ @% a % a ] " @ pr_tyl tyl print_ident id | Octy_arrow ( lab , ty , cty ) -> fprintf ppf " [ @% s % a ->@ % a ] " @ ( if lab <> " " then lab ^ " " : else " " ) print_out_type_2 ty print_out_class_type cty | Octy_signature ( self_ty , csil ) -> let pr_param ppf = function Some ty -> fprintf ppf " @ [ ( @% a ) ] " @ ! out_type ty | None -> ( ) in fprintf ppf " [ @< hv 2 [ >@< 2 > object % a ] @@ % a ; @< 1 - 2 > end ] " @ pr_param self_ty ( print_list print_out_class_sig_item ( fun ppf -> fprintf ppf " @ " ) ) csil function Ocsg_constraint ( ty1 , ty2 ) -> fprintf ppf " [ @< 2 > constraint % a =@ % a ] " @ ! out_type ty1 ! out_type ty2 | Ocsg_method ( name , priv , virt , ty ) -> fprintf ppf " [ @< 2 > method % s % s % s :@ % a ] " @ ( if priv then " private " else " " ) ( if virt then " virtual " else " " ) name ! out_type ty | Ocsg_value ( name , mut , vr , ty ) -> fprintf ppf " [ @< 2 > val % s % s % s :@ % a ] " @ ( if mut then " mutable " else " " ) ( if vr then " virtual " else " " ) name ! out_type ty
let out_class_type = ref print_out_class_type
let out_module_type = ref ( fun _ -> failwith " Xoprint . out_module_type " )
let out_sig_item = ref ( fun _ -> failwith " Xoprint . out_sig_item " )
let out_signature = ref ( fun _ -> failwith " Xoprint . out_signature " )
let out_type_extension = ref ( fun _ -> failwith " Xoprint . out_type_extension " )
let rec print_out_functor funct ppf = function Omty_functor ( _ , None , mty_res ) -> if funct then fprintf ppf " ( ) % a " ( print_out_functor true ) mty_res else fprintf ppf " functor @ ( ) % a " ( print_out_functor true ) mty_res | Omty_functor ( name , Some mty_arg , mty_res ) -> begin match name , funct with | " _ " , true -> fprintf ppf " ->@ % a ->@ % a " print_out_module_type mty_arg ( print_out_functor false ) mty_res | " _ " , false -> fprintf ppf " % a ->@ % a " print_out_module_type mty_arg ( print_out_functor false ) mty_res | name , true -> fprintf ppf " ( % s : % a ) % a " name print_out_module_type mty_arg ( print_out_functor true ) mty_res | name , false -> fprintf ppf " functor @ ( % s : % a ) % a " name print_out_module_type mty_arg ( print_out_functor true ) mty_res end | m -> if funct then fprintf ppf " ->@ % a " print_out_module_type m else print_out_module_type ppf m function Omty_abstract -> ( ) | Omty_functor _ as t -> fprintf ppf " [ @< 2 >% a ] " @ ( print_out_functor false ) t | Omty_ident id -> fprintf ppf " % a " print_ident id | Omty_signature sg -> fprintf ppf " [ @< hv 2 > sig @ % a ; @< 1 - 2 > end ] " @ ! out_signature sg | Omty_alias id -> fprintf ppf " ( module % a ) " print_ident id function [ ] -> ( ) | [ item ] -> ! out_sig_item ppf item | Osig_typext ( ext , Oext_first ) :: items -> let rec gather_extensions acc items = match items with Osig_typext ( ext , Oext_next ) :: items -> gather_extensions ( ( ext . oext_name , ext . oext_args , ext . oext_ret_type ) :: acc ) items | _ -> ( List . rev acc , items ) in let exts , items = gather_extensions [ ( ext . oext_name , ext . oext_args , ext . oext_ret_type ) ] items in let te = { otyext_name = ext . oext_type_name ; otyext_params = ext . oext_type_params ; otyext_constructors = exts ; otyext_private = ext . oext_private } in fprintf ppf " % a @ % a " ! out_type_extension te print_out_signature items | item :: items -> fprintf ppf " % a @ % a " ! out_sig_item item print_out_signature items function Osig_class ( vir_flag , name , params , clt , rs ) -> fprintf ppf " [ @< 2 >% s % s @ % a % s @ :@ % a ] " @ ( if rs = Orec_next then " and " else " class " ) ( if vir_flag then " virtual " else " " ) print_out_class_params params name ! out_class_type clt | Osig_class_type ( vir_flag , name , params , clt , rs ) -> fprintf ppf " [ @< 2 >% s % s @ % a % s @ =@ % a ] " @ ( if rs = Orec_next then " and " else " class type " ) ( if vir_flag then " virtual " else " " ) print_out_class_params params name ! out_class_type clt | Osig_typext ( ext , Oext_exception ) -> fprintf ppf " [ @< 2 > exception % a ] " @ print_out_constr ( ext . oext_name , ext . oext_args , ext . oext_ret_type ) | Osig_typext ( ext , es ) -> print_out_extension_constructor ppf ext | Osig_modtype ( name , Omty_abstract ) -> fprintf ppf " [ @< 2 > module type % s ] " @ name | Osig_modtype ( name , mty ) -> fprintf ppf " [ @< 2 > module type % s =@ % a ] " @ name ! out_module_type mty | Osig_module ( name , Omty_alias id , _ ) -> fprintf ppf " [ @< 2 > module % s =@ % a ] " @ name print_ident id | Osig_module ( name , mty , rs ) -> fprintf ppf " [ @< 2 >% s % s :@ % a ] " @ ( match rs with Orec_not -> " module " | Orec_first -> " module rec " | Orec_next -> " and " ) name ! out_module_type mty | Osig_type ( td , rs ) -> print_out_type_decl ( match rs with | Orec_not -> " type nonrec " | Orec_first -> " type " | Orec_next -> " and " ) ppf td | Osig_value vd -> let kwd = if vd . oval_prims = [ ] then " val " else " external " in let pr_prims ppf _ = ( ) in fprintf ppf " [ @< 2 >% s % a :@ % a % a % a ] " @ kwd value_ident vd . oval_name ! out_type vd . oval_type pr_prims vd . oval_prims ( fun ppf -> List . iter ( fun a -> fprintf ppf " @ [ @@@@% s ] " a . oattr_name ) ) vd . oval_attributes | Osig_ellipsis -> fprintf ppf " . . . " let print_constraints ppf = List . iter ( fun ( ty1 , ty2 ) -> fprintf ppf " @ [ @< 2 > constraint % a =@ % a ] " @ ! out_type ty1 ! out_type ty2 ) td . otype_cstrs in let type_defined ppf = match td . otype_params with [ ] -> pp_print_string ppf td . otype_name | [ param ] -> fprintf ppf " [ @% a @ % s ] " @ type_parameter param td . otype_name | _ -> fprintf ppf " [ ( [ @@% a ) ] @@ % s ] " @ ( print_list type_parameter ( fun ppf -> fprintf ppf " , @ " ) ) td . otype_params td . otype_name in let print_manifest ppf = function Otyp_manifest ( ty , _ ) -> fprintf ppf " =@ % a " ! out_type ty | _ -> ( ) in let print_name_params ppf = fprintf ppf " % s % t % a " kwd type_defined print_manifest td . otype_type in let ty = match td . otype_type with Otyp_manifest ( _ , ty ) -> ty | _ -> td . otype_type in let print_private ppf = function Asttypes . Private -> fprintf ppf " private " | Asttypes . Public -> ( ) in let print_immediate ppf = if td . otype_immediate then fprintf ppf " [ %@%@ immediate ] " else ( ) in let print_out_tkind ppf = function | Otyp_abstract -> ( ) | Otyp_record lbls -> fprintf ppf " =% a % a " print_private td . otype_private print_record_decl lbls | Otyp_sum constrs -> fprintf ppf " =% a ; @< 1 2 >% a " print_private td . otype_private ( print_list print_out_constr ( fun ppf -> fprintf ppf " @ | " ) ) constrs | Otyp_open -> fprintf ppf " = . . " | ty -> fprintf ppf " =% a ; @< 1 2 >% a " print_private td . otype_private ! out_type ty in fprintf ppf " [ @< 2 [ >@< hv 2 >% t % a ] @% t % t ] " @ print_name_params print_out_tkind ty print_constraints print_immediate match ret_type_opt with | None -> begin match tyl with | [ ] -> pp_print_string ppf name | _ -> fprintf ppf " [ @< 2 >% s of @ % a ] " @ name ( print_typlist print_simple_out_type " " ) * tyl end | Some ret_type -> begin match tyl with | [ ] -> fprintf ppf " [ @< 2 >% s :@ % a ] " @ name print_simple_out_type ret_type | _ -> fprintf ppf " [ @< 2 >% s :@ % a -> % a ] " @ name ( print_typlist print_simple_out_type " " ) * tyl print_simple_out_type ret_type end let print_extended_type ppf = let print_type_parameter ppf ty = fprintf ppf " % s " ( if ty = " _ " then ty else " ' " ^ ty ) in match ext . oext_type_params with [ ] -> fprintf ppf " % s " ext . oext_type_name | [ ty_param ] -> fprintf ppf " [ @% a @ % s ] " @ print_type_parameter ty_param ext . oext_type_name | _ -> fprintf ppf " [ ( [ @@% a ) ] @@ % s ] " @ ( print_list print_type_parameter ( fun ppf -> fprintf ppf " , @ " ) ) ext . oext_type_params ext . oext_type_name in fprintf ppf " [ @< hv 2 > type % t +=% s ; @< 1 2 >% a ] " @ print_extended_type ( if ext . oext_private = Asttypes . Private then " private " else " " ) print_out_constr ( ext . oext_name , ext . oext_args , ext . oext_ret_type ) let print_extended_type ppf = let print_type_parameter ppf ty = fprintf ppf " % s " ( if ty = " _ " then ty else " ' " ^ ty ) in match te . otyext_params with [ ] -> fprintf ppf " % s " te . otyext_name | [ param ] -> fprintf ppf " [ @% a @ % s ] " @ print_type_parameter param te . otyext_name | _ -> fprintf ppf " [ ( [ @@% a ) ] @@ % s ] " @ ( print_list print_type_parameter ( fun ppf -> fprintf ppf " , @ " ) ) te . otyext_params te . otyext_name in fprintf ppf " [ @< hv 2 > type % t +=% s ; @< 1 2 >% a ] " @ print_extended_type ( if te . otyext_private = Asttypes . Private then " private " else " " ) ( print_list print_out_constr ( fun ppf -> fprintf ppf " @ | " ) ) te . otyext_constructors
let _ = out_module_type := print_out_module_type
let _ = out_signature := print_out_signature
let _ = out_sig_item := print_out_sig_item
let _ = out_type_extension := print_out_type_extension