text
stringlengths 12
786k
|
---|
let get_global conn index = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' G ' ; % lwt Lwt_io . BE . write_int conn . io . out index ; % lwt let % lwt rv = _read_remote_value conn in Lwt . return rv ) rv |
let get_accu conn = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' A ' ; % lwt let % lwt rv = _read_remote_value conn in Lwt . return rv ) rv |
let get_header conn rv = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' H ' ; % lwt _write_remote_value conn rv ; % lwt let % lwt hdr = Lwt_io . BE . read_int conn . io . in_ in Lwt . return hdr ) hdr |
let get_field conn rv index = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' F ' ; % lwt _write_remote_value conn rv ; % lwt Lwt_io . BE . write_int conn . io . out index ; % lwt let % lwt res = match % lwt Lwt_io . read_char conn . io . in_ with | ' \ 000 ' -> let % lwt rv = _read_remote_value conn in Lwt . return rv | ' \ 001 ' -> let % lwt v = Lwt_io . read_float64 conn . io . in_ in Lwt . fail ( Float_field v ) v | _ -> assert false in Lwt . return res ) res |
let marshal_obj conn rv = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' M ' ; % lwt _write_remote_value conn rv ; % lwt let % lwt v = Lwt_io . read_value conn . io . in_ in Lwt . return v ) v |
let get_closure_code conn rv = Lwt_conn . atomic conn ( fun conn -> Lwt_io . write_char conn . io . out ' C ' ; % lwt _write_remote_value conn rv ; % lwt let % lwt pc = _read_pc conn in Lwt . return pc ) pc |
type t = | Varint | Sixty_four | Length_delimited | Start_group | End_group | Thirty_two |
let of_int = function | 0 -> Varint | 1 -> Sixty_four | 2 -> Length_delimited | 3 -> Start_group | 4 -> End_group | 5 -> Thirty_two | n -> Printf . kprintf invalid_arg " Wire_type . of_int ( % d ) " n |
let to_int = function | Varint -> 0 | Sixty_four -> 1 | Length_delimited -> 2 | Start_group -> 3 | End_group -> 4 | Thirty_two -> 5 |
let to_string = function | Varint -> " Varint " | Sixty_four -> " Sixty_four " | Length_delimited -> " Length_delimited " | Start_group -> " Start_group " | End_group -> " End_group " | Thirty_two -> " Thirty_two " |
let pp fmt v = Format . pp_print_string fmt ( to_string v ) |
let to_http service region req = let uri = Uri . add_query_params ( Uri . of_string ( Aws . Util . of_option_exn ( Endpoints . url_of service region ) ) ) ( List . append [ ( " Version " , [ " 2016 - 11 - 15 " ] ) ; ( " Action " , [ " WithdrawByoipCidr " ] ) ] ( Util . drop_empty ( Uri . query_of_encoded ( Query . render ( WithdrawByoipCidrRequest . to_query req ) ) ) ) ) in ( ` POST , uri , [ ] ) |
let of_http body = try let xml = Ezxmlm . from_string body in let resp = Xml . member " WithdrawByoipCidrResponse " ( snd xml ) in try Util . or_error ( Util . option_bind resp WithdrawByoipCidrResult . parse ) ( let open Error in BadResponse { body ; message = " Could not find well formed WithdrawByoipCidrResult . " } ) with | Xml . RequiredFieldMissing msg -> let open Error in ` Error ( BadResponse { body ; message = ( " Error parsing WithdrawByoipCidrResult - missing field in body or children : " ^ msg ) } ) with | Failure msg -> ` Error ( let open Error in BadResponse { body ; message = ( " Error parsing xml : " ^ msg ) } ) |
let parse_error code err = let errors = [ ] @ Errors_internal . common in match Errors_internal . of_string err with | Some var -> if ( List . mem var errors ) && ( ( match Errors_internal . to_http_code var with | Some var -> var = code | None -> true ) ) then Some var else None | None -> None |
let invalid name loc = Invalid_argument ( Printf . sprintf " % s called from % s " name loc ) |
module Option = struct let get ~ loc = function | Some v -> v | None -> raise ( invalid " Lwtreslib . WithExceptions . Option . get " loc ) let to_exn ~ none = function Some v -> v | None -> raise none let to_exn_f ~ none = function Some v -> v | None -> raise ( none ( ) ) end |
module Result = struct let get_ok ~ loc = function | Ok v -> v | Error _ -> raise ( invalid " Lwtreslib . WithExceptions . Result . get_ok " loc ) let get_error ~ loc = function | Error e -> e | Ok _ -> raise ( invalid " Lwtreslib . WithExceptions . Result . get_error " loc ) let to_exn = function Ok v -> v | Error exc -> raise exc let to_exn_f ~ error = function Ok v -> v | Error b -> raise ( error b ) end |
module List = struct let rev_combine ~ loc xs ys = let rec aux acc xs ys = match ( xs , ys ) with | ( [ ] , [ ] ) -> acc | ( x :: xs , y :: ys ) -> aux ( ( x , y ) :: acc ) xs ys | ( [ ] , _ :: _ ) | ( _ :: _ , [ ] ) -> raise ( invalid " Lwtreslib . WithExceptions . List . rev_combine " loc ) in aux [ ] xs ys let combine ~ loc xs ys = let rec aux acc xs ys = match ( xs , ys ) with | ( [ ] , [ ] ) -> acc | ( x :: xs , y :: ys ) -> aux ( ( x , y ) :: acc ) xs ys | ( [ ] , _ :: _ ) | ( _ :: _ , [ ] ) -> raise ( invalid " Lwtreslib . WithExceptions . List . combine " loc ) in Stdlib . List . rev ( aux [ ] xs ys ) end |
module type S_bigarray = sig open Bigarray type ' a t val bigstring : ( char , int8_unsigned_elt , c_layout ) Array1 . t t val float32_vec : ( float , float32_elt , fortran_layout ) Array1 . t t val float64_vec : ( float , float64_elt , fortran_layout ) Array1 . t t val float32_mat : ( float , float32_elt , fortran_layout ) Array2 . t t val float64_mat : ( float , float64_elt , fortran_layout ) Array2 . t t end |
module type S = sig type ' a t val unit : unit t val bool : bool t val char : char t val string : string t val int : int t val int32 : int32 t val int63 : Int63 . t t val int64 : int64 t val nativeint : nativeint t val float : float t val sexp : Sexp . t t val option : ' a t -> ' a option t val list : ' a t -> ' a list t val both : ' a t -> ' b t -> ( ' a * ' b ) t val either : ' a t -> ' b t -> ( ' a , ' b ) Either . t t val result : ' a t -> ' b t -> ( ' a , ' b ) Result . t t include S_bigarray with type ' a t := ' a t end |
let ( ) = Css . install_css ( ) |
module Legend_model = struct type t = { visibility : bool list } [ @@ deriving equal , fields ] end |
let id = Type_equal . Id . create ~ name " : dygraph " [ % sexp_of : opaque ] |
let widget ? with_graph ? on_zoom data options = let resize_when_inserted_into_the_dom graph _time = Graph . resize graph in let override_zoom_callback ~ graph options = match on_zoom with | None -> options | Some on_zoom -> let zoomCallback = let caller ' s_zoom_callback = Options . zoomCallback options in fun ~ xmin ~ xmax ~ yRanges -> Option . iter caller ' s_zoom_callback ~ f ( : fun f -> f ~ xmin ~ xmax ~ yRanges ) ; let is_zoomed = Graph . isZoomed graph in Vdom . Effect . Expert . handle_non_dom_event_exn ( on_zoom ~ is_zoomed ) in let our_options = Options . create ~ zoomCallback ( ) in Options . merge options ~ prefer : our_options in Vdom . Node . widget ( ) ~ id ~ destroy ( : fun ( _ , _ , _ , graph , animation_id ) _el -> Graph . destroy graph ; Dom_html . window ## cancelAnimationFrame animation_id ) ~ init ( : fun ( ) -> let el = Dom_html . createDiv Dom_html . document in let graph = Graph . create el data options in let ( ) = let options = override_zoom_callback ~ graph options in let updateOptions = Update_options . create ~ options ? data : None ( ) in Graph . updateOptions graph updateOptions in Option . iter with_graph ~ f ( : fun with_graph -> with_graph graph ) ; let animation_id = Dom_html . window ## requestAnimationFrame ( Js . wrap_callback ( resize_when_inserted_into_the_dom graph ) ) in ( data , options , on_zoom , graph , animation_id ) , el ) ~ update ( : fun ( old_data , old_options , old_on_zoom , graph , animation_id ) el -> let ( ) = let data = Option . some_if ( not ( phys_equal old_data data ) ) data in let options = match phys_equal old_options options , phys_equal old_on_zoom on_zoom with | true , true -> None | _ -> Some ( override_zoom_callback ~ graph options ) in match data , options with | None , None -> ( ) | _ -> let updateOptions = Update_options . create ? options ? data ( ) in Graph . updateOptions graph updateOptions in ( data , options , on_zoom , graph , animation_id ) , el ) ; ; |
let create_graph ? with_graph ? on_zoom data options = let on_zoom = match on_zoom with | None -> Bonsai . Value . return None | Some on_zoom -> Bonsai . Value . map on_zoom ~ f : Option . some in return ( let % map . Bonsai data = data and options = options and on_zoom = on_zoom in widget ? with_graph ? on_zoom data options ) ; ; |
let create_options ~ x_label ~ y_labels ~ visibility ~ legendFormatter = let labels = x_label :: y_labels in let hidden_legend = Dom_html . createDiv Dom_html . document in Options . create ( ) ~ xlabel : x_label ~ labels ~ visibility ~ legend ` : always ~ labelsDiv_el : hidden_legend ~ legendFormatter ; ; |
let create_default_legend ~ x_label ~ per_series_info = let % sub model , view , inject = Default_legend . create ~ x_label ~ per_series_info in let model = let % map model = model in { Legend_model . visibility = List . map model . series ~ f : Default_legend . Model . Series . is_visible } in let inject = let % map inject = inject in fun data -> inject Default_legend . Action . ( From_graph data ) in return ( Bonsai . Value . map3 model view inject ~ f : Tuple3 . create ) ; ; |
let format_legend inject_legend_data options data = let caller ' s_legend_formatter = Option . bind options ~ f : Options . legendFormatter in Option . iter caller ' s_legend_formatter ~ f ( : fun f -> ignore ( f data : string ) ) ; Vdom . Effect . Expert . handle_non_dom_event_exn ( inject_legend_data data ) ; " this should not be visible " ; ; |
let build_options options visibility legendFormatter x_label y_labels = let our_options = create_options ~ x_label ~ y_labels ~ visibility ~ legendFormatter in match options with | None -> our_options | Some options -> Options . merge options ~ prefer : our_options ; ; |
let visibility ~ legend_model ~ num_series = let visibility = let % map . Bonsai visibility_from_legend = legend_model >>| Legend_model . visibility and num_series = num_series in let visibility_len = List . length visibility_from_legend in if visibility_len < num_series then ( let padding = List . init ( num_series - visibility_len ) ~ f ( : Fn . const true ) in visibility_from_legend @ padding ) else visibility_from_legend in visibility |> Bonsai . Value . cutoff ~ equal [ :% equal : bool list ] ; ; |
let create ~ key ~ x_label ~ per_series_info ? custom_legend ? options ? with_graph ? on_zoom ~ data ( ) = let options = Option . value_map options ~ default ( : Bonsai . Value . return None ) ~ f ( : Bonsai . Value . map ~ f : Option . some ) in let % sub legend = match custom_legend with | Some legend -> Bonsai . read legend | None -> create_default_legend ~ x_label ~ per_series_info in let % pattern_bind legend_model , legend_view , inject_legend_data = legend in let inject_legend_data = Bonsai . Value . cutoff inject_legend_data ~ equal : phys_equal in let y_labels = Bonsai . Value . map per_series_info ~ f ( : List . map ~ f : Per_series_info . label ) in let visibility = let num_series = Bonsai . Value . map per_series_info ~ f : List . length in visibility ~ legend_model ~ num_series in let legendFormatter = Bonsai . Value . map2 inject_legend_data options ~ f : format_legend in let options = Bonsai . Value . map5 options visibility legendFormatter x_label y_labels ~ f : build_options in let % sub graph = create_graph ? with_graph ? on_zoom data options in return @@ let % map graph = graph and legend_view = legend_view and key = key in Vdom . Node . div ~ key ~ attr : ( Vdom . Attr . many_without_merge [ Vdom . Attr . class_ " dygraph " ; Vdom . Attr . style ( Css_gen . flex_container ( ) ) ] ) [ graph ; legend_view ] ; ; |
module type s = sig class type c = object method m : int end } ] | |
module type s = sig class type ct = object method m : int end } ] | |
module type s = sig type top and t = private < . . > and mid and u = private < . . > and v with type u = private < . . > |
module type s = sig type top and t = private < . . > and mid and u = private < . . > and v end } ] | |
let f x = match x with |
let f = fun x -> match x with |
let f = let g x = match x with | ` A -> " A " | ` B -> " B " in g |
let f = let g = function | ` A -> " A " | ` B -> " B " in g |
let f = let g = fun x -> match x with | ` A -> " A " | ` B -> " B " in g |
let z = begin match x with | X -> x end |
let config_converter = ( fun str -> try ignore ( IndentConfig . update_from_string IndentConfig . default str ) ; ` Ok str with Invalid_argument s -> ` Error s ) , ignore ( IndentConfig . update_from_string IndentConfig . default str ) ; ` Ok str |
let f = try match a with B -> x with C -> y |
let g = try match X with | X -> X with | X -> Y |
type ' a return = { return : ' b . ' a -> ' b } [ @@ unboxed ] |
let with_return ( type a ) f = let module M = struct exception Return of a end in let is_alive = ref true in let return a = if not ! is_alive then failwith " use of [ return ] from a [ with_return ] that already returned " ; Exn . raise_without_backtrace ( M . Return a ) in try let a = f { return } in is_alive := false ; a with | exn -> is_alive := false ; ( match exn with | M . Return a -> a | _ -> raise exn ) ; ; |
let with_return_option f = with_return ( fun return -> f { return = ( fun a -> return . return ( Some a ) ) } ; None ) ; ; |
let prepend { return } ~ f = { return = ( fun x -> return ( f x ) ) } |
let str s = Sexp . Atom s |
let list l = Sexp . List l |
let ns_to_string = function | [ base ] -> [ base ] | base :: rst -> let seps = [ " . " ; " __ " ] in List . map ( fun sep -> base ^ sep ^ String . concat " . " rst ) seps | _ -> assert false |
let ns_expend ns m = let m = of_coq_name m in match ns with " " -> m | ns -> ns ^ " . " ^ m |
let type_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts typ = let coqt = ns_expend coqns ( Conflict . get_coq_type rev_namespace conflicts ~ ty : typ . type_name ) in List . map ( fun sep -> list [ str ( libname ^ sep ^ String . concat " . " ( List . rev ( typ . type_name :: rev_namespace ) ) ) ; str " . " ; str coqt ; ] ) [ " . " ; " __ " ] |
let mutually_recursive_type_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts mt = Compat . concat_map ( type_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts ) mt |
let rec intro_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts = function | Right mt -> mutually_recursive_type_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts mt | Left m -> let rev_namespace = m . mod_name :: rev_namespace in let coqmod = Conflict . get_coq_module conflicts ~ m : m . mod_name in let coqns = ns_expend coqns coqmod in mod_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts m Compat . concat_map ( intro_to_sexp ~ libname ~ rev_namespace ~ coqns conflicts ) m . mod_intro |
let of_mod ~ coqns conflicts m = mod_to_sexp ~ libname ( : List . hd m . mod_namespace ) ~ rev_namespace [ : m . mod_name ] ~ coqns conflicts m |
let pp fmt witness = let open Format in fprintf fmt " [ @< v 2 ( > translations % a ) ] " @ ( Pp . pp_list ~ pp_prefix : pp_print_space ~ pp_sep : pp_print_space Sexp . pp ) witness |
module Node : Printable . S with type t = MyCFG . node = struct include Var let to_yojson = Node . to_yojson let show = Node . show_cfg let pretty = Node . pretty_trace let printXml f x = BatPrintf . fprintf f " < value >\ n < data >\ n % s \ n </ data >\ n </ value >\ n " ( XmlUtil . escape ( show x ) ) let name ( ) = " var " let invariant _ _ = Invariant . none let tag _ = failwith " PrintableVar : no tag " let arbitrary ( ) = failwith " PrintableVar : no arbitrary " end |
module Edge : Printable . S with type t = MyARG . inline_edge = struct type t = MyARG . inline_edge [ @@ deriving to_yojson ] let equal = Util . equals let compare = Stdlib . compare let hash = Hashtbl . hash let name ( ) = " edge " let pretty = MyARG . pretty_inline_edge include Printable . SimplePretty ( struct type nonrec t = t let pretty = pretty end ) let invariant _ _ = Invariant . none let tag _ = failwith " Edge : no tag " let arbitrary ( ) = failwith " Edge : no arbitrary " let relift x = x end |
module PathSensitive3 ( Spec : Spec ) : Spec = struct module I = struct include Spec . D let to_int = tag let name ( ) = " D " let printXml f d = BatPrintf . fprintf f " < value >% a </ value " > printXml d end module CC = struct include Spec . C let name ( ) = " C " let printXml f c = BatPrintf . fprintf f " < value >% a </ value " > printXml c end module VI = Printable . Prod3 ( Node ) ( CC ) ( I ) module VIE = struct include Printable . Prod ( VI ) ( Edge ) let leq ( ( v , c , x ' ) , e ) ( ( w , d , y ' ) , f ) = Node . equal v w && Spec . C . equal c d && I . leq x ' y ' && Edge . equal e f let join _ _ = failwith " VIE join " let meet _ _ = failwith " VIE meet " let widen x y = y let narrow x y = x let top ( ) = failwith " VIE top " let is_top _ = failwith " VIE is_top " let bot ( ) = failwith " VIE bot " let is_bot _ = failwith " VIE is_bot " let pretty_diff ( ) ( ( ( v , c , x ' ) , e ) , ( ( w , d , y ' ) , f ) ) = if not ( Node . equal v w ) then Pretty . dprintf " % a not equal % a " Node . pretty v Node . pretty w else if not ( Spec . C . equal c d ) then Pretty . dprintf " % a not equal % a " Spec . C . pretty c Spec . C . pretty d else if not ( Edge . equal e f ) then Pretty . dprintf " % a not equal % a " Edge . pretty e Edge . pretty f else I . pretty_diff ( ) ( x ' , y ' ) end module VIEB = Lattice . LiftBot ( VIE ) module VIES = HoareDomain . Set ( VIEB ) module R = VIES module Dom = struct include HoareDomain . MapBot ( Spec . D ) ( R ) let name ( ) = " PathSensitive ( " ^ name ( ) ^ " ) " let printXml f x = let print_one x r = BatPrintf . fprintf f " \ n < path >% a < analysis name " =\ witness " \>% a </ analysis ></ path " > Spec . D . printXml x R . printXml r in iter ' print_one x let join_reduce a = let rec loop js = function | [ ] -> js | ( x , xr ) :: xs -> let ( ( j , jr ) , r ) = List . fold_left ( fun ( ( j , jr ) , r ) ( x , xr ) -> if Spec . should_join x j then ( Spec . D . join x j , R . join xr jr ) , r else ( j , jr ) , ( x , xr ) :: r ) ( ( x , xr ) , [ ] ) xs in loop ( ( j , jr ) :: js ) r in apply_list ( loop [ ] ) a let leq a b = leq a b || leq ( join_reduce a ) ( join_reduce b ) let binop op a b = op a b |> join_reduce let join = binop join let meet = binop meet let widen = binop widen let narrow = binop narrow let invariant c s = let ( d , _ ) = List . find ( fun ( x , _ ) -> I . to_int x = c . Invariant . i ) ( elements s ) in Spec . D . invariant c d end module SyncSet = HoareDomain . Set ( Spec . D ) module Sync = HoareDomain . MapBot ( Spec . D ) ( SyncSet ) module D = struct include Lattice . Prod ( Dom ) ( Sync ) let printXml f ( d , _ ) = Dom . printXml f d end module G = Spec . G module C = Spec . C module V = Spec . V let name ( ) = " PathSensitive3 ( " ^ Spec . name ( ) " ) " ^ type marshal = Spec . marshal let init = Spec . init let finalize = Spec . finalize let should_join x y = true let exitstate v = ( Dom . singleton ( Spec . exitstate v ) ( R . bot ( ) ) , Sync . bot ( ) ) let startstate v = ( Dom . singleton ( Spec . startstate v ) ( R . bot ( ) ) , Sync . bot ( ) ) let morphstate v ( d , _ ) = ( Dom . map ( Spec . morphstate v ) d , Sync . bot ( ) ) let call_descr = Spec . call_descr let context fd ( l , _ ) = if Dom . cardinal l <> 1 then failwith " PathSensitive3 . context must be called with a singleton set . " else Spec . context fd @@ Dom . choose l let conv ctx x = let rec ctx ' = { ctx with ask = ( fun ( type a ) ( q : a Queries . t ) -> Spec . query ctx ' q ) ; local = x ; split = ( ctx . split % ( fun x -> ( Dom . singleton x ( R . bot ( ) ) , Sync . bot ( ) ) ) ) } in ctx ' let step n c i e = R . singleton ( ` Lifted ( ( n , c , i ) , e ) ) let step n c i e sync = SyncSet . fold ( fun xsync acc -> R . join acc ( step n c xsync e ) ) ( Sync . find i sync ) ( R . bot ( ) ) let step_ctx ctx x e = try step ctx . prev_node ( ctx . context ( ) ) x e ( snd ctx . local ) with Ctx_failure _ -> R . bot ( ) let step_ctx_edge ctx x = step_ctx ctx x ( CFGEdge ctx . edge ) let map ctx f g = let h x xs = try Dom . add ( g ( f ( conv ctx x ) ) ) ( step_ctx_edge ctx x ) xs with Deadcode -> xs in let d = Dom . fold h ( fst ctx . local ) ( Dom . empty ( ) ) |> Dom . reduce in if Dom . is_bot d then raise Deadcode else ( d , Sync . bot ( ) ) let fold ' ctx f g h a = let k x a = try h a x @@ g @@ f @@ conv ctx x with Deadcode -> a in Dom . fold k ( fst ctx . local ) a let fold ' ' ctx f g h a = let k x r a = try h a x r @@ g @@ f @@ conv ctx x with Deadcode -> a in Dom . fold ' k ( fst ctx . local ) a let assign ctx l e = map ctx Spec . assign ( fun h -> h l e ) let vdecl ctx v = map ctx Spec . vdecl ( fun h -> h v ) let body ctx f = map ctx Spec . body ( fun h -> h f ) let return ctx e f = map ctx Spec . return ( fun h -> h e f ) let branch ctx e tv = map ctx Spec . branch ( fun h -> h e tv ) let asm ctx = map ctx Spec . asm identity let skip ctx = map ctx Spec . skip identity let special ctx l f a = map ctx Spec . special ( fun h -> h l f a ) let threadenter ctx lval f args = let g xs x ' ys = let ys ' = List . map ( fun y -> let yr = R . bot ( ) in ( Dom . singleton y yr , Sync . bot ( ) ) ) ys in ys ' @ xs in fold ' ctx Spec . threadenter ( fun h -> h lval f args ) g [ ] let threadspawn ctx lval f args fctx = let fd1 = Dom . choose ( fst fctx . local ) in map ctx Spec . threadspawn ( fun h -> h lval f args ( conv fctx fd1 ) ) let sync ctx reason = fold ' ' ctx Spec . sync ( fun h -> h reason ) ( fun ( a , async ) x r a ' -> ( Dom . add a ' r a , Sync . add a ' ( SyncSet . singleton x ) async ) ) ( Dom . empty ( ) , Sync . bot ( ) ) let query ctx ( type a ) ( q : a Queries . t ) : a Queries . result = match q with | Queries . IterPrevVars f -> Dom . iter ' ( fun x r -> R . iter ( function | ` Lifted ( ( n , c , j ) , e ) -> f ( I . to_int x ) ( n , Obj . repr c , I . to_int j ) e | ` Bot -> failwith " PathSensitive3 . query : range contains bot " ) r ) ( fst ctx . local ) ; begin match ctx . node with | Function _ -> ( ) | _ -> assert ( Sync . is_bot ( snd ctx . local ) ) ; end ; ( ) | Queries . IterVars f -> Dom . iter ' ( fun x r -> f ( I . to_int x ) ) ( fst ctx . local ) ; ( ) | _ -> let module Result = ( val Queries . Result . lattice q ) in fold ' ctx Spec . query identity ( fun x _ f -> Result . join x ( f q ) ) ( Result . bot ( ) ) let should_inline f = not ( Svcomp . is_special_function f ) || Svcomp . is_error_function f ) * true let enter ctx l f a = let g xs x ' ys = let ys ' = List . map ( fun ( x , y ) -> let yr = if should_inline f then step_ctx ctx x ' ( InlineEntry a ) else R . bot ( ) in ( ( Dom . singleton x ( R . bot ( ) ) , snd ctx . local ) , ( Dom . singleton y yr , Sync . bot ( ) ) ) ) ys in ys ' @ xs in fold ' ctx Spec . enter ( fun h -> h l f a ) g [ ] let combine ctx l fe f a fc d = assert ( Dom . cardinal ( fst ctx . local ) = 1 ) ; let cd = Dom . choose ( fst ctx . local ) in let k x y = let r = if should_inline f then let nosync = ( Sync . singleton x ( SyncSet . singleton x ) ) in step ( Function f ) ( Option . get fc ) x ( InlineReturn l ) nosync else step_ctx_edge ctx cd in try Dom . add ( Spec . combine ( conv ctx cd ) l fe f a fc x ) r y with Deadcode -> y in let d = Dom . fold k ( fst d ) ( Dom . bot ( ) ) in if Dom . is_bot d then raise Deadcode else ( d , Sync . bot ( ) ) end |
module NH = Hashtbl . Make ( Node ) |
module NS = Set . Make ( Node ) |
let find_main_entry entrystates = let ( main_entry_nodes , other_entry_nodes ) = entrystates |> List . map fst |> List . partition ( function | FunctionEntry f , _ -> f . svar . vname = " main " | _ , _ -> false ) in match main_entry_nodes , other_entry_nodes with | [ ] , _ -> failwith " no main_entry_nodes " | _ :: _ :: _ , _ -> failwith " multiple main_entry_nodes " | _ , _ :: _ -> failwith " some other_entry_nodes " | [ main_entry ] , [ ] -> main_entry |
let find_loop_heads ( module Cfg : CfgForward ) ( file : Cil . file ) : unit NH . t = let loop_heads = NH . create 100 in let global_visited_nodes = NH . create 100 in let rec iter_node path_visited_nodes node = if NS . mem node path_visited_nodes then NH . replace loop_heads node ( ) else if not ( NH . mem global_visited_nodes node ) then begin NH . replace global_visited_nodes node ( ) ; let new_path_visited_nodes = NS . add node path_visited_nodes in List . iter ( fun ( _ , to_node ) -> iter_node new_path_visited_nodes to_node ) ( Cfg . next node ) end in Cil . iterGlobals file ( function | GFun ( fd , _ ) -> let entry_node = FunctionEntry fd in iter_node NS . empty entry_node | _ -> ( ) ) ; loop_heads |
module type File = sig val file : Cil . file end |
module Invariant ( File : File ) ( Cfg : MyCFG . CfgBidir ) = struct let emit_loop_head = GobConfig . get_bool " witness . invariant . loop - head " let emit_after_lock = GobConfig . get_bool " witness . invariant . after - lock " let emit_other = GobConfig . get_bool " witness . invariant . other " let loop_heads = find_loop_heads ( module Cfg ) File . file let is_after_lock to_node = List . exists ( fun ( edges , from_node ) -> List . exists ( fun ( _ , edge ) -> match edge with | Proc ( _ , Lval ( Var fv , NoOffset ) , args ) -> begin match LibraryFunctions . classify fv . vname args with | ` Lock _ -> true | _ -> false end | _ -> false ) edges ) ( Cfg . prev to_node ) let is_invariant_node cfgnode = if NH . mem loop_heads cfgnode then emit_loop_head else if is_after_lock cfgnode then emit_after_lock else emit_other end |
module InvariantExp = struct module ES = SetDomain . Make ( CilType . Exp ) let rec pullOutCommonConjuncts e = let rec to_conjunct_set = function | Cil . BinOp ( LAnd , e1 , e2 , _ ) -> ES . join ( to_conjunct_set e1 ) ( to_conjunct_set e2 ) | e -> ES . singleton e in let combine_conjuncts es = ES . fold ( fun e acc -> match acc with | None -> Some e | Some acce -> Some ( BinOp ( LAnd , acce , e , Cil . intType ) ) ) es None in match e with | Cil . BinOp ( LOr , e1 , e2 , t ) -> let e1s = pullOutCommonConjuncts e1 in let e2s = pullOutCommonConjuncts e2 in let common = ES . inter e1s e2s in let e1s ' = ES . diff e1s e2s in let e2s ' = ES . diff e2s e1s in ( match combine_conjuncts e1s ' , combine_conjuncts e2s ' with | Some e1e , Some e2e -> ES . add ( BinOp ( LOr , e1e , e2e , Cil . intType ) ) common | _ -> common ) | e -> to_conjunct_set e let process_exp inv = let inv ' = InvariantCil . exp_replace_original_name inv in if GobConfig . get_bool " witness . invariant . split - conjunction " then ES . elements ( pullOutCommonConjuncts inv ' ) else [ inv ' ] end |
type parsing_sate = Initial | EntRef of int ; ; |
let internal_break_words b t = |
let is_whitespace = function | ' ' | ' \ t ' | ' \ n ' | ' \ r ' -> true | _ -> false |
let words_of_string s = let len = String . length s in let finish acc = List . rev acc in let rec iter acc = function | ` Skip next_ofs when next_ofs >= len -> finish acc | ` Skip next_ofs -> if is_whitespace s . [ next_ofs ] then iter acc ( ` Skip ( next_ofs + 1 ) ) else iter acc ( ` Collect ( next_ofs , next_ofs + 1 ) ) | ` Collect ( start_ofs , next_ofs ) when next_ofs >= len -> finish ( ( String . sub s start_ofs ( next_ofs - start_ofs ) ) :: acc ) | ` Collect ( start_ofs , next_ofs ) -> if is_whitespace s . [ next_ofs ] then iter ( String . sub s start_ofs ( next_ofs - start_ofs ) :: acc ) ( ` Skip ( next_ofs + 1 ) ) else iter acc ( ` Collect ( start_ofs , ( next_ofs + 1 ) ) ) in iter [ ] ( ` Skip 0 ) |
type t = { count : int ref ; dict : ( string , int ) Hashtbl . t ; outputs : ( Pipeline . label , Bi_outbuf . t ) Hashtbl . t ; } |
let task_init _ = { count = ref 0 ; dict = ( Hashtbl . create ( 1024 * 1024 ) : ( string , int ) Hashtbl . t ) ; outputs = ( Hashtbl . create mAX_LABEL : ( Pipeline . label , Bi_outbuf . t ) Hashtbl . t ) ; } |
let label_of disco word = if disco . Task . grouping = Pipeline . Group_all then 0 else let h = ref 0 in String . iter ( fun c -> h := ! h + Char . code c ) word ; ! h mod mAX_LABEL |
let output_of init disco label = try Hashtbl . find init . outputs label with Not_found -> let o = Bi_outbuf . create_channel_writer ( disco . Task . out_channel ~ label ) in Hashtbl . add init . outputs label o ; o |
let task_done init disco = Hashtbl . iter ( fun k v -> Wc_b . write_wc ( output_of init disco ( label_of disco k ) ) ( k , v ) ; ) init . dict ; Hashtbl . iter ( fun _l o -> Bi_outbuf . flush_channel_writer o ) init . outputs ; disco . Task . log ( Printf . sprintf " Output % d entries ( % d keys ) into % d files . \ n " ( ! init . count ) ( Hashtbl . length init . dict ) ( Hashtbl . length init . outputs ) ) |
module MapTask = struct module T = Task type init = t let task_init = task_init let task_process init disco in_chan = disco . T . log ( Printf . sprintf " Processing % s ( % d bytes ) with label % d on % s . . . \ n " disco . T . input_url disco . T . input_size disco . T . group_label disco . T . hostname ) ; let rec loop ( ) = List . iter ( fun key -> let v = try Hashtbl . find init . dict key with Not_found -> 0 in Hashtbl . replace init . dict key ( v + 1 ) ; incr init . count ) ( words_of_string ( input_line in_chan ) ) ; loop ( ) in try loop ( ) with End_of_file -> ( ) let task_done = task_done end |
module ReduceTask = struct module T = Task type init = t let task_init = task_init let task_process init disco in_chan = disco . T . log ( Printf . sprintf " Processing % s ( % d bytes ) with label % d on % s . . . \ n " disco . T . input_url disco . T . input_size disco . T . group_label disco . T . hostname ) ; let inp = Bi_inbuf . from_channel in_chan in let rec loop ( ) = let ( k , v ) = Wc_b . read_wc inp in let cnt = try Hashtbl . find init . dict k with Not_found -> 0 in Hashtbl . replace init . dict k ( v + cnt ) ; incr init . count ; loop ( ) in try loop ( ) with End_of_file | Bi_inbuf . End_of_input -> ( ) let task_done = task_done end |
let _ = Worker . start [ ( mAP , ( module MapTask : Task . TASK ) ) ; ( sHUFFLE , ( module ReduceTask : Task . TASK ) ) ; ( rEDUCE , ( module ReduceTask : Task . TASK ) ) ] |
module Single = struct module Spec = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type ( ' witness , ' ledger_proof ) ' ledger_proof t = | Transition of Transaction_snark . Statement . Stable . V2 . t * ' witness | Merge of Transaction_snark . Statement . Stable . V2 . t * ' ledger_proof * ' ledger_proof [ @@ deriving sexp , to_yojson ] to_yojson end end ] end type ( ' witness , ' ledger_proof ) ' ledger_proof t = ( ' witness , ' ledger_proof ) ' ledger_proof Stable . Latest . t = | Transition of Transaction_snark . Statement . t * ' witness | Merge of Transaction_snark . Statement . t * ' ledger_proof * ' ledger_proof [ @@ deriving sexp , to_yojson ] to_yojson let statement = function Transition ( s , _ ) _ -> s | Merge ( s , _ , _ ) _ -> s let gen : ' witness Quickcheck . Generator . t -> ' ledger_proof Quickcheck . Generator . t -> ( ' witness , ' ledger_proof ) ' ledger_proof t Quickcheck . Generator . t = fun gen_witness gen_proof -> let open Quickcheck . Generator in let gen_transition = let open Let_syntax in let % bind statement = Transaction_snark . Statement . gen in let % map witness = gen_witness in Transition ( statement , witness ) witness in let gen_merge = let open Let_syntax in let % bind statement = Transaction_snark . Statement . gen in let % map p1 , p2 = tuple2 gen_proof gen_proof in Merge ( statement , p1 , p2 ) p2 in union [ gen_transition ; gen_merge ] end end |
module Spec = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V1 = struct type ' single t = { instances : ' single One_or_two . Stable . V1 . t ; fee : Currency . Fee . Stable . V1 . t } [ @@ deriving fields , sexp , to_yojson ] to_yojson let to_latest single_latest { instances ; fee } = { instances = One_or_two . Stable . V1 . to_latest single_latest instances ; fee } let of_latest single_latest { instances ; fee } = let open Result . Let_syntax in let % map instances = One_or_two . Stable . V1 . of_latest single_latest instances in { instances ; fee } end end ] end type ' single t = ' single Stable . Latest . t = { instances : ' single One_or_two . t ; fee : Currency . Fee . t } [ @@ deriving fields , sexp , to_yojson ] to_yojson end |
module Result = struct [ %% versioned module Stable = struct module V1 = struct type ( ' spec , ' single ) ' single t = { proofs : ' single One_or_two . Stable . V1 . t ; metrics : ( Core . Time . Stable . Span . V1 . t * [ ` Transition | ` Merge ] ) One_or_two . Stable . V1 . t ; spec : ' spec ; prover : Signature_lib . Public_key . Compressed . Stable . V1 . t } [ @@ deriving fields ] fields end end ] end end |
module Book_view = struct module Visibility = struct type t = | Hidden | Very_hidden | Visible [ @@ deriving sexp_of ] let of_string = function | " hidden " -> Hidden | " veryHidden " -> Very_hidden | " visible " -> Visible | str -> failwithf " Expected ST_Visibility but got ' % s ' " str ( ) end type t = { active_tab : uint32 ; autofilter_date_grouping : bool ; first_sheet : uint32 ; minimized : bool ; show_horizontal_scroll : bool ; show_vertical_scroll : bool ; tab_ratio : uint32 ; visibility : Visibility . t ; window_height : uint32 option ; window_width : uint32 option ; x_window : int32 option ; y_window : int32 option } [ @@ deriving fields , sexp_of ] let default = { active_tab = Uint32 . zero ; autofilter_date_grouping = true ; first_sheet = Uint32 . zero ; minimized = false ; show_horizontal_scroll = true ; show_vertical_scroll = true ; tab_ratio = Uint32 . of_int 600 ; visibility = Visibility . Visible ; window_height = None ; window_width = None ; x_window = None ; y_window = None } let of_xml = function | Xml . Element ( " bookView " , attrs , _ ) -> List . fold attrs ~ init : default ~ f ( : fun t -> function | " activeTab " , v -> { t with active_tab = Uint32 . of_string v } | " autoFilterDateGrouping " , v -> { t with autofilter_date_grouping = bool_of_xsd_boolean v } | " firstSheet " , v -> { t with first_sheet = Uint32 . of_string v } | " minimized " , v -> { t with minimized = bool_of_xsd_boolean v } | " showHorizontalScroll " , v -> { t with show_horizontal_scroll = bool_of_xsd_boolean v } | " showVerticalScroll " , v -> { t with show_vertical_scroll = bool_of_xsd_boolean v } | " tabRatio " , v -> { t with tab_ratio = Uint32 . of_string v } | " visibility " , v -> { t with visibility = Visibility . of_string v } | " windowHeight " , v -> { t with window_height = Some ( Uint32 . of_string v ) } | " windowWidth " , v -> { t with window_width = Some ( Uint32 . of_string v ) } | " xWindow " , v -> { t with x_window = Some ( Int32 . of_string v ) } | " yWindow " , v -> { t with y_window = Some ( Int32 . of_string v ) } | _ -> t ) |> Option . some | _ -> None end |
module Sheet = struct module State = struct type t = | Hidden | Very_hidden | Visible [ @@ deriving sexp_of ] let of_string = function | " hidden " -> Hidden | " veryHidden " -> Very_hidden | " visible " -> Visible | str -> failwithf " Expected ST_SheetState but got ' % s ' " str ( ) end type t = { id : string ; name : string ; sheet_id : uint32 ; state : State . t } [ @@ deriving fields , sexp_of ] let of_xml = function | Xml . Element ( " sheet " , attrs , _ ) -> let name = ref None in let sheet_id = ref None in let state = ref State . Visible in let id = ref None in List . iter attrs ~ f ( : function | " name " , v -> name := Some v | " sheetId " , v -> sheet_id := Some ( Uint32 . of_string v ) | " state " , v -> state := State . of_string v | " r : id " , v -> id := Some v | _ -> ( ) ) ; let name = require_attribute " sheet " " name " ! name in let sheet_id = require_attribute " sheet " " sheetId " ! sheet_id in let id = require_attribute " sheet " " r : id " ! id in Some { name ; sheet_id ; state = ! state ; id } | _ -> None end |
type t = { book_views : Book_view . t list ; sheets : Sheet . t list } [ @@ deriving fields , sexp_of ] |
let empty = { book_views = [ ] ; sheets = [ ] } |
let of_xml = expect_element " workbook " ( fun _ -> List . fold ~ init : empty ~ f ( : fun t -> let open Xml in function | Element ( " bookViews " , _ , children ) -> let book_views = List . filter_map children ~ f : Book_view . of_xml in { t with book_views } | Element ( " sheets " , _ , children ) -> let sheets = List . filter_map children ~ f : Sheet . of_xml in { t with sheets } | _ -> t ) ) |
type worker_name = { base : string ; name : string } |
type Error_monad . error += Closed of worker_name |
let ( ) = register_error_kind ` Permanent ~ id " : worker . closed " ~ title " : Worker closed " ~ description : " An operation on a worker could not complete before it was shut down . " ~ pp ( : fun ppf w -> Format . fprintf ppf " Worker % s [ % s ] has been shut down . " w . base w . name ) Data_encoding . ( conv ( fun { base ; name } -> ( base , name ) ) ( fun ( name , base ) -> { base ; name } ) ( obj1 ( req " worker " ( tup2 string string ) ) ) ) ( function Closed w -> Some w | _ -> None ) ( fun w -> Closed w ) |
module type T = sig module Name : Worker_intf . NAME module Event : Worker_intf . EVENT module Request : Worker_intf . REQUEST module Types : Worker_intf . TYPES type ' kind t type ' kind table type ' a queue and bounded and infinite type dropbox type _ buffer_kind = | Queue : infinite queue buffer_kind | Bounded : { size : int } -> bounded queue buffer_kind | Dropbox : { merge : dropbox t -> any_request -> any_request option -> any_request option ; } -> dropbox buffer_kind and any_request = Any_request : _ Request . t -> any_request val create_table : ' kind buffer_kind -> ' kind table module type HANDLERS = sig type self val on_launch : self -> Name . t -> Types . parameters -> Types . state tzresult Lwt . t val on_request : self -> ' a Request . t -> ' a tzresult Lwt . t val on_no_request : self -> unit tzresult Lwt . t val on_close : self -> unit Lwt . t val on_error : self -> Request . view -> Worker_types . request_status -> error list -> unit tzresult Lwt . t val on_completion : self -> ' a Request . t -> ' a -> Worker_types . request_status -> unit Lwt . t end val launch : ' kind table -> ? timeout : Time . System . Span . t -> Name . t -> Types . parameters -> ( module HANDLERS with type self = ' kind t ) -> ' kind t tzresult Lwt . t val shutdown : _ t -> unit Lwt . t module type BOX = sig type t val put_request : t -> ' a Request . t -> unit val put_request_and_wait : t -> ' a Request . t -> ' a tzresult Lwt . t end module type QUEUE = sig type ' a t val push_request_and_wait : ' q t -> ' a Request . t -> ' a tzresult Lwt . t val push_request : ' q t -> ' a Request . t -> unit Lwt . t val pending_requests : ' a t -> ( Time . System . t * Request . view ) list val pending_requests_length : ' a t -> int end module Dropbox : sig include BOX with type t := dropbox t end module Queue : sig include QUEUE with type ' a t := ' a queue t val push_request_now : infinite queue t -> ' a Request . t -> unit end val protect : _ t -> ? on_error ( : error list -> ' b tzresult Lwt . t ) -> ( unit -> ' b tzresult Lwt . t ) -> ' b tzresult Lwt . t val canceler : _ t -> Lwt_canceler . t val trigger_shutdown : _ t -> unit val record_event : _ t -> Event . t -> unit val log_event : _ t -> Event . t -> unit Lwt . t val state : _ t -> Types . state val pending_requests : _ queue t -> ( Time . System . t * Request . view ) list val status : _ t -> Worker_types . worker_status val current_request : _ t -> ( Time . System . t * Time . System . t * Request . view ) option val information : _ t -> Worker_types . worker_information val list : ' a table -> ( Name . t * ' a t ) list val find_opt : ' a table -> Name . t -> ' a t option end |
module Make ( Name : Worker_intf . NAME ) ( Event : Worker_intf . EVENT ) ( Request : Worker_intf . REQUEST ) ( Types : Worker_intf . TYPES ) ( Logger : Worker_intf . LOGGER with module Event = Event and type Request . view = Request . view ) = struct module Name = Name module Event = Event module Request = Request module Types = Types module Logger = Logger module Nametbl = Hashtbl . MakeSeeded ( struct type t = Name . t let hash = Hashtbl . seeded_hash let equal = Name . equal end ) let base_name = String . concat " " - Name . base type message = Message : ' a Request . t * ' a tzresult Lwt . u option -> message type ' a queue and bounded and infinite type dropbox type _ buffer_kind = | Queue : infinite queue buffer_kind | Bounded : { size : int } -> bounded queue buffer_kind | Dropbox : { merge : dropbox t -> any_request -> any_request option -> any_request option ; } -> dropbox buffer_kind and any_request = Any_request : _ Request . t -> any_request and _ buffer = | Queue_buffer : ( Time . System . t * message ) Lwt_pipe . Unbounded . t -> infinite queue buffer | Bounded_buffer : ( Time . System . t * message ) Lwt_pipe . Bounded . t -> bounded queue buffer | Dropbox_buffer : ( Time . System . t * message ) Lwt_dropbox . t -> dropbox buffer and ' kind t = { timeout : Time . System . Span . t option ; parameters : Types . parameters ; mutable worker : unit Lwt . t ; mutable state : Types . state option ; buffer : ' kind buffer ; canceler : Lwt_canceler . t ; name : Name . t ; id : int ; mutable status : Worker_types . worker_status ; mutable current_request : ( Time . System . t * Time . System . t * Request . view ) option ; logEvent : ( module Internal_event . EVENT with type t = Logger . t ) ; table : ' kind table ; } and ' kind table = { buffer_kind : ' kind buffer_kind ; mutable last_id : int ; instances : ' kind t Nametbl . t ; } let queue_item ? u r = ( Systime_os . now ( ) , Message ( r , u ) ) let drop_request w merge message_box request = try match match Lwt_dropbox . peek message_box with | None -> merge w ( Any_request request ) None | Some ( _ , Message ( old , _ ) ) -> Lwt . ignore_result ( Lwt_dropbox . take message_box ) ; merge w ( Any_request request ) ( Some ( Any_request old ) ) with | None -> ( ) | Some ( Any_request neu ) -> Lwt_dropbox . put message_box ( Systime_os . now ( ) , Message ( neu , None ) ) with Lwt_dropbox . Closed -> ( ) let drop_request_and_wait w message_box request = let ( t , u ) = Lwt . wait ( ) in Lwt . catch ( fun ( ) -> Lwt_dropbox . put message_box ( queue_item ~ u request ) ; t ) ( function | Lwt_dropbox . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) | exn -> raise exn ) module type BOX = sig type t val put_request : t -> ' a Request . t -> unit val put_request_and_wait : t -> ' a Request . t -> ' a tzresult Lwt . t end module type QUEUE = sig type ' a t val push_request_and_wait : ' q t -> ' a Request . t -> ' a tzresult Lwt . t val push_request : ' q t -> ' a Request . t -> unit Lwt . t val pending_requests : ' a t -> ( Time . System . t * Request . view ) list val pending_requests_length : ' a t -> int end module Dropbox = struct let put_request ( w : dropbox t ) request = let ( Dropbox { merge } ) = w . table . buffer_kind in let ( Dropbox_buffer message_box ) = w . buffer in drop_request w merge message_box request let put_request_and_wait ( w : dropbox t ) request = let ( Dropbox_buffer message_box ) = w . buffer in drop_request_and_wait w message_box request end module Queue = struct let push_request ( type a ) ( w : a queue t ) request = match w . buffer with | Queue_buffer message_queue -> Lwt_pipe . Unbounded . push message_queue ( queue_item request ) ; Lwt . return_unit | Bounded_buffer message_queue -> Lwt_pipe . Bounded . push message_queue ( queue_item request ) let push_request_now ( w : infinite queue t ) request = let ( Queue_buffer message_queue ) = w . buffer in if Lwt_pipe . Unbounded . is_closed message_queue then ( ) else Lwt_pipe . Unbounded . push message_queue ( queue_item request ) let push_request_and_wait ( type a ) ( w : a queue t ) request = match w . buffer with | Queue_buffer message_queue -> ( try let ( t , u ) = Lwt . wait ( ) in Lwt_pipe . Unbounded . push message_queue ( queue_item ~ u request ) ; t with Lwt_pipe . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) ) | Bounded_buffer message_queue -> let ( t , u ) = Lwt . wait ( ) in Lwt . try_bind ( fun ( ) -> Lwt_pipe . Bounded . push message_queue ( queue_item ~ u request ) ) ( fun ( ) -> t ) ( function | Lwt_pipe . Closed -> let name = Format . asprintf " % a " Name . pp w . name in fail ( Closed { base = base_name ; name } ) | exn -> raise exn ) let pending_requests ( type a ) ( w : a queue t ) = let peeked = try match w . buffer with | Queue_buffer message_queue -> Lwt_pipe . Unbounded . peek_all_now message_queue | Bounded_buffer message_queue -> Lwt_pipe . Bounded . peek_all_now message_queue with Lwt_pipe . Closed -> [ ] in List . map ( function ( t , Message ( req , _ ) ) -> ( t , Request . view req ) ) peeked let pending_requests_length ( type a ) ( w : a queue t ) = let pipe_length ( type a ) ( q : a buffer ) = match q with | Queue_buffer queue -> Lwt_pipe . Unbounded . length queue | Bounded_buffer queue -> Lwt_pipe . Bounded . length queue | Dropbox_buffer _ -> 1 in pipe_length w . buffer end let close ( type a ) ( w : a t ) = let wakeup = function | ( _ , Message ( _ , Some u ) ) -> let name = Format . asprintf " % a " Name . pp w . name in Lwt . wakeup_later u ( error ( Closed { base = base_name ; name } ) ) | ( _ , Message ( _ , None ) ) -> ( ) in let close_queue message_queue = let messages = Lwt_pipe . Bounded . pop_all_now message_queue in List . iter wakeup messages ; Lwt_pipe . Bounded . close message_queue in let close_unbounded_queue message_queue = let messages = Lwt_pipe . Unbounded . pop_all_now message_queue in List . iter wakeup messages ; Lwt_pipe . Unbounded . close message_queue in match w . buffer with | Queue_buffer message_queue -> close_unbounded_queue message_queue | Bounded_buffer message_queue -> close_queue message_queue | Dropbox_buffer message_box -> ( try Option . iter wakeup ( Lwt_dropbox . peek message_box ) with Lwt_dropbox . Closed -> ( ) ) ; Lwt_dropbox . close message_box let pop ( type a ) ( w : a t ) = let open Lwt_syntax in let pop_queue message_queue = match w . timeout with | None -> let * m = Lwt_pipe . Bounded . pop message_queue in return_some m | Some timeout -> Lwt_pipe . Bounded . pop_with_timeout ( Systime_os . sleep timeout ) message_queue in let pop_unbounded_queue message_queue = match w . timeout with | None -> let * m = Lwt_pipe . Unbounded . pop message_queue in return_some m | Some timeout -> Lwt_pipe . Unbounded . pop_with_timeout ( Systime_os . sleep timeout ) message_queue in match w . buffer with | Queue_buffer message_queue -> pop_unbounded_queue message_queue | Bounded_buffer message_queue -> pop_queue message_queue | Dropbox_buffer message_box -> ( match w . timeout with | None -> let * m = Lwt_dropbox . take message_box in return_some m | Some timeout -> Lwt_dropbox . take_with_timeout ( Systime_os . sleep timeout ) message_box ) let trigger_shutdown w = Lwt . ignore_result ( Lwt_canceler . cancel w . canceler ) let canceler { canceler ; _ } = canceler let lwt_emit w ( status : Logger . status ) = let ( module LogEvent ) = w . logEvent in let time = Systime_os . now ( ) in Lwt . bind ( LogEvent . emit ~ section ( : Internal_event . Section . make_sanitized Name . base ) ( fun ( ) -> Time . System . stamp ~ time status ) ) ( function | Ok ( ) -> Lwt . return_unit | Error el -> Format . kasprintf Lwt . fail_with " Worker_event . emit : % a " pp_print_trace el ) let log_event w evt = lwt_emit w ( Logger . WorkerEvent ( evt , Event . level evt ) ) let record_event w evt = Lwt . ignore_result ( log_event w evt ) module type HANDLERS = sig type self val on_launch : self -> Name . t -> Types . parameters -> Types . state tzresult Lwt . t val on_request : self -> ' a Request . t -> ' a tzresult Lwt . t val on_no_request : self -> unit tzresult Lwt . t val on_close : self -> unit Lwt . t val on_error : self -> Request . view -> Worker_types . request_status -> error list -> unit tzresult Lwt . t val on_completion : self -> ' a Request . t -> ' a -> Worker_types . request_status -> unit Lwt . t end let create_table buffer_kind = { buffer_kind ; last_id = 0 ; instances = Nametbl . create ~ random : true 10 } let worker_loop ( type kind ) handlers ( w : kind t ) = let ( module Handlers : HANDLERS with type self = kind t ) = handlers in let do_close errs = let open Lwt_syntax in let t0 = match w . status with | Running t0 -> t0 | Launching _ | Closing _ | Closed _ -> assert false in w . status <- Closing ( t0 , Systime_os . now ( ) ) ; close w ; let * ( ) = Error_monad . cancel_with_exceptions w . canceler in w . status <- Closed ( t0 , Systime_os . now ( ) , errs ) ; let * ( ) = Handlers . on_close w in Nametbl . remove w . table . instances w . name ; w . state <- None ; return_unit in let rec loop ( ) = Lwt . bind Lwt_tzresult_syntax . ( let * popped = protect ~ canceler : w . canceler ( fun ( ) -> Lwt_result . ok @@ pop w ) in match popped with | None -> Handlers . on_no_request w | Some ( pushed , Message ( request , u ) ) -> ( let current_request = Request . view request in let treated_time = Systime_os . now ( ) in w . current_request <- Some ( pushed , treated_time , current_request ) ; match u with | None -> let * res = Handlers . on_request w request in let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in w . current_request <- None ; let status = Worker_types . { pushed ; treated ; completed } in let *! ( ) = Handlers . on_completion w request res status in let *! ( ) = lwt_emit w ( Request ( current_request , status , None ) ) in return_unit | Some u -> let *! res = Handlers . on_request w request in Lwt . wakeup_later u res ; let *? res = res in let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in let status = Worker_types . { pushed ; treated ; completed } in w . current_request <- None ; let *! ( ) = Handlers . on_completion w request res status in let *! ( ) = lwt_emit w ( Request ( current_request , status , None ) ) in return_unit ) ) Lwt_syntax . ( function | Ok ( ) -> loop ( ) | Error ( Canceled :: _ ) | Error ( Exn Lwt . Canceled :: _ ) | Error ( Exn Lwt_pipe . Closed :: _ ) | Error ( Exn Lwt_dropbox . Closed :: _ ) -> let * ( ) = lwt_emit w Terminated in do_close None | Error errs -> ( let * r = match w . current_request with | Some ( pushed , treated_time , request ) -> let completed_time = Systime_os . now ( ) in let treated = Ptime . diff treated_time pushed in let completed = Ptime . diff completed_time treated_time in w . current_request <- None ; Handlers . on_error w request Worker_types . { pushed ; treated ; completed } errs | None -> assert false in match r with | Ok ( ) -> loop ( ) | Error ( Timeout :: _ as errs ) -> let * ( ) = lwt_emit w Terminated in do_close ( Some errs ) | Error errs -> let * ( ) = lwt_emit w ( Crashed errs ) in do_close ( Some errs ) ) ) in loop ( ) let launch : type kind . kind table -> ? timeout : Time . System . Span . t -> Name . t -> Types . parameters -> ( module HANDLERS with type self = kind t ) -> kind t tzresult Lwt . t = fun table ? timeout name parameters ( module Handlers ) -> let name_s = Format . asprintf " % a " Name . pp name in let full_name = if name_s = " " then base_name else Format . asprintf " % s_ % s " base_name name_s in if Nametbl . mem table . instances name then invalid_arg ( Format . asprintf " Worker . launch : duplicate worker % s " full_name ) else let id = table . last_id <- table . last_id + 1 ; table . last_id in let id_name = if name_s = " " then base_name else Format . asprintf " % s_ % d " base_name id in let canceler = Lwt_canceler . create ( ) in let buffer : kind buffer = match table . buffer_kind with | Queue -> Queue_buffer ( Lwt_pipe . Unbounded . create ( ) ) | Bounded { size } -> Bounded_buffer ( Lwt_pipe . Bounded . create ~ max_size : size ~ compute_size ( : fun _ -> 1 ) ( ) ) | Dropbox _ -> Dropbox_buffer ( Lwt_dropbox . create ( ) ) in let w = { parameters ; name ; canceler ; table ; buffer ; state = None ; id ; worker = Lwt . return_unit ; timeout ; current_request = None ; logEvent = ( module Logger . LogEvent ) ; status = Launching ( Systime_os . now ( ) ) ; } in Nametbl . add table . instances name w ; let open Lwt_tzresult_syntax in let started = if id_name = base_name then None else Some name_s in let *! ( ) = lwt_emit w ( Started started ) in let * state = Handlers . on_launch w name parameters in w . status <- Running ( Systime_os . now ( ) ) ; w . state <- Some state ; w . worker <- Lwt_utils . worker full_name ~ on_event : Internal_event . Lwt_worker_event . on_event ~ run ( : fun ( ) -> worker_loop ( module Handlers ) w ) ~ cancel ( : fun ( ) -> Error_monad . cancel_with_exceptions w . canceler ) ; return w let shutdown w = let open Lwt_syntax in let * ( ) = lwt_emit w Triggering_shutdown in let * ( ) = Error_monad . cancel_with_exceptions w . canceler in w . worker let state w = match ( w . state , w . status ) with | ( None , Launching _ ) -> invalid_arg ( Format . asprintf " Worker . state ( % s [ % a ] ) : state called before worker was initialized " base_name Name . pp w . name ) | ( None , ( Closing _ | Closed _ ) ) -> invalid_arg ( Format . asprintf " Worker . state ( % s [ % a ] ) : state called after worker was terminated " base_name Name . pp w . name ) | ( None , _ ) -> assert false | ( Some state , _ ) -> state let pending_requests q = Queue . pending_requests q let status { status ; _ } = status let current_request { current_request ; _ } = current_request let information ( type a ) ( w : a t ) = { Worker_types . instances_number = Nametbl . length w . table . instances ; wstatus = w . status ; queue_length = ( match w . buffer with | Queue_buffer pipe -> Lwt_pipe . Unbounded . length pipe | Bounded_buffer pipe -> Lwt_pipe . Bounded . length pipe | Dropbox_buffer _ -> 1 ) ; } let list { instances ; _ } = Nametbl . fold ( fun n w acc -> ( n , w ) :: acc ) instances [ ] let find_opt { instances ; _ } = Nametbl . find instances let protect { canceler ; _ } ? on_error f = protect ? on_error ~ canceler f let ( ) = Internal_event . register_section ( Internal_event . Section . make_sanitized Name . base ) end |
let build_rpc_directory state = let dir : unit RPC_directory . t ref = ref RPC_directory . empty in let register0 s f = dir := RPC_directory . register ! dir s ( fun ( ) p q -> f p q ) in let register1 s f = dir := RPC_directory . register ! dir s ( fun ( ( ) , a ) p q -> f a p q ) in let register2 s f = dir := RPC_directory . register ! dir s ( fun ( ( ( ) , a ) , b ) p q -> f a b p q ) in register0 Worker_services . Prevalidators . S . list ( fun ( ) ( ) -> let workers = Prevalidator . running_workers ( ) in let statuses = List . map ( fun ( chain_id , _ , t ) -> ( chain_id , Prevalidator . status t , Prevalidator . information t , Prevalidator . pipeline_length t ) ) workers in return statuses ) ; register1 Worker_services . Prevalidators . S . state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let workers = Prevalidator . running_workers ( ) in let ( _ , _ , t ) = WithExceptions . Option . to_exn ~ none : Not_found @@ List . find ( fun ( c , _ , _ ) -> Chain_id . equal c chain_id ) workers in let status = Prevalidator . status t in let pending_requests = Prevalidator . pending_requests t in let current_request = Prevalidator . current_request t in return { Worker_types . status ; pending_requests ; current_request } ) ; register0 Worker_services . Block_validator . S . state ( fun ( ) ( ) -> let w = Block_validator . running_worker ( ) in return { Worker_types . status = Block_validator . status w ; pending_requests = Block_validator . pending_requests w ; current_request = Block_validator . current_request w ; } ) ; register1 Worker_services . Peer_validators . S . list ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> return ( List . filter_map ( fun ( ( id , peer_id ) , w ) -> if Chain_id . equal id chain_id then Some ( peer_id , Peer_validator . status w , Peer_validator . information w , Peer_validator . pipeline_length w ) else None ) ( Peer_validator . running_workers ( ) ) ) ) ; register2 Worker_services . Peer_validators . S . state ( fun chain peer_id ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let equal ( acid , apid ) ( bcid , bpid ) = Chain_id . equal acid bcid && P2p_peer . Id . equal apid bpid in let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal ( chain_id , peer_id ) ( Peer_validator . running_workers ( ) ) in return { Worker_types . status = Peer_validator . status w ; pending_requests = [ ] ; current_request = Peer_validator . current_request w ; } ) ; register0 Worker_services . Chain_validators . S . list ( fun ( ) ( ) -> return ( List . map ( fun ( id , w ) -> ( id , Chain_validator . status w , Chain_validator . information w , Chain_validator . pending_requests_length w ) ) ( Chain_validator . running_workers ( ) ) ) ) ; register1 Worker_services . Chain_validators . S . state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal : Chain_id . equal chain_id ( Chain_validator . running_workers ( ) ) in return { Worker_types . status = Chain_validator . status w ; pending_requests = Chain_validator . pending_requests w ; current_request = Chain_validator . current_request w ; } ) ; register1 Worker_services . Chain_validators . S . ddb_state ( fun chain ( ) ( ) -> Chain_directory . get_chain_id state chain >>= fun chain_id -> let w = WithExceptions . Option . to_exn ~ none : Not_found @@ List . assoc ~ equal : Chain_id . equal chain_id ( Chain_validator . running_workers ( ) ) in return ( Chain_validator . ddb_information w ) ) ; ! dir |
module type NAME = sig val base : string list type t val encoding : t Data_encoding . t val pp : Format . formatter -> t -> unit val equal : t -> t -> bool end |
module type VIEW = sig type view val encoding : view Data_encoding . t val pp : Format . formatter -> view -> unit end |
module type EVENT = sig type t include VIEW with type view := t val level : t -> Internal_event . level end |
module type REQUEST = sig type ' a t include VIEW val view : ' a t -> view end |
module type TYPES = sig type state type parameters end |
module type LOGGER = sig module Event : EVENT module Request : VIEW type status = | WorkerEvent of ( Event . t * Internal_event . level ) | Request of ( Request . view * Worker_types . request_status * error list option ) | Terminated | Timeout | Crashed of error list | Started of string option | Triggering_shutdown | Duplicate of string type t = status Time . System . stamped module LogEvent : Internal_event . EVENT with type t = t end |
module type STATIC = sig val worker_name : string end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.