text
stringlengths
12
786k
let resize indexfun h = let odata = h . data in let osize = Array . length odata in let nsize = osize * 2 in if nsize < Sys . max_array_length then begin let ndata = Array . make nsize Empty in h . data <- ndata ; let rec insert_bucket = function Empty -> ( ) | Cons ( key , data , rest ) -> insert_bucket rest ; let nidx = indexfun h key in a_set ndata nidx @@ Cons ( key , data , a_get ndata nidx ) in for i = 0 to osize - 1 do insert_bucket @@ a_get odata i done end
let key_index h key = if Obj . size ( Obj . repr h ) >= 3 then ( seeded_hash_param 10 100 h . seed key ) land ( Array . length h . data - 1 ) else ( old_hash_param 10 100 key ) mod ( Array . length h . data )
let add h key info = let i = key_index h key in let bucket = Cons ( key , info , a_get h . data i ) in a_set h . data i bucket ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h
let remove h key = let rec remove_bucket = function | Empty -> Empty | Cons ( k , i , next ) -> if compare k key = 0 then begin h . size <- h . size - 1 ; next end else Cons ( k , i , remove_bucket next ) in let i = key_index h key in a_set h . data i @@ remove_bucket @@ a_get h . data i
let rec find_rec key = function | Empty -> raise Not_found | Cons ( k , d , rest ) -> if compare key k = 0 then d else find_rec key rest
let find h key = match a_get h . data @@ key_index h key with | Empty -> raise Not_found | Cons ( k1 , d1 , rest1 ) -> if compare key k1 = 0 then d1 else match rest1 with | Empty -> raise Not_found | Cons ( k2 , d2 , rest2 ) -> if compare key k2 = 0 then d2 else match rest2 with | Empty -> raise Not_found | Cons ( k3 , d3 , rest3 ) -> if compare key k3 = 0 then d3 else find_rec key rest3
let find_all h key = let rec find_in_bucket = function | Empty -> [ ] | Cons ( k , d , rest ) -> if compare k key = 0 then d :: find_in_bucket rest else find_in_bucket rest in find_in_bucket @@ a_get h . data @@ key_index h key
let replace h key info = let rec replace_bucket = function | Empty -> raise Not_found | Cons ( k , i , next ) -> if compare k key = 0 then Cons ( key , info , next ) else Cons ( k , i , replace_bucket next ) in let i = key_index h key in let l = a_get h . data i in try a_set h . data i @@ replace_bucket l with Not_found -> a_set h . data i @@ Cons ( key , info , l ) ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h
let mem h key = let rec mem_in_bucket = function | Empty -> false | Cons ( k , _d , rest ) -> compare k key = 0 || mem_in_bucket rest in mem_in_bucket @@ a_get h . data @@ key_index h key
let iter f h = let rec do_bucket = function | Empty -> ( ) | Cons ( k , d , rest ) -> f k d ; do_bucket rest in let d = h . data in for i = 0 to Array . length d - 1 do do_bucket @@ a_get d i done
let fold f h init = let rec do_bucket b accu = match b with Empty -> accu | Cons ( k , d , rest ) -> do_bucket rest ( f k d accu ) in let d = h . data in let accu = ref init in for i = 0 to Array . length d - 1 do accu := do_bucket ( a_get d i ) ! accu done ; ! accu
type statistics = { num_bindings : int ; num_buckets : int ; max_bucket_length : int ; bucket_histogram : int array }
let rec bucket_length accu = function | Empty -> accu | Cons ( _ , _ , rest ) -> bucket_length ( accu + 1 ) rest
let stats h = let mbl = Array . fold_left ( fun m b -> max m ( bucket_length 0 b ) ) 0 h . data in let histo = Array . make ( mbl + 1 ) 0 in Array . iter ( fun b -> let l = bucket_length 0 b in a_set histo l @@ a_get histo l + 1 ) h . data ; { num_bindings = h . size ; num_buckets = Array . length h . data ; max_bucket_length = mbl ; bucket_histogram = histo }
module type HashedType = sig type t val equal : t -> t -> bool val hash : t -> int end
module type SeededHashedType = sig type t val equal : t -> t -> bool val hash : int -> t -> int end
module type S = sig type key type ' a t val create : int -> ' a t val clear : ' a t -> unit val reset : ' a t -> unit val copy : ' a t -> ' a t val add : ' a t -> key -> ' a -> unit val remove : ' a t -> key -> unit val find : ' a t -> key -> ' a val find_all : ' a t -> key -> ' a list val replace : ' a t -> key -> ' a -> unit val mem : ' a t -> key -> bool val iter : ( key -> ' a -> unit ) -> ' a t -> unit val fold : ( key -> ' a -> ' b -> ' b ) -> ' a t -> ' b -> ' b val length : ' a t -> int val stats : ' a t -> statistics end
module type SeededS = sig type key type ' a t val create : ? random : bool -> int -> ' a t val clear : ' a t -> unit val reset : ' a t -> unit val copy : ' a t -> ' a t val add : ' a t -> key -> ' a -> unit val remove : ' a t -> key -> unit val find : ' a t -> key -> ' a val find_all : ' a t -> key -> ' a list val replace : ' a t -> key -> ' a -> unit val mem : ' a t -> key -> bool val iter : ( key -> ' a -> unit ) -> ' a t -> unit val fold : ( key -> ' a -> ' b -> ' b ) -> ' a t -> ' b -> ' b val length : ' a t -> int val stats : ' a t -> statistics end
module MakeSeeded ( H : SeededHashedType ) : ( SeededS with type key = H . t ) = struct type key = H . t type ' a hashtbl = ( key , ' a ) t type ' a t = ' a hashtbl let create = create let clear = clear let reset = reset let copy = copy let key_index h key = ( H . hash h . seed key ) land ( Array . length h . data - 1 ) let add h key info = let i = key_index h key in let bucket = Cons ( key , info , a_get h . data i ) in a_set h . data i bucket ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h let remove h key = let rec remove_bucket = function | Empty -> Empty | Cons ( k , i , next ) -> if H . equal k key then begin h . size <- h . size - 1 ; next end else Cons ( k , i , remove_bucket next ) in let i = key_index h key in a_set h . data i @@ remove_bucket @@ a_get h . data i let rec find_rec key = function | Empty -> raise Not_found | Cons ( k , d , rest ) -> if H . equal key k then d else find_rec key rest let find h key = match a_get h . data @@ key_index h key with | Empty -> raise Not_found | Cons ( k1 , d1 , rest1 ) -> if H . equal key k1 then d1 else match rest1 with | Empty -> raise Not_found | Cons ( k2 , d2 , rest2 ) -> if H . equal key k2 then d2 else match rest2 with | Empty -> raise Not_found | Cons ( k3 , d3 , rest3 ) -> if H . equal key k3 then d3 else find_rec key rest3 let find_all h key = let rec find_in_bucket = function | Empty -> [ ] | Cons ( k , d , rest ) -> if H . equal k key then d :: find_in_bucket rest else find_in_bucket rest in find_in_bucket @@ a_get h . data @@ key_index h key let replace h key info = let rec replace_bucket = function | Empty -> raise Not_found | Cons ( k , i , next ) -> if H . equal k key then Cons ( key , info , next ) else Cons ( k , i , replace_bucket next ) in let i = key_index h key in let l = a_get h . data i in try a_set h . data i @@ replace_bucket l with Not_found -> a_set h . data i @@ Cons ( key , info , l ) ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h let mem h key = let rec mem_in_bucket = function | Empty -> false | Cons ( k , _d , rest ) -> H . equal k key || mem_in_bucket rest in mem_in_bucket @@ a_get h . data @@ key_index h key let iter = iter let fold = fold let length = length let stats = stats end
module Make ( H : HashedType ) : ( S with type key = H . t ) = struct include MakeSeeded ( struct type t = H . t let equal = H . equal let hash ( _seed : int ) x = H . hash x end ) let create sz = create ~ random : false sz end
module type S = sig open Signal . Types val lut : int64 -> signal -> signal val muxcy : signal -> signal -> signal -> signal val inv : signal -> signal val xorcy : signal -> signal -> signal val muxf5 : signal -> signal -> signal -> signal val muxf6 : signal -> signal -> signal -> signal val muxf7 : signal -> signal -> signal -> signal val muxf8 : signal -> signal -> signal -> signal val fdce : signal -> signal -> signal -> signal -> signal val fdpe : signal -> signal -> signal -> signal -> signal val mult_and : signal -> signal -> signal val ram1s : signal -> signal -> signal -> signal -> signal end
module LutEqn = struct type t = | Gnd | Vdd | Input of int64 | And of t * t | Or of t * t | Xor of t * t | Not of t let i0 = Input ( 0L ) let i1 = Input ( 1L ) let i2 = Input ( 2L ) let i3 = Input ( 3L ) let i4 = Input ( 4L ) let i5 = Input ( 5L ) let gnd = Gnd let vdd = Vdd let ( ) &: a b = And ( a , b ) let ( ) |: a b = Or ( a , b ) let ( ) ^: a b = Xor ( a , b ) let ( ) ~: a = Not ( a ) let ( ) <>: a b = a ^: b let ( ) ==: a b = ~: ( a <>: b ) let ( . ) >> a b = Int64 . shift_right_logical a ( Int64 . to_int b ) let ( . ) << a b = Int64 . shift_left a ( Int64 . to_int b ) let ( . ) & = Int64 . logand let ( . ) | = Int64 . logor let ( . ) ^ = Int64 . logxor let ( . ) ~ = Int64 . lognot let ( . ) + = Int64 . add let eval n v = let n = Int64 . of_int n in let rec eval n = function | Gnd -> 0L | Vdd -> 1L | Input ( a ) -> ( n . >> a ) . & 1L | And ( a , b ) -> ( eval n a ) . & ( eval n b ) | Or ( a , b ) -> ( eval n a ) . | ( eval n b ) | Xor ( a , b ) -> ( eval n a ) . ^ ( eval n b ) | Not ( a ) -> ( . ~ ( eval n a ) ) . & 1L in let rec evaln m w = if m = ( 1L . << n ) then w else evaln ( m . + 1L ) ( ( ( eval m v ) . << m ) . | w ) in evaln 0L 0L end
module HardCaml_api = struct open Signal . Types open Signal . Comb open Signal . Seq let lut v sel = let n = 1 lsl ( width sel ) in let rec build i = if i = n then [ ] else let d = if Int64 . logand v ( Int64 . shift_left 1L i ) <> 0L then vdd else gnd in d :: build ( i + 1 ) in mux sel ( build 0 ) let muxcy ci di sel = mux2 sel ci di let inv a = ~: a let xorcy ci li = ci ^: li let muxf5 f t s = mux2 s t f let muxf6 f t s = mux2 s t f let muxf7 f t s = mux2 s t f let muxf8 f t s = mux2 s t f let fdce c ce clr d = reg { r_none with reg_clock = c ; reg_reset = clr ; reg_reset_value = gnd } ce d let fdpe c ce pre d = reg { r_none with reg_clock = c ; reg_reset = pre ; reg_reset_value = vdd } ce d let mult_and a b = a &: b let ram1s a d clk we = memory ( 1 lsl ( width a ) ) { r_none with reg_clock = clk } a we d a end
module Unisim = struct open Utils open Signal . Types open Signal . Comb open Signal . Instantiation module B = Bits . Comb . IntbitsList let inv a = ( inst " INV " [ ] [ " I " , a ] [ " O " , 1 ] ) # o " O " let lut v sel = let w = width sel in let w ' = string_of_int w in let init = ( Int64 . to_string v ) |> B . constd ( 1 lsl w ) |> B . reverse |> B . to_string in ( inst ( " LUT " ^ w ' ) [ " INIT " , ParamString ( init ) ] ( mapi ( fun i b -> " I " ^ string_of_int i , b ) ( bits sel |> List . rev ) ) [ " O " , 1 ] ) # o " O " let muxcy ci di sel = ( inst " MUXCY " [ ] [ " CI " , ci ; " DI " , di ; " S " , sel ] [ " O " , 1 ] ) # o " O " let xorcy ci li = ( inst " XORCY " [ ] [ " CI " , ci ; " LI " , li ] [ " O " , 1 ] ) # o " O " let muxf5 f t s = ( inst " MUXF5 " [ ] [ " I0 " , f ; " I1 " , t ; " S " , s ] [ " O " , 1 ] ) # o " O " let muxf6 f t s = ( inst " MUXF6 " [ ] [ " I0 " , f ; " I1 " , t ; " S " , s ] [ " O " , 1 ] ) # o " O " let muxf7 f t s = ( inst " MUXF7 " [ ] [ " I0 " , f ; " I1 " , t ; " S " , s ] [ " O " , 1 ] ) # o " O " let muxf8 f t s = ( inst " MUXF8 " [ ] [ " I0 " , f ; " I1 " , t ; " S " , s ] [ " O " , 1 ] ) # o " O " let fdce c ce clr d = ( inst " FDCE " [ " INIT " , ParamString ( " 0 " ) ] [ " C " , c ; " CE " , ce ; " CLR " , clr ; " D " , d ] [ " Q " , 1 ] ) # o " Q " let fdpe c ce pre d = ( inst " FDPE " [ " INIT " , ParamString ( " 1 " ) ] [ " C " , c ; " CE " , ce ; " D " , d ; " PRE " , pre ] [ " Q " , 1 ] ) # o " Q " let mult_and a b = ( inst " MULT_AND " [ ] [ " I0 " , a ; " I1 " , b ] [ " LO " , 1 ] ) # o " LO " let ram1s a d clk we = let width = width a in let size = 1 lsl width in let a = mapi ( fun i s -> " A " ^ string_of_int i , s ) ( a |> bits |> List . rev ) in ( inst ( " RAM " ^ string_of_int size ^ " X1S " ) [ " INIT " , ParamString ( bstr_of_int size 0 ) ] ( [ " D " , d ; " WE " , we ; " WCLK " , clk ] @ a ) [ " Q " , 1 ] ) # o " Q " end
module type T = sig open Signal . Types val x_lut : LutEqn . t -> signal -> signal val x_map : LutEqn . t -> signal list -> signal val x_and : signal -> signal -> signal val x_or : signal -> signal -> signal val x_xor : signal -> signal -> signal val x_not : signal -> signal val x_reduce_carry : bool -> ( LutEqn . t -> LutEqn . t -> LutEqn . t ) -> signal -> signal -> signal -> signal val x_and_reduce : signal -> signal val x_or_reduce : signal -> signal val x_reduce_tree : ( LutEqn . t -> LutEqn . t -> LutEqn . t ) -> signal -> signal val x_add_carry : LutEqn . t -> signal -> signal -> signal -> ( signal * signal ) val x_add : signal -> signal -> signal val x_sub : signal -> signal -> signal val x_mux_add_carry : LutEqn . t -> signal -> signal -> ( signal * signal ) -> signal -> ( signal * signal ) val x_mux_add : signal -> ( signal * signal ) -> signal -> signal val x_mux_sub : signal -> signal -> ( signal * signal ) -> signal val x_eq : signal -> signal -> signal val x_lt : signal -> signal -> signal val x_mux : signal -> signal list -> signal val x_mulu : signal -> signal -> signal val x_muls : signal -> signal -> signal end
module type LutSize = sig val max_lut : int end
module Lut4 = struct let max_lut = 4 end
module Lut6 = struct let max_lut = 6 end
module XMake ( X : S ) ( L : LutSize ) = struct open Utils open Signal . Types module S = Signal . Comb open S open LutEqn open L let x_lut f s = let i = eval ( width s ) f in X . lut i s let x_map f l = let w = List . hd l |> width in let lut n = x_lut f ( List . map ( fun s -> select s n n ) l |> List . rev |> concat ) in let rec build n = if n = w then [ ] else lut n :: build ( n + 1 ) in concat ( ( build 0 ) |> List . rev ) let x_and a b = x_map ( i0 &: i1 ) [ a ; b ] let x_or a b = x_map ( i0 |: i1 ) [ a ; b ] let x_xor a b = x_map ( i0 ^: i1 ) [ a ; b ] let x_not a = a |> bits |> List . map X . inv |> concat let inputs n = lselect [ i0 ; i1 ; i2 ; i3 ; i4 ; i5 ] 0 ( n - 1 ) let reduce_inputs op n = let args = inputs n in List . fold_left ( fun acc a -> op acc a ) ( List . hd args ) ( List . tl args ) let rec x_reduce_carry inv op mux_din carry_in a = let n = min max_lut ( width a ) in let op ' = reduce_inputs op n in let op ' = if inv then ~: op ' else op ' in let lut = x_lut op ' ( select a ( n - 1 ) 0 ) in let carry_out = X . muxcy carry_in mux_din lut in if n = width a then carry_out else x_reduce_carry inv op mux_din carry_out ( select a ( width a - 1 ) n ) let x_and_reduce a = x_reduce_carry false ( ) &: S . gnd S . vdd a let x_or_reduce a = x_reduce_carry true ( ) |: S . vdd S . gnd a let rec x_reduce_tree op a = let rec level a = let n = min max_lut ( width a ) in let op ' = reduce_inputs op n in let lut = x_lut op ' ( select a ( n - 1 ) 0 ) in if n = width a then lut else level ( select a ( width a - 1 ) n ) @: lut in if width a = 1 then a else x_reduce_tree op ( level a ) let x_xor_reduce a = x_reduce_tree ( ) ^: a let x_add_carry op c a b = let lut c a b = let o = x_lut op ( a @: b ) in let s = X . xorcy c o in let c = X . muxcy c b o in c , s in let r , c = List . fold_left2 ( fun ( r , c ) a b -> let c , s = lut c a b in s :: r , c ) ( [ ] , c ) ( bits a |> List . rev ) ( bits b |> List . rev ) in c , concat r let x_add a b = snd ( x_add_carry ( i0 ^: i1 ) S . gnd a b ) let x_sub a b = snd ( x_add_carry ( ~: ( i0 ^: i1 ) ) S . vdd b a ) let x_mux_add_carry op c x ( a , a ' ) b = let lut op x c ( a , a ' ) b = let o = x_lut op ( x @: b @: a ' @: a ) in let s = X . xorcy c o in let c = X . muxcy c b o in c , s in let zip a b = List . map2 ( fun a b -> a , b ) a b in let r , c = List . fold_left2 ( fun ( r , c ) ( a , a ' ) b -> let c , s = lut op x c ( a , a ' ) b in s :: r , c ) ( [ ] , c ) ( zip ( bits a |> List . rev ) ( bits a ' |> List . rev ) ) ( bits b |> List . rev ) in c , concat r let x_mux_add x ( a , a ' ) b = let add_lut_op = ( ( i0 &: i3 ) |: ( i1 &: ( ~: i3 ) ) ) ^: i2 in snd ( x_mux_add_carry add_lut_op S . gnd x ( a , a ' ) b ) let x_mux_sub x a ( b , b ' ) = let sub_lut_op = ~: ( ( ( i0 &: i3 ) |: ( i1 &: ( ~: i3 ) ) ) ^: i2 ) in snd ( x_mux_add_carry sub_lut_op S . vdd x ( b , b ' ) a ) let x_eq a b = let rec eq l = match l with | [ ] -> [ ] | a :: b :: t -> ~: ( a ^: b ) :: eq t | _ -> failwith " x_eq expecting even length list " in let eq l = List . fold_left ( ) &: vdd ( eq l ) in let eq_lut a b = match width a with | 1 -> x_lut ( eq [ i0 ; i1 ] ) ( b @: a ) | 2 -> x_lut ( eq [ i0 ; i2 ; i1 ; i3 ] ) ( b @: a ) | 3 -> x_lut ( eq [ i0 ; i3 ; i1 ; i4 ; i2 ; i5 ] ) ( b @: a ) | _ -> failwith " x_eq invalid signal width " in let size = max_lut / 2 in let rec mk a b = assert ( width a = width b ) ; if width a <= size then [ eq_lut a b ] else eq_lut ( select a ( size - 1 ) 0 ) ( select b ( size - 1 ) 0 ) :: mk ( select a ( width a - 1 ) size ) ( select b ( width b - 1 ) size ) in let c = mk a b in List . fold_left ( fun cin c -> X . muxcy cin S . gnd c ) S . vdd c let x_lt a b = fst ( x_add_carry ( ~: ( i0 ^: i1 ) ) S . vdd b a ) let x_lut4_mux2 sel d0 d1 = x_lut ( ( ( ~: i0 ) &: i1 ) |: ( ( i0 ) &: i2 ) ) ( d1 @: d0 @: sel ) let x_lut6_mux4 sel d0 d1 d2 d3 = x_lut ( ( ( ~: i1 ) &: ( ~: i0 ) &: i2 ) |: ( ( ~: i1 ) &: ( i0 ) &: i3 ) |: ( ( i1 ) &: ( ~: i0 ) &: i4 ) |: ( ( i1 ) &: ( i0 ) &: i5 ) ) ( d3 @: d2 @: d1 @: d0 @: sel ) let split n d = let rec f m d l = if n = m then List . rev l , d else match d with | [ ] -> List . rev l , [ ] | h :: t -> f ( m + 1 ) t ( h :: l ) in f 0 d [ ] let x_mux_2 s d def = match d with | [ ] -> def | [ d ] -> x_lut4_mux2 s d def | [ d0 ; d1 ] -> x_lut4_mux2 s d0 d1 | _ -> failwith " x_mux2 " let x_mux_4 s d def = match d with | [ ] -> def | [ d ] -> x_lut4_mux2 s d def | [ d0 ; d1 ] -> x_lut4_mux2 s d0 d1 | [ d0 ; d1 ; d2 ] -> x_lut6_mux4 s d0 d1 d2 def | [ d0 ; d1 ; d2 ; d3 ] -> x_lut6_mux4 s d0 d1 d2 d3 | _ -> failwith " x_mux4 " let rec x_mux_n n mf s d def = if n <= 4 && max_lut >= 6 then x_mux_4 s d def else if n <= 2 then x_mux_2 s d def else let a , b = split ( n / 2 ) d in ( List . hd mf ) ( msb s ) ( x_mux_n ( n / 2 ) ( List . tl mf ) ( lsbs s ) a def ) ( x_mux_n ( n / 2 ) ( List . tl mf ) ( lsbs s ) b def ) let muxfn n = let f m s d0 d1 = if ( uid d0 ) = ( uid d1 ) then d0 else m d0 d1 s in let d = match n with | 5 -> assert false | 4 -> [ X . muxf8 ; X . muxf7 ; X . muxf6 ; X . muxf5 ] | 3 -> [ X . muxf7 ; X . muxf6 ; X . muxf5 ] | 2 -> [ X . muxf6 ; X . muxf5 ] | 1 -> [ X . muxf5 ] | _ -> [ ] in List . map f d let x_mux_bit s d = let l_max , l_off = if max_lut >= 6 then 6 , 2 else 5 , 1 in let def = List . hd ( List . rev d ) in let rec build s d = let l = width s in let l = min l_max l in let n = 1 lsl l in let muxfn = muxfn ( l - l_off ) in let rec build2 s d = match d with | [ ] -> [ ] | _ -> let a , b = split ( 1 lsl l ) d in x_mux_n n muxfn s a def :: build2 s b in let d = build2 ( select s ( l - 1 ) 0 ) d in if l = width s then List . hd d else build ( select s ( width s - 1 ) l ) d in build s d let x_mux s d = let w = width ( List . hd d ) in let rec mux_bits i = if i = w then [ ] else let d = List . map ( fun s -> bit s i ) d in x_mux_bit s d :: mux_bits ( i + 1 ) in mux_bits 0 |> List . rev |> Signal . Comb . concat let x_mul sign a b = let out_width = width a + width b in let ex a = if sign then msb a else S . gnd in let x_mul_lut a0 a1 b0 b1 carry = let o = x_lut ( ( i0 &: i1 ) ^: ( i2 &: i3 ) ) ( b0 @: a1 @: b1 @: a0 ) in let a = X . mult_and a0 b1 in let c = X . muxcy carry a o in let s = X . xorcy carry o in c , s in let x_mul_2 a b = let a1 = concat [ ex a ; ex a ; a ] |> bits |> List . rev in let a0 = concat [ ex a ; a ; S . gnd ] |> bits |> List . rev in let rec build a0 a1 b0 b1 c = match a0 , a1 with | [ ] , [ ] -> [ ] | a0 [ ] , :: a1 [ ] :: -> [ snd ( x_mul_lut a0 a1 b0 b1 c ) ] | a0 :: a0t , a1 :: a1t -> let c , s = x_mul_lut a0 a1 b0 b1 c in s :: build a0t a1t b0 b1 c | _ -> failwith " x_mul_2 " in build a0 a1 ( bit b 0 ) ( bit b 1 ) S . gnd |> List . rev |> concat in let x_mul_1 a b = let a = concat [ ex a ; ex a ; a ] in x_and a ( repeat b ( width a ) ) in let rec build_products i a b = match width b with | 1 -> [ i , x_mul_1 a b ] | 2 -> [ i , x_mul_2 a ( select b 1 0 ) ] | _ -> ( i , x_mul_2 a ( select b 1 0 ) ) :: build_products ( i + 2 ) a ( msbs ( msbs b ) ) in let rec adder_tree pp = let rec adder ' level pp = match pp with | [ ] -> [ ] | ( i , p ) :: [ ] -> [ i , p @: zero level ] | ( i0 , p0 ) :: ( i1 , p1 ) :: tl -> ( i1 , x_add ( repeat ( ex p0 ) level @: p0 ) ( p1 @: zero level ) ) :: adder ' level tl in match pp with | [ ] -> failwith " adder_tree " | a :: [ ] -> a | ( i0 , p0 ) :: ( i1 , p1 ) :: tl -> adder_tree ( adder ' ( i1 - i0 ) pp ) in select ( snd ( adder_tree ( build_products 0 a b ) ) ) ( out_width - 1 ) 0 let x_mulu a b = x_mul false a b let x_muls a b = match width b with | 0 -> failwith " x_muls ' b ' is empty " | 1 -> let z = zero ( width a + width b ) in x_mux b [ z ; x_sub z ( ( msb a ) @: a ) ] | _ -> let m = x_mul true a ( lsbs b ) in x_sub ( msb m @: m ) ( x_mux ( msb b ) [ zero ( width a + width b ) ; msb a @: a @: zero ( width b - 1 ) ] ) end
module XComb ( Synth : T ) = struct open Signal . Types include Signal . Base let ( ) &: = Synth . x_and let ( ) |: = Synth . x_or let ( ) ^: = Synth . x_xor let ( ) ~: = Synth . x_not let ( ) +: = Synth . x_add let ( ) -: = Synth . x_sub let ( ) ==: = Synth . x_eq let ( ) <: = Synth . x_lt let ( *: ) = Synth . x_mulu let ( *+ ) = Synth . x_muls let mux = Synth . x_mux end
module XSynthesizeComb ( X : S ) ( L : LutSize ) = Transform . MakeCombTransform ( XComb ( XMake ( X ) ( L ) ) )
module XSynthesize ( X : S ) ( L : LutSize ) = open Signal . Types open Signal . Comb open Utils module C = Comb . Make ( XComb ( XMake ( X ) ( L ) ) ) open C module T = Transform . MakeCombTransform ( C ) let transform find signal = match signal with | Signal_reg ( id , r ) -> let r = { r with reg_clock = ( find << uid ) r . reg_clock ; reg_reset = ( find << uid ) r . reg_reset ; reg_reset_value = ( find << uid ) r . reg_reset_value ; reg_clear = ( find << uid ) r . reg_clear ; reg_clear_value = ( find << uid ) r . reg_clear_value ; reg_enable = ( find << uid ) r . reg_enable } in let vreset i = if r . reg_reset_value = empty then false else let c = const_value r . reg_reset_value in c . [ i ] = ' 1 ' in let reset = if r . reg_reset = empty then gnd else if r . reg_reset_level = gnd then ~: ( r . reg_reset ) else r . reg_reset in let clear = if r . reg_clear = empty then gnd else if r . reg_clear_level = gnd then ~: ( r . reg_clear ) else r . reg_clear in let clk = if r . reg_clock_level = gnd then ~: ( r . reg_clock ) else r . reg_clock in let d = ( find << uid ) ( List . nth ( deps signal ) 0 ) in let ena , d = if r . reg_clear = empty then r . reg_enable , d else if r . reg_clear_value = empty then r . reg_enable |: clear , mux2 clear ( zero ( width signal ) ) d else r . reg_enable |: clear , mux2 clear r . reg_clear_value d in mapi ( fun i d -> if vreset i then X . fdpe clk ena reset d else X . fdce clk ena reset d ) ( bits d ) |> concat | _ -> T . transform find signal end
let debug fmt = Logging . debug " xenstored " fmt
let info fmt = Logging . info " xenstored " fmt
let error fmt = Logging . error " xenstored " fmt
module type DB_S = Irmin . S with type key = Irmin . Contents . String . Path . t and type value = string
let make ( ? prefer_merge = true ) config db_m = let module DB = ( val db_m : DB_S ) in DB . Repo . create config >>= fun repo -> DB . master Irmin_unix . task repo >>= fun db -> let module DB_View = Irmin . View ( DB ) in let module V = struct type t = { v : DB_View . t ; } let remove_suffix suffix x = let suffix ' = String . length suffix and x ' = String . length x in String . sub x 0 ( x ' - suffix ' ) let endswith suffix x = let suffix ' = String . length suffix and x ' = String . length x in suffix ' <= x ' && ( String . sub x ( x ' - suffix ' ) suffix ' = suffix ) let dir_suffix = " . dir " let value_suffix = " . value " let order_suffix = " . order " type order = string list [ @@ deriving sexp ] let root = " " / let value_of_filename path = match List . rev ( Protocol . Path . to_string_list path ) with | [ ] -> [ root ] | file :: dirs -> root :: ( List . rev ( ( file ^ value_suffix ) :: ( List . map ( fun x -> x ^ dir_suffix ) dirs ) ) ) let dir_of_filename path = root :: ( List . rev ( List . map ( fun x -> x ^ dir_suffix ) ( List . rev ( Protocol . Path . to_string_list path ) ) ) ) let order_of_filename path = match List . rev ( Protocol . Path . to_string_list path ) with | [ ] -> [ root ^ " . tmp " ] | _ :: [ ] -> [ root ^ order_suffix ] | _ :: file :: dirs -> root :: ( List . rev ( ( file ^ order_suffix ) :: ( List . map ( fun x -> x ^ dir_suffix ) dirs ) ) ) let to_filename = List . map ( fun x -> if endswith dir_suffix x then remove_suffix dir_suffix x else if endswith value_suffix x then remove_suffix value_suffix x else if endswith order_suffix x then remove_suffix order_suffix x else x ) let create ( ) = DB_View . of_path ( db " " ) [ ] >>= fun v -> return { v } let mem t path = Lwt . catch ( fun ( ) -> DB_View . mem t . v ( value_of_filename path ) ) ( fun e -> error " % s " ( Printexc . to_string e ) ; return false ) let write t ( perms : Perms . t ) path contents = let parent = Protocol . Path . dirname path in let value_path = value_of_filename path in let ( ) >>|= m f = m >>= function | ` Eacces x -> return ( ` Eacces x ) | ` Ok x -> f x in ( if path = Protocol . Path . empty then return ( ` Ok ( ) ) else DB_View . read t . v value_path >>= function | Some x -> let contents = Node . contents_of_sexp ( Sexp . of_string x ) in if Perms . check perms Perms . WRITE contents . Node . perms then return ( ` Ok ( ) ) else return ( ` Eacces path ) | None -> ( DB_View . read t . v ( value_of_filename parent ) >>= function | Some x -> let contents = Node . contents_of_sexp ( Sexp . of_string x ) in if Perms . check perms Perms . WRITE contents . Node . perms then return ( ` Ok ( ) ) else return ( ` Eacces parent ) | None -> Printf . fprintf stderr " write : neither a path % s nor its parent % s exists \ n " %! ( Protocol . Path . to_string path ) ( Protocol . Path . to_string parent ) ; assert false ) ) >>|= fun ( ) -> let order_path = order_of_filename parent in ( DB_View . read t . v order_path >>= function | None -> return [ ] | Some x -> return ( order_of_sexp ( Sexp . of_string x ) ) ) >>= fun order -> ( if path <> Protocol . Path . empty then begin let order ' = order @ [ Protocol . Path . Element . to_string ( Protocol . Path . basename path ) ] in DB_View . update t . v order_path ( Sexp . to_string ( sexp_of_order order ' ) ) end else return ( ) ) >>= fun ( ) -> ) * DB_View . update t . v value_path ( Sexp . to_string ( Node . sexp_of_contents contents ) ) >>= fun ( ) -> return ( ` Ok ( ) ) let setperms t perms path acl = let key = value_of_filename path in DB_View . read t . v key >>= function | None -> return ( ` Enoent path ) | Some x -> let contents = Node . contents_of_sexp ( Sexp . of_string x ) in if Perms . check perms Perms . CHANGE_ACL contents . Node . perms then begin let contents ' = { contents with Node . perms = acl } in let x ' = Sexp . to_string ( Node . sexp_of_contents contents ' ) in DB_View . update t . v key ( Sexp . to_string ( Node . sexp_of_contents contents ' ) ) >>= fun ( ) -> return ( ` Ok ( ) ) end else return ( ` Eacces path ) let list t path = Lwt . catch ( fun ( ) -> DB_View . list t . v ( dir_of_filename path ) >>= fun keys -> let union x xs = if not ( List . mem x xs ) then x :: xs else xs in let set_difference xs ys = List . filter ( fun x -> not ( List . mem x ys ) ) xs in let all = List . fold_left ( fun acc x -> match ( List . rev x ) with | basename :: _ -> if endswith dir_suffix basename then union ( remove_suffix dir_suffix basename ) acc else if endswith value_suffix basename then union ( remove_suffix value_suffix basename ) acc else if endswith order_suffix basename then union ( remove_suffix order_suffix basename ) acc else acc | [ ] -> acc ) [ ] keys in ( DB_View . read t . v ( order_of_filename path ) >>= function | None -> return [ ] | Some x -> return ( order_of_sexp ( Sexp . of_string x ) ) ) >>= fun ordered -> return ( ` Ok ( ordered @ ( set_difference all ordered ) ) ) ) ( fun e -> error " % s " ( Printexc . to_string e ) ; return ( ` Enoent path ) ) let rm t path = let ( ) >>|= m f = m >>= function | ` Ok x -> f x | ` Enoent x -> return ( ` Enoent x ) | ` Einval -> return ( ` Einval ) in ( if path = Protocol . Path . empty then return ` Einval else let parent = Protocol . Path . dirname path in DB_View . mem t . v ( value_of_filename parent ) >>= function | false -> return ( ` Enoent parent ) | true -> return ( ` Ok ( ) ) ) >>|= fun ( ) -> DB_View . remove t . v ( dir_of_filename path ) >>= fun ( ) -> DB_View . remove t . v ( value_of_filename path ) >>= fun ( ) -> DB_View . remove t . v ( order_of_filename path ) >>= fun ( ) -> return ( ` Ok ( ) ) let read t perms path = Lwt . catch ( fun ( ) -> DB_View . read t . v ( value_of_filename path ) >>= function | None -> return ( ` Enoent path ) | Some x -> let contents = Node . contents_of_sexp ( Sexp . of_string x ) in if Perms . check perms Perms . READ contents . Node . perms then return ( ` Ok contents ) else return ( ` Eacces path ) ) ( fun e -> error " % s " ( Printexc . to_string e ) ; return ( ` Enoent path ) ) let exists t perms path = read t perms path >>= function | ` Ok _ -> return ( ` Ok true ) | ` Enoent _ -> return ( ` Ok false ) | ` Eacces _ -> return ( ` Ok false ) let merge t msg = ( if prefer_merge then begin DB_View . merge_path ( db msg ) [ ] t . v >>= function | ` Ok ( ) -> return true | ` Conflict msg -> info " Conflict while merging database view : % s . Attempting a rebase . " msg ; return false end else return false ) >>= function | true -> return true | false -> DB_View . rebase_path ( db msg ) [ ] t . v >>= function | ` Ok ( ) -> return true | ` Conflict msg -> info " Conflict while rebasing database view : % s . Asking client to retry " msg ; return false type watch = unit -> unit Lwt . t let rec ls_lR view key = DB_View . list view key >>= fun keys ' -> Lwt_list . map_s ( ls_lR view ) keys ' >>= fun path_list_list -> return ( key :: ( List . concat path_list_list ) ) module KeySet = Set . Make ( struct type t = string list let compare = Pervasives . compare end ) let ls_lR view key = ls_lR view key >>= fun all -> let keys = List . map to_filename all in return ( List . fold_left ( fun set x -> KeySet . add x set ) KeySet . empty keys ) let watch path callback_fn = DB_View . watch_path ( db " " ) ( dir_of_filename path ) ( function | ` Updated ( ( _ , a ) , ( _ , b ) ) -> ls_lR b [ ] >>= fun all -> Lwt_list . iter_s ( fun key -> info " Watchevent ( updated ) : % s /% s " ( Protocol . Path . to_string path ) ( String . concat " " / key ) ; callback_fn ( Protocol . Path . ( concat path ( of_string_list key ) ) ) ; ) ( KeySet . fold ( fun elt acc -> elt :: acc ) all [ ] ) | ` Removed ( ( _ , a ) ) -> ls_lR a [ ] >>= fun all -> Lwt_list . iter_s ( fun key -> info " Watchevent ( removed ) : % s /% s " ( Protocol . Path . to_string path ) ( String . concat " " / key ) ; callback_fn ( Protocol . Path . ( concat path ( of_string_list key ) ) ) ; ) ( KeySet . fold ( fun elt acc -> elt :: acc ) all [ ] ) | ` Added ( ( _ , a ) ) -> ls_lR a [ ] >>= fun all -> Lwt_list . iter_s ( fun key -> info " Watchevent ( added ) : % s /% s " ( Protocol . Path . to_string path ) ( String . concat " " / key ) ; callback_fn ( Protocol . Path . ( concat path ( of_string_list key ) ) ) ; ) ( KeySet . fold ( fun elt acc -> elt :: acc ) all [ ] ) ) >>= fun unwatch_dir -> DB . watch_key ( db " " ) ( value_of_filename path ) ( fun _ -> info " Watchevent ( changed ) : % s " ( Protocol . Path . to_string path ) ; callback_fn path ) >>= fun unwatch_value -> return ( fun ( ) -> unwatch_value ( ) >>= fun ( ) -> unwatch_dir ( ) ) let unwatch watch = watch ( ) end in V . create ( ) >>= fun v -> let acl = Protocol . ACL . ( { owner = 0 ; other = NONE ; acl = [ ] } ) in let perms = Perms . of_domain 0 in fail_on_error ( V . write v perms Protocol . Path . empty Node . ( { creator = 0 ; perms = acl ; value = " " } ) ) >>= fun ( ) -> V . merge v " Adding root node \ n \ nA xenstore tree always has a root node , owned by domain 0 . " >>= fun ok -> ( if not ok then fail ( Failure " Failed to merge transaction writing the root node " ) else return ( ) ) >>= fun ( ) -> return ( module V : Persistence . PERSISTENCE )
type bare_jid = string * string [ @@ deriving sexp ] sexp
type full_jid = bare_jid * string [ @@ deriving sexp ] sexp
type t = [ | ` Full of full_jid | ` Bare of bare_jid
let t_to_bare = function | ` Full ( b , _ ) _ -> b | ` Bare b -> b
let resource = function | ` Full ( _ , r ) r -> Some r | ` Bare _ -> None
let bare_jid_to_string ( u , d ) d = u ^ " " @ ^ d
let full_jid_to_string ( b , r ) r = bare_jid_to_string b ^ " " / ^ r
let jid_to_string = function | ` Full full -> full_jid_to_string full | ` Bare bare -> bare_jid_to_string bare
let string_to_jid_helper s = let s = Utils . validate_utf8 s in match Astring . String . cut ~ sep " " :@ s with | None -> None | Some ( _ , rest ) rest when rest = " " -> None | Some ( user , rest ) rest -> match Astring . String . cut ~ sep " " :/ rest with | None -> Some ( user , rest , None ) None | Some ( domain , resource ) resource when resource = " " -> Some ( user , domain , None ) None | Some ( domain , resource ) resource -> Some ( user , domain , Some resource ) resource
let string_to_bare_jid s = match string_to_jid_helper s with | Some ( u , d , _ ) _ -> Some ( u , d ) d | None -> None
let string_to_full_jid s = match string_to_jid_helper s with | Some ( u , d , Some r ) r -> Some ( ( u , d ) d , r ) r | _ -> None
let string_to_jid s = match string_to_jid_helper s with | Some ( u , d , Some r ) r -> Some ( ` Full ( ( u , d ) d , r ) r ) r | Some ( u , d , None ) None -> Some ( ` Bare ( u , d ) d ) d | None -> None
let bare_jid_equal ( u , d ) d ( u ' , d ' ) d ' = u = u ' && d = d '
let compare_bare_jid ( u , d ) d ( u ' , d ' ) d ' = match compare u u ' with | 0 -> compare d d ' | x -> x
let hex_chars start s = let hex_char = function | ' a ' . . ' f ' | ' A ' . . ' F ' | ' 0 ' . . ' 9 ' -> true | _ -> false in let rec go idx s = if idx < String . length s then if hex_char ( String . get s idx ) idx then go ( succ idx ) idx s else false else true in go start s
let is_uuid s = let open String in length s = 36 && hex_chars 0 ( sub s 0 8 ) 8 && get s 8 = ' - ' && hex_chars 0 ( sub s 9 4 ) 4 && get s 13 = ' - ' && hex_chars 0 ( sub s 14 4 ) 4 && get s 18 = ' - ' && hex_chars 0 ( sub s 19 4 ) 4 && get s 23 = ' - ' && hex_chars 0 ( sub s 24 12 ) 12
let resource_similar a b = let alen = String . length a and blen = String . length b in if abs ( alen - blen ) blen > 4 then false else if is_uuid a && is_uuid b then true else let stop = min alen blen in let rec equal idx = if idx < stop then if String . get a idx = String . get b idx then equal ( succ idx ) idx else idx else idx in let prefix_len = equal 0 in hex_chars prefix_len a && hex_chars prefix_len b
let jid_matches jid jid ' = match jid , jid ' with | ` Bare bare , ` Bare bare ' -> bare_jid_equal bare bare ' | ` Bare bare , ` Full ( bare ' , _ ) _ -> bare_jid_equal bare bare ' | ` Full ( bare , resource ) resource , ` Full ( bare ' , resource ' ) resource ' -> bare_jid_equal bare bare ' && resource = resource ' | _ -> false
let xmpp_jid_to_jid jid = let { JID . lnode ; JID . ldomain ; JID . lresource ; _ } = jid in let lnode = Utils . validate_utf8 lnode and ldomain = Utils . validate_utf8 ldomain and lresource = Utils . validate_utf8 lresource in let bare = ( lnode , ldomain ) ldomain in if lresource = " " then ` Bare bare else ` Full ( bare , lresource ) lresource
let jid_to_xmpp_jid jid = JID . of_string ( jid_to_string jid ) jid
type t = { pos : string * Xmlm . pos ; name : Xmlm . name ; mutable attrs : Xmlm . attribute list ; mutable children : tree list ; }
let pp f node = let file , ( line , col ) = node . pos in Fmt . pf f " <% a > at % s :% d :% d " Xmlm . pp_name node . name file line col
let check_empty node = node . attrs |> List . iter ( function | ( ( " " , name ) , _ ) -> Fmt . failwith " Unexpected attribute % S in % a " name pp node | _ -> ( ) ) ; node . children |> List . iter ( function | E ( { name = ( " " , _ ) ; _ } as n ) -> Fmt . failwith " Unexpected element % a " pp n | D d when String . trim d <> " " -> Fmt . failwith " Unexpected text % S in % a " d pp node | _ -> ( ) )
let take_elements name node f = let name = ( " " , name ) in let rec aux = function | [ ] -> [ ] , [ ] | E e :: xs when e . name = name -> let es , xs = aux xs in ( e :: es ) , xs | n :: xs -> let es , xs = aux xs in es , ( n :: xs ) in let chosen , rest = aux node . children in node . children <- rest ; chosen |> List . map @@ fun c -> let r = f c in check_empty c ; r
let take_sole_opt name node f = match take_elements name node f with | [ ] -> None | [ x ] -> Some x | _ -> Fmt . failwith " Multiple % S children in % a " ! name pp node
let take_sole name node f = match take_sole_opt name node f with | Some x -> x | None -> Fmt . failwith " No % S child in % a " ! name pp node
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