text
stringlengths
0
601k
let axiom f x = let axiom f _ = pp f " [ @ axiom . . . ] " @ in spec axiom f x
let rec s_signature_item f x = let s_val_description f vd = let intro = if vd . vprim = [ ] then " val " else " external " in pp f " [ @< 2 >% s @ % a @ :@ % a ] @% a @\ n % a " intro protect_ident vd . vname . txt value_description vd ( item_attributes reset_ctxt ) vd . vattributes val_spec vd . vspec in let print_open f od = pp f " [ @< hov2 > open % s @ % a ] @% a " ( override od . popen_override ) longident_loc od . popen_expr ( item_attributes reset_ctxt ) od . popen_attributes in match x . sdesc with | Sig_type ( rf , l ) -> s_type_declaration_rec_flag f ( rf , l ) | Sig_val vd -> s_val_description f vd | Sig_typext te -> type_extension reset_ctxt f te | Sig_exception ed -> exception_declaration reset_ctxt f ed | Sig_class l -> ( let class_description kwd f ( { pci_params = ls ; pci_name = { txt ; _ } ; _ } as x ) = pp f " [ @< 2 >% s % a % a % s ; ; @:@% a ] @% a " kwd virtual_flag x . pci_virt ( class_params_def reset_ctxt ) ls txt class_type x . pci_expr ( item_attributes reset_ctxt ) x . pci_attributes in match l with | [ ] -> ( ) | [ x ] -> class_description " class " f x | x :: xs -> pp f " [ @< v >% a , @% a ] " @ ( class_description " class " ) x ( list ( class_description " and " ) ) xs ) | Sig_module ( { mdtype = { mdesc = Mod_alias alias ; mattributes = [ ] ; _ } ; _ } as pmd ) -> pp f " [ @< hov > module @ % s @ =@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) longident_loc alias ( item_attributes reset_ctxt ) pmd . mdattributes | Sig_module pmd -> pp f " [ @< hov > module @ % s @ :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes | Sig_modsubst pms -> pp f " [ @< hov > module @ % s @ :=@ % a ] @% a " pms . pms_name . txt longident_loc pms . pms_manifest ( item_attributes reset_ctxt ) pms . pms_attributes | Sig_open od -> print_open f od | Sig_typesubst _l -> pp f " < typesubst " > | Sig_include incl -> pp f " [ @< hov2 > include @ % a ] @% a " module_type incl . pincl_mod ( item_attributes reset_ctxt ) incl . pincl_attributes | Sig_modtype { mtdname = s ; mtdtype = md ; mtdattributes = attrs ; _ } -> pp f " [ @< hov2 > module @ type @ % s % a ] @% a " s . txt ( fun f md -> match md with | None -> ( ) | Some mt -> Format . pp_print_space f ( ) ; pp f " @ =@ % a " s_module_type mt ) md ( item_attributes reset_ctxt ) attrs | Sig_modtypesubst { mtdname = s ; mtdtype = md ; mtdattributes = attrs ; _ } -> let md = match md with None -> assert false | Some mt -> mt in pp f " [ @< hov2 > module @ type @ % s @ :=@ % a ] @% a " s . txt s_module_type md ( item_attributes reset_ctxt ) attrs | Sig_class_type l -> class_type_declaration_list reset_ctxt f l | Sig_recmodule decls -> let rec string_x_module_type_list f ( ? first = true ) l = match l with | [ ] -> ( ) | pmd :: tl -> if not first then pp f " @ [ @< hov2 > and @ % s :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type1 pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes else pp f " [ @< hov2 > module @ rec @ % s :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type1 pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes ; string_x_module_type_list f ~ first : false tl in string_x_module_type_list f decls | Sig_attribute a -> floating_attribute reset_ctxt f a | Sig_extension ( e , a ) -> item_extension reset_ctxt f e ; item_attributes reset_ctxt f a | Sig_function x -> function_ f x | Sig_axiom x -> axiom f x | Sig_ghost_type ( rf , l ) -> pp f " [ @% a ] " @ ( spec s_type_declaration_rec_flag ) ( rf , l ) | Sig_ghost_val vd -> pp f " [ @% a ] " @ ( spec s_val_description ) vd | Sig_ghost_open od -> pp f " [ @% a ] " @ ( spec print_open ) od if x . mattributes <> [ ] then pp f " ( ( % a ) % a ) " s_module_type { x with mattributes = [ ] } ( attributes reset_ctxt ) x . mattributes else match x . mdesc with | Mod_functor ( Unit , me ) -> pp f " functor ( ) ; ; @->@% a " s_module_type me | Mod_functor ( Named ( s , mt ) , me ) -> pp f " functor @ ( % s @ :@ % a ) ; ; @->@% a " ( match s . txt with None -> " _ " | Some s -> s ) s_module_type mt s_module_type me | Mod_with ( mt , [ ] ) -> s_module_type f mt | Mod_with ( mt , l ) -> let with_constraint f = function | Wtype ( li , ( { tparams = ls ; _ } as td ) ) -> let ls = List . map fst ls in pp f " type @ % a % a =@ % a " ( list core_type ~ sep : comma ~ first : rparens ~ last : lparens ) ls longident_loc li s_type_declaration td | Wmodule ( li , li2 ) -> pp f " module % a =@ % a " longident_loc li longident_loc li2 | Wmodtype ( li , mty ) -> pp f " module type % a =@ % a " longident_loc li module_type mty | Wtypesubst ( li , ( { tparams = ls ; _ } as td ) ) -> let ls = List . map fst ls in pp f " type @ % a % a :=@ % a " ( list core_type ~ sep : comma ~ first : lparens ~ last : rparens ) ls longident_loc li s_type_declaration td | Wmodsubst ( li , li2 ) -> pp f " module % a :=@ % a " longident_loc li longident_loc li2 | Wmodtypesubst ( li , mty ) -> pp f " module type % a :=@ % a " longident_loc li module_type mty in pp f " [ @< hov2 >% a @ with @ % a ] " @ s_module_type1 mt ( list with_constraint ~ sep ( : any " and @ " ) ) l | _ -> s_module_type1 f x if x . mattributes <> [ ] then s_module_type f x else match x . mdesc with | Mod_ident li -> pp f " % a " longident_loc li | Mod_alias li -> pp f " ( module % a ) " longident_loc li | Mod_signature s -> pp f " [ @< hv0 [ >@< hv2 > sig @ % a ] @@ end ] " @ ( list s_signature_item ) s | Mod_typeof me -> pp f " [ @< hov2 > module @ type @ of @ % a ] " @ module_expr me | Mod_extension e -> extension reset_ctxt f e | _ -> paren true s_module_type f x
module Blake2 = Blake2 . Make ( )
type block_data = { block : string ; created_at : string ; peer_id : string ; snark_work : string option [ @ default None ] None }
module Proof_data = struct type t = { proof : Ledger_proof . Stable . Latest . t ; proof_time : Core_kernel . Time . Span . t ; snark_work_fee : Currency . Fee . Stable . Latest . t } [ @@ deriving bin_io_unversioned ] bin_io_unversioned end
let sign_blake2_hash ~ private_key s = let module Field = Snark_params . Tick . Field in let blake2 = Blake2 . digest_string s in let field_elements = [ ] || in let bitstrings = [ | Blake2 . to_raw_string blake2 |> Blake2 . string_to_bits |> Array . to_list ] | in let input : ( Field . t , bool ) bool Random_oracle . Legacy . Input . t = { field_elements ; bitstrings } in Schnorr . Legacy . sign private_key input
let send_uptime_data ~ logger ~ interruptor ( ~ submitter_keypair : Keypair . t ) t ~ url ~ state_hash ~ produced block_data = let open Interruptible . Let_syntax in let make_interruptible f = Interruptible . lift f interruptor in let block_data_json = block_data_to_yojson block_data in let block_data_string = Yojson . Safe . to_string block_data_json in let signature = sign_blake2_hash ~ private_key : submitter_keypair . private_key block_data_string in let json = ` Assoc [ ( " data " , block_data_json ) block_data_json ; ( " signature " , Signature . to_yojson signature ) signature ; ( " submitter " , Public_key . to_yojson submitter_keypair . public_key ) public_key ] in let headers = Cohttp . Header . of_list [ ( " Content - Type " , " application / json ) " ] in let metadata_of_body = function | ` String s -> [ ( " error " , ` String s ) s ] | ` Strings ss -> [ ( " error " , ` List ( List . map ss ~ f ( : fun s -> ` String s ) s ) s ) s ] | ` Empty | ` Pipe _ -> [ ] in let max_attempts = 8 in let attempt_pause_sec = 4 . 0 in let unrecoverable_status_codes = [ 400 ; 401 ; 411 ; 413 ] in let run_attempt attempt = let interruptible = match % map make_interruptible ( Monitor . try_with ~ here [ :% here ] here ~ extract_exn : true ( fun ( ) -> Cohttp_async . Client . post ~ headers ~ body : ( Yojson . Safe . to_string json |> Cohttp_async . Body . of_string ) of_string url ) ) with | Ok ( { status ; _ } , body ) body -> let status_code = Cohttp . Code . code_of_status status in let status_string = Cohttp . Code . string_of_status status in let unretriable = List . mem unrecoverable_status_codes status_code ~ equal : Int . equal in let succeeded = status_code = 200 in ( if succeeded then [ % log info ] info " Sent block with state hash $ state_hash to uptime service at URL \ $ url " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " includes_snark_work " , ` Bool ( Option . is_some block_data . snark_work ) snark_work ) ; ( " is_produced_block " , ` Bool produced ) produced ] else if unretriable then [ % log error ] error " Got unrecoverable response from update service backend at URL \ $ url , not retrying to send block " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ; ( " payload " , json ) json ] else if attempt >= max_attempts then let base_metadata = [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ; ( " payload " , json ) json ] in let extra_metadata = metadata_of_body body in let metadata = base_metadata @ extra_metadata in [ % log error ] error " After % d attempts , failed to send block with state hash \ $ state_hash to uptime service at URL $ url , no more retries " max_attempts ~ metadata else let base_metadata = [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ] in let extra_metadata = metadata_of_body body in let metadata = base_metadata @ extra_metadata in [ % log info ] info " Failure when sending block with state hash $ state_hash to \ uptime service at URL $ url , attempt % d of % d , retrying " attempt max_attempts ~ metadata ) ; succeeded || unretriable | Error exn -> [ % log warn ] warn " Error when sending block with state hash $ state_hash to uptime \ service at URL $ url " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " payload " , json ) json ; ( " error " , ` String ( Exn . to_string exn ) exn ) exn ] ; false in match % map . Deferred Interruptible . force interruptible with | Ok succeeded -> succeeded | Error _ -> [ % log error ] error " In uptime service , POST of block with state hash $ state_hash was \ interrupted " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " payload " , json ) json ] ; true in let rec go attempt = let open Deferred . Let_syntax in let % bind succeeded = run_attempt attempt in if succeeded then Deferred . return ( ) else if attempt < max_attempts then ( let % bind ( ) = Async . after ( Time . Span . of_sec attempt_pause_sec ) attempt_pause_sec in [ % log info ] info " In uptime service , retrying to send block , attempt % d of % d attempts \ allowed " attempt max_attempts ; go ( attempt + 1 ) 1 ) else Deferred . unit in make_interruptible ( go 1 ) 1
let block_base64_of_breadcrumb breadcrumb = let external_transition = breadcrumb |> Transition_frontier . Breadcrumb . block |> External_transition . compose in let block_string = Binable . to_string ( module External_transition . Raw . Stable . Latest ) Latest external_transition in Base64 . encode_exn block_string
let send_produced_block_at ~ logger ~ interruptor ~ url ~ peer_id ( ~ submitter_keypair : Keypair . t ) t ~ block_produced_bvar tm = let open Interruptible . Let_syntax in let make_interruptible f = Interruptible . lift f interruptor in let timeout_min = 3 . 0 in let % bind ( ) = make_interruptible ( at tm ) tm in match % bind make_interruptible ( with_timeout ( Time . Span . of_min timeout_min ) timeout_min ( Bvar . wait block_produced_bvar ) block_produced_bvar ) with | ` Timeout -> [ % log error ] error " Uptime service did not get a produced block within % 0 . 1f minutes \ after scheduled time " timeout_min ; return ( ) | ` Result breadcrumb -> let block_base64 = block_base64_of_breadcrumb breadcrumb in let state_hash = Transition_frontier . Breadcrumb . state_hash breadcrumb in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : true block_data
let send_block_and_transaction_snark ~ logger ~ interruptor ~ url ~ snark_worker ~ transition_frontier ~ peer_id ( ~ submitter_keypair : Keypair . t ) t ~ snark_work_fee = match Broadcast_pipe . Reader . peek transition_frontier with | None -> [ % log info ] info " Transition frontier not available to send a block to uptime service " ; Interruptible . return ( ) | Some tf -> ( let make_interruptible f = Interruptible . lift f interruptor in let breadcrumb = Transition_frontier . best_tip tf in let block_base64 = block_base64_of_breadcrumb breadcrumb in let open Interruptible . Let_syntax in let message = Sok_message . create ~ fee : snark_work_fee ~ prover ( : Public_key . compress submitter_keypair . public_key ) public_key in let best_tip = Transition_frontier . best_tip tf in let best_tip_block = Transition_frontier . Breadcrumb . block best_tip in if List . is_empty ( Mina_block . transactions ~ constraint_constants : Genesis_constants . Constraint_constants . compiled best_tip_block ) then ( [ % log info ] info " No transactions in block , sending block without SNARK work to \ uptime service " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data ) else let best_tip_staged_ledger = Transition_frontier . Breadcrumb . staged_ledger best_tip in match Staged_ledger . all_work_pairs best_tip_staged_ledger ~ get_state ( : fun state_hash -> match Transition_frontier . find_protocol_state tf state_hash with | None -> Error ( Error . createf " Could not find state_hash % s in transition frontier \ for uptime service " ( State_hash . to_base58_check state_hash ) state_hash ) | Some protocol_state -> Ok protocol_state ) with | Error e -> [ % log error ] error " Could not get SNARK work from best tip staged ledger for uptime \ service " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok [ ] -> [ % log info ] info " No SNARK jobs available for uptime service , sending just the \ block " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data | Ok job_one_or_twos -> ( let transitions = List . concat_map job_one_or_twos ~ f : One_or_two . to_list |> List . filter ~ f ( : function | Snark_work_lib . Work . Single . Spec . Transition _ -> true | Merge _ -> false ) in let staged_ledger_hash = Mina_block . header best_tip_block |> Mina_block . Header . protocol_state |> Mina_state . Protocol_state . blockchain_state |> Mina_state . Blockchain_state . staged_ledger_hash in match List . find transitions ~ f ( : fun transition -> match transition with | Snark_work_lib . Work . Single . Spec . Transition ( { target ; _ } , _ ) _ -> Pasta_bindings . Fp . equal target . ledger ( Staged_ledger_hash . ledger_hash staged_ledger_hash ) staged_ledger_hash | Merge _ -> failwith " Expected Transition work , not Merge " ) with | None -> [ % log info ] info " No transactions in block match staged ledger hash , sending \ block without SNARK work " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data | Some single_spec -> ( match % bind make_interruptible ( Uptime_snark_worker . perform_single snark_worker ( message , single_spec ) single_spec ) with | Error e -> [ % log error ] error " Error when running uptime service SNARK worker on a \ transaction " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok ( Error e ) e -> [ % log error ] error " Error computing SNARK work for uptime service " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok ( Ok ( proof , proof_time ) proof_time ) proof_time -> let proof_data : Proof_data . t = { proof ; proof_time ; snark_work_fee } in let proof_string = Binable . to_string ( module Proof_data ) Proof_data proof_data in let snark_work_base64 = Base64 . encode_exn proof_string in let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = Some snark_work_base64 } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data ) ) )
let start ~ logger ~ uptime_url ~ snark_worker_opt ~ transition_frontier ~ time_controller ~ block_produced_bvar ~ uptime_submitter_keypair ~ get_next_producer_timing ~ get_snark_work_fee ~ get_peer = match uptime_url with | None -> [ % log info ] info " Not running uptime service , no URL given " ; ( ) | Some url -> [ % log info ] info " Starting uptime service using URL $ url " ~ metadata [ : ( " url " , ` String ( Uri . to_string url ) url ) url ] ; let snark_worker : Uptime_snark_worker . t = Option . value_exn snark_worker_opt in let slot_duration_ms = Consensus . Configuration . t ~ constraint_constants : Genesis_constants . Constraint_constants . compiled ~ protocol_constants : Genesis_constants . compiled . protocol |> Consensus . Configuration . slot_duration |> Float . of_int in let make_slots_span min = Block_time . Span . of_time_span ( Time . Span . of_ms ( slot_duration_ms . * min ) min ) min in let five_slots_span = make_slots_span 5 . 0 in let four_slots_span = make_slots_span 4 . 0 in let wait_until_iteration_start block_tm = let now = Block_time . now time_controller in if Block_time ( . < ) now block_tm then at ( Block_time . to_time block_tm ) block_tm else ( [ % log warn ] warn " In uptime service , current block time is past desired start of \ iteration " ; return ( ) ) in let register_iteration = let interrupt_ivar = ref ( Ivar . create ( ) ) in fun ( ) -> Ivar . fill_if_empty ! interrupt_ivar ( ) ; Deferred . create ( fun ivar -> interrupt_ivar := ivar ) ivar in let run_iteration next_block_tm : Block_time . t Deferred . t = let get_next_producer_time_opt ( ) = match get_next_producer_timing ( ) with | None -> [ % log trace ] trace " Next producer timing not set for uptime service " ; None | Some timing -> ( let open Daemon_rpcs . Types . Status . Next_producer_timing in match timing . timing with | Check_again _tm -> [ % log trace ] trace " Next producer timing not available for uptime service " ; None | Evaluating_vrf _ -> [ % log trace ] trace " Evaluating VRF , wait for block production status for \ uptime service " ; None | Produce prod_tm | Produce_now prod_tm -> Some ( Block_time . to_time prod_tm . time ) time ) in [ % log trace ] trace " Waiting for next 5 - slot boundary to start work in uptime service " ~ metadata : [ ( " boundary_block_time " , Block_time . to_yojson next_block_tm ) next_block_tm ; ( " boundary_time " , ` String ( Block_time . to_time next_block_tm |> Time . to_string ) to_string ) ] ; let % bind ( ) = wait_until_iteration_start next_block_tm in let interruptor = register_iteration ( ) in let open Interruptible . Let_syntax in Interruptible . don ' t_wait_for ( [ % log trace ] trace " Determining which action to take in uptime service " ; match get_peer ( ) with | None -> [ % log warn ] warn " Daemon is not yet a peer in the gossip network , uptime \ service not sending a produced block " ; Interruptible . return ( ) | Some ( { peer_id ; _ } : Network_peer . Peer . t ) t -> ( let submitter_keypair = Option . value_exn uptime_submitter_keypair in let send_just_block next_producer_time = [ % log info ] info " Uptime service will attempt to send the next produced \ block " ; send_produced_block_at ~ logger ~ interruptor ~ url ~ peer_id ~ submitter_keypair ~ block_produced_bvar next_producer_time in let send_block_and_snark_work ( ) = [ % log info ] info " Uptime service will attempt to send a block and SNARK work " ; let snark_work_fee = get_snark_work_fee ( ) in send_block_and_transaction_snark ~ logger ~ interruptor ~ url ~ snark_worker ~ transition_frontier ~ peer_id ~ submitter_keypair ~ snark_work_fee in match get_next_producer_time_opt ( ) with | None -> send_block_and_snark_work ( ) | Some next_producer_time -> let four_slots_from_start = Block_time . add next_block_tm four_slots_span |> Block_time . to_time in if Time ( . <= ) next_producer_time four_slots_from_start then let % bind ( ) = send_block_and_snark_work ( ) in send_just_block next_producer_time else send_block_and_snark_work ( ) ) ) ; Deferred . return ( Block_time . add next_block_tm five_slots_span ) five_slots_span in let next_slot_block_time = let block_time_ms_int64 = Block_time . now time_controller |> Block_time . to_int64 in let slot_duration_ms_int64 = Float . to_int64 slot_duration_ms in let next_slot_ms = if Int64 . equal Int64 . zero ( Int64 ( . rem ) rem block_time_ms_int64 slot_duration_ms_int64 ) slot_duration_ms_int64 then block_time_ms_int64 else let last_slot_no = Int64 ( . / ) block_time_ms_int64 slot_duration_ms_int64 in Int64 ( . * ) ( Int64 . succ last_slot_no ) last_slot_no slot_duration_ms_int64 in Block_time . of_int64 next_slot_ms in Async . Deferred . forever next_slot_block_time run_iteration
module Worker_state = struct module type S = sig val perform_single : Sok_message . t * Prod . single_spec -> ( Ledger_proof . t * Time . Span . t ) t Deferred . Or_error . t end type init_arg = Logger . Stable . Latest . t [ @@ deriving bin_io_unversioned ] bin_io_unversioned type t = ( module S ) S let create ~ logger : t Deferred . t = Memory_stats . log_memory_stats logger ~ process " : uptime service SNARK worker " ; Deferred . return ( let module M = struct let perform_single ( message , single_spec ) single_spec = let % bind ( worker_state : Prod . Worker_state . t ) t = Prod . Worker_state . create ~ constraint_constants : Genesis_constants . Constraint_constants . compiled ~ proof_level : Full ( ) in Prod . perform_single worker_state ~ message single_spec end in ( module M : S ) S ) let get = Fn . id end
module Worker = struct module T = struct module F = Rpc_parallel . Function type ' w functions = { perform_single : ( ' w , Sok_message . t * Prod . single_spec , ( Ledger_proof . t * Time . Span . t ) t Or_error . t ) F . t } module Worker_state = Worker_state module Connection_state = struct type init_arg = unit [ @@ deriving bin_io_unversioned ] bin_io_unversioned type t = unit end module Functions ( C : Rpc_parallel . Creator with type worker_state := Worker_state . t and type connection_state := Connection_state . t ) t = struct let perform_single ( w : Worker_state . t ) t msg_and_single_spec = let ( module M ) M = Worker_state . get w in M . perform_single msg_and_single_spec let functions = let f ( i , o , f ) f = C . create_rpc ~ f ( : fun ~ worker_state ~ conn_state : _ i -> f worker_state i ) i ~ bin_input : i ~ bin_output : o ( ) in { perform_single = f ( [ % bin_type_class : Sok_message . Stable . Latest . t * Prod . single_spec ] single_spec , [ % bin_type_class : ( Ledger_proof . Stable . Latest . t * Time . Span . t ) t Or_error . t ] t , perform_single ) } let init_worker_state logger = [ % log info ] info " Uptime SNARK worker started " ; Worker_state . create ~ logger let init_connection_state ~ connection : _ ~ worker_state : _ ( ) = Deferred . unit end end include Rpc_parallel . Make ( T ) T end
type t = { connection : Worker . Connection . t ; process : Process . t ; logger : Logger . Stable . Latest . t }
let create ~ logger ~ pids : t Deferred . t = let on_failure err = [ % log error ] error " Uptime service SNARK worker process failed with error $ err " ~ metadata [ : ( " err " , Error_json . error_to_yojson err ) err ] ; Error . raise err in [ % log info ] info " Starting a new uptime service SNARK worker process " ; let % map connection , process = Worker . spawn_in_foreground_exn ~ connection_timeout ( : Time . Span . of_min 1 ) . ~ on_failure ~ shutdown_on : Connection_closed ~ connection_state_init_arg ( ) : logger in [ % log info ] info " Daemon started process of kind $ process_kind with pid \ $ uptime_snark_worker_pid " ~ metadata : [ ( " uptime_snark_worker_pid " , ` Int ( Process . pid process |> Pid . to_int ) to_int ) to_int ; ( " process_kind " , ` String Child_processes . Termination ( . show_process_kind Uptime_snark_worker ) Uptime_snark_worker ) ] ; Child_processes . Termination . register_process pids process Child_processes . Termination . Uptime_snark_worker ; don ' t_wait_for @@ Pipe . iter ( Process . stdout process |> Reader . pipe ) pipe ~ f ( : fun stdout -> return @@ [ % log debug ] debug " Uptime SNARK worker stdout : $ stdout " ~ metadata [ : ( " stdout " , ` String stdout ) stdout ] ) ; don ' t_wait_for @@ Pipe . iter ( Process . stderr process |> Reader . pipe ) pipe ~ f ( : fun stderr -> return @@ [ % log error ] error " Uptime SNARK worker stderr : $ stderr " ~ metadata [ : ( " stderr " , ` String stderr ) stderr ] ) ; { connection ; process ; logger }
let perform_single { connection ; _ } ( ( _message , _single_spec ) _single_spec as arg ) arg = Worker . Connection . run connection ~ f : Worker . functions . perform_single ~ arg
let root_dir = ref Sundials . RootDirs . Increasing
let args = [ ( " - e " , Arg . Unit ( fun ( ) -> root_dir := Sundials . RootDirs . IncreasingOrDecreasing ) , " Use either instead of up ( ) " ) ; ]
let _ = Arg . parse args ( fun _ -> ( ) ) " upvseither : test different types of root detection "
let print_with_time t v = Printf . printf " % e " t ; Sundials . RealArray . iter ( Printf . printf " \ t % e " ) v ; print_newline ( )
let f t_s y yd = yd . { x } <- - 1 . 0 ; Printf . printf " f ( % e , [ % e ] ) = [ % e ] \ n " t_s y . { x } yd . { x }
let g t_s y gout = gout . { 0 } <- y . { x } ; Printf . printf " g ( % e , [ % e ] ) = [ % e ] \ n " t_s y . { x } gout . { 0 }
let y = Sundials . RealArray . of_array [ | x_i ] |
let s = Cvode . ( init Adams default_tolerances f ~ roots ( : 1 , g ) 0 . y_nvec )
let rootdata = Sundials . Roots . create 1
let _ = Cvode . set_all_root_directions s ! root_dir
let _ = Cvode . set_stop_time s max_sim_t
let _ = Cvode . set_max_step s 5 . 0
let _ = Printf . printf " time \ t \ t t \ n " ; Printf . printf " ------------------------------------\ n " ; print_with_time 0 . 0 y ; try let i = ref 0 in while true do let ( t ' , result ) = Cvode . solve_one_step s max_sim_t y_nvec in Printf . printf " \ nstep % 3d . \ n " ! i ; incr i ; print_with_time t ' y ; Printf . printf " \ t \ t ( step size = % e ) \ n " ( Cvode . get_last_step s ) ; match result with | Cvode . RootsFound -> print_endline " ** root found " | Cvode . StopTimeReached -> raise Done | Cvode . Success -> ( ) done with Done -> ( )
let get_file_size fd = Unix . handle_unix_error Unix . fstat fd |> fun { Unix . st_size ; _ } -> st_size
type t = { freelist : int Queue . t ; mutable insize : int ; mutable offset : Int63 . t ; mutable reads : int ; mutable writes : int ; mutable write_left : int ; mutable read_left : int ; block_size : int ; infd : Unix . file_descr ; outfd : Unix . file_descr ; }
let pp ppf { insize ; offset ; reads ; writes ; write_left ; read_left ; _ } = Fmt . pf ppf " insize % d offset % a reads % d writes % d rleft % d wleft % d " insize Int63 . pp offset reads writes read_left write_left
type req = { op : [ ` R | ` W ] ; fixed_off : int ; mutable len : int ; fileoff : Int63 . t ; mutable off : int ; t : t ; }
let pp_req ppf { op ; len ; off ; fixed_off ; fileoff ; t ; _ } = Fmt . pf ppf " [ % s fileoff % a len % d off % d fixedoff % d ] [ % a ] " ( match op with ` | R -> " r " ` | W -> " w " ) Int63 . pp fileoff len off fixed_off pp t
let queue_read uring t len = let fixed_off = Queue . pop t . freelist in let req = { op ` = R ; fixed_off ; fileoff = t . offset ; len ; off = 0 ; t } in Logs . debug ( fun l -> l " queue_read : % a " pp_req req ) ; let r = Uring . read_fixed uring ~ file_offset : t . offset t . infd ~ off : fixed_off ~ len req in assert ( r <> None ) ; t . offset <- Int63 . ( add t . offset ( of_int len ) ) ; t . read_left <- t . read_left - len ; t . reads <- t . reads + 1
let handle_read_completion uring req res = Logs . debug ( fun l -> l " read_completion : res =% d % a " res pp_req req ) ; let bytes_to_read = req . len - req . off in match res with | 0 -> Logs . debug ( fun l -> l " eof % a " pp_req req ) ; | n when n = eagain || n = eintr -> let r = Uring . read_fixed ~ file_offset : req . fileoff uring req . t . infd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < 0 -> raise ( Failure ( " unix errorno " ^ ( string_of_int n ) ) ) | n when n < bytes_to_read -> req . off <- req . off + n ; req . len <- req . len - n ; let r = Uring . read_fixed ~ file_offset : req . fileoff uring req . t . infd ~ off ( : req . fixed_off + req . off ) ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued short read : % a " pp_req req ) ; | n when n = bytes_to_read -> req . t . reads <- req . t . reads - 1 ; req . t . writes <- req . t . writes + 1 ; let req = { req with op ` = W ; off = 0 ; len = req . len + req . off } in let r = Uring . write_fixed uring ~ file_offset : req . fileoff req . t . outfd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " queued write : % a " pp_req req ) ; | n -> raise ( Failure ( Printf . sprintf " unexpected read result % d > % d " bytes_to_read n ) )
let handle_write_completion uring req res = Logs . debug ( fun l -> l " write_completion : res =% d % a " res pp_req req ) ; let bytes_to_write = req . len - req . off in match res with | 0 -> raise End_of_file | n when n = eagain || n = eintr -> let r = Uring . write_fixed ~ file_offset : req . fileoff uring req . t . outfd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < 0 -> failwith ( Fmt . str " unix error % d " ( - n ) ) | n when n < bytes_to_write -> req . off <- req . off + n ; req . len <- req . len - n ; let r = Uring . write_fixed ~ file_offset : req . fileoff uring req . t . outfd ~ off ( : req . fixed_off + req . off ) ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued short write : % a " pp_req req ) ; | n when n = bytes_to_write -> req . t . writes <- req . t . writes - 1 ; req . t . write_left <- req . t . write_left - req . len ; Queue . push req . fixed_off req . t . freelist ; Logs . debug ( fun l -> l " write done : % a " pp_req req ) ; | n -> raise ( Failure ( Printf . sprintf " unexpected writev result % d > % d " bytes_to_write n ) )
let handle_completion uring req res = match req . op with ` | R -> handle_read_completion uring req res ` | W -> handle_write_completion uring req res
let copy_file uring t = while t . write_left > 0 || t . read_left > 0 do let rec submit_reads ( ) = if t . read_left > 0 then begin if t . reads + t . writes < ( Uring . queue_depth uring ) then begin let size = min t . block_size t . read_left in queue_read uring t size ; submit_reads ( ) end end ; in submit_reads ( ) ; let num = Uring . submit uring in Logs . debug ( fun l -> l " % a : % d " Fmt . ( styled ` Yellow string ) " submit " num ) ; let got_completion = ref false in let rec handle_completions ( ) = if t . write_left > 0 then begin let check_q = if ! got_completion then Uring . peek uring else Uring . wait uring in match check_q with | None -> Logs . debug ( fun l -> l " completions : retry so finishing loop " ) | Some { data ; result } -> handle_completion uring data result ; got_completion := true ; handle_completions ( ) ; end in handle_completions ( ) ; let num = Uring . submit uring in Logs . debug ( fun l -> l " % a : % d " Fmt . ( styled ` Yellow string ) " submit " num ) ; done
let run_cp block_size queue_depth infile outfile ( ) = let infd = Unix . ( handle_unix_error ( openfile infile [ O_RDONLY ] ) 0 ) in let outfd = Unix . ( handle_unix_error ( openfile outfile [ O_WRONLY ; O_CREAT ; O_TRUNC ] ) 0o644 ) in let insize = get_file_size infd in let freelist = Queue . create ( ) in for i = 0 to queue_depth - 1 do Queue . push ( block_size * i ) freelist ; done ; let t = { freelist ; block_size ; insize ; offset = Int63 . zero ; reads = 0 ; writes = 0 ; write_left = insize ; read_left = insize ; infd ; outfd } in Logs . debug ( fun l -> l " starting : % a bs =% d qd =% d " pp t block_size queue_depth ) ; let fixed_buf_len = queue_depth * block_size in let uring = Uring . create ~ queue_depth ( ) in let fbuf = Bigarray . ( Array1 . create char c_layout fixed_buf_len ) in Fun . protect ( fun ( ) -> match Uring . set_fixed_buffer uring fbuf with | Ok ( ) -> copy_file uring t | Error ` ENOMEM -> failwith " Can ' t lock memory ( check RLIMIT_MEMLOCK ) " ) ~ finally ( : fun ( ) -> Unix . close infd ; Unix . close outfd ; Uring . exit uring )
let get_file_size fd = Unix . handle_unix_error Unix . fstat fd |> fun { Unix . st_size ; _ } -> st_size
type t = { mutable insize : int ; mutable offset : Int63 . t ; mutable reads : int ; mutable writes : int ; mutable write_left : int ; mutable read_left : int ; block_size : int ; infd : Unix . file_descr ; outfd : Unix . file_descr ; }
let pp ppf { insize ; offset ; reads ; writes ; write_left ; read_left ; _ } = Fmt . pf ppf " insize % d offset % a reads % d writes % d rleft % d wleft % d " insize Int63 . pp offset reads writes read_left write_left
type iovec = { all : Cstruct . t list ; mutable next : Cstruct . t list ; }
type req = { op : [ ` R | ` W ] ; iov : iovec ; len : int ; fileoff : Int63 . t ; mutable off : int ; t : t ; }
let pp_req ppf { op ; len ; off ; fileoff ; t ; _ } = Fmt . pf ppf " [ % s fileoff % a len % d off % d ] [ % a ] " ( match op with ` | R -> " r " ` | W -> " w " ) Int63 . pp fileoff len off pp t
let queue_read uring t len = let all = [ Cstruct . create len ] in let iov = { all ; next = all } in let req = { op ` = R ; iov ; fileoff = t . offset ; len ; off = 0 ; t } in Logs . debug ( fun l -> l " queue_read : % a " pp_req req ) ; let r = Uring . readv uring ~ file_offset : t . offset t . infd iov . next req in assert ( r <> None ) ; t . offset <- Int63 . ( add t . offset ( of_int len ) ) ; t . read_left <- t . read_left - len ; t . reads <- t . reads + 1
let handle_read_completion uring req res = Logs . debug ( fun l -> l " read_completion : res =% d % a " res pp_req req ) ; let bytes_to_read = req . len - req . off in match res with | 0 -> Logs . debug ( fun l -> l " eof % a " pp_req req ) ; | n when n = eagain || n = eintr -> let r = Uring . readv ~ file_offset : req . fileoff uring req . t . infd req . iov . next req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < 0 -> raise ( Failure ( " unix errorno " ^ ( string_of_int n ) ) ) | n when n < bytes_to_read -> req . iov . next <- Cstruct . shiftv req . iov . next n ; req . off <- req . off + n ; let r = Uring . readv ~ file_offset ( : Int63 . of_int req . off ) uring req . t . infd req . iov . next req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued short read : % a " pp_req req ) ; | n when n = bytes_to_read -> req . t . reads <- req . t . reads - 1 ; req . t . writes <- req . t . writes + 1 ; req . iov . next <- req . iov . all ; let req = { req with op ` = W ; off = 0 } in let r = Uring . writev uring ~ file_offset : req . fileoff req . t . outfd req . iov . next req in assert ( r <> None ) ; Logs . debug ( fun l -> l " queued write : % a " pp_req req ) ; | n -> raise ( Failure ( Printf . sprintf " unexpected readv result % d > % d " bytes_to_read n ) )
let handle_write_completion uring req res = Logs . debug ( fun l -> l " write_completion : res =% d % a " res pp_req req ) ; let bytes_to_write = req . len - req . off in match res with | 0 -> raise End_of_file | n when n = eagain || n = eintr -> let r = Uring . writev ~ file_offset : req . fileoff uring req . t . infd req . iov . next req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < bytes_to_write -> req . iov . next <- Cstruct . shiftv req . iov . next n ; req . off <- req . off + n ; let r = Uring . writev ~ file_offset : req . fileoff uring req . t . infd req . iov . next req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued write read : % a " pp_req req ) ; | n when n = bytes_to_write -> req . t . writes <- req . t . writes - 1 ; req . t . write_left <- req . t . write_left - req . len ; Logs . debug ( fun l -> l " write done : % a " pp_req req ) | n -> raise ( Failure ( Printf . sprintf " unexpected writev result % d > % d " bytes_to_write n ) )
let handle_completion uring req res = match req . op with ` | R -> handle_read_completion uring req res ` | W -> handle_write_completion uring req res
let copy_file uring t = while t . write_left > 0 || t . read_left > 0 do let rec submit_reads ( ) = if t . read_left > 0 then begin if t . reads + t . writes < ( Uring . queue_depth uring ) then begin let size = min t . block_size t . read_left in queue_read uring t size ; submit_reads ( ) end end ; in submit_reads ( ) ; let num = Uring . submit uring in Logs . debug ( fun l -> l " % a : % d " Fmt . ( styled ` Yellow string ) " submit " num ) ; let got_completion = ref false in let rec handle_completions ( ) = if t . write_left > 0 then begin let check_q = if ! got_completion then Uring . peek uring else Uring . wait uring in match check_q with | None -> Logs . debug ( fun l -> l " completions : retry so finishing loop " ) | Some { data ; result } -> handle_completion uring data result ; got_completion := true ; handle_completions ( ) ; end in handle_completions ( ) ; let num = Uring . submit uring in Logs . debug ( fun l -> l " % a : % d " Fmt . ( styled ` Yellow string ) " submit " num ) ; done
let run_cp block_size queue_depth infile outfile ( ) = let infd = Unix . ( handle_unix_error ( openfile infile [ O_RDONLY ] ) 0 ) in let outfd = Unix . ( handle_unix_error ( openfile outfile [ O_WRONLY ; O_CREAT ; O_TRUNC ] ) 0o644 ) in let insize = get_file_size infd in let t = { block_size ; insize ; offset = Int63 . zero ; reads = 0 ; writes = 0 ; write_left = insize ; read_left = insize ; infd ; outfd } in Logs . debug ( fun l -> l " starting : % a bs =% d qd =% d " pp t block_size queue_depth ) ; let uring = Uring . create ~ queue_depth ( ) in copy_file uring t ; Unix . close infd ; Unix . close outfd ; Uring . exit uring ; Gc . compact ( )
type regexp = [ ` Alt of regexp * regexp | ` Seq of regexp * regexp | ` Rep of regexp | ` Repn of regexp * int * int option | ` After of regexp | ` Before of regexp | ` Epsilon | ` Group of regexp | ` OneChar | ` String of UChar . t list | ` Set of USet . t | ` BoS | ` EoS ]
type match_semantics = [ ` First | ` Shortest | ` Longest ]
let rec no_group = function ` Alt ( r1 , r2 ) r2 -> ` Alt ( no_group r1 , no_group r2 ) r2 | ` Seq ( r1 , r2 ) r2 -> ` Alt ( no_group r1 , no_group r2 ) r2 | ` Rep r -> ` Rep ( no_group r ) r | ` Group r -> r | r -> r
module type Type = sig type text type index type compiled_regexp module SubText : SubText . Type with type ur_text = text and type ur_index = index val compile : regexp -> compiled_regexp val regexp_match : ? sem : match_semantics -> compiled_regexp -> text -> index -> SubText . t option array option val string_match : compiled_regexp -> text -> index -> bool val search_forward : ? sem : match_semantics -> compiled_regexp -> text -> index -> SubText . t option array option end
module Make ( Text : UnicodeString . Type ) Type = struct type text = Text . t type index = Text . index module SubText = SubText . Make ( Text ) Text type instr = String of UChar . t list | OneChar | Set of USet . t | Par of instr * instr | Seq of instr * instr | Rep of instr | Repn of instr * int * int option | Epsilon | Group of int * instr | BoS | EoS | Before of instr | After of instr | Group_end of int * Text . index type compiled_regexp = int * instr let compile ( r : regexp ) regexp = let rec loop n = function ` Alt ( r1 , r2 ) r2 -> let n , r1 = loop n r1 in let n , r2 = loop n r2 in n , Par ( r1 , r2 ) r2 | ` Seq ( r1 , r2 ) r2 -> let n , r1 = loop n r1 in let n , r2 = loop n r2 in n , Seq ( r1 , r2 ) r2 | ` Rep r -> let n , r = loop n r in n , Rep r | ` Repn ( r , n , m ) m -> let n , r = loop n r in n , Repn ( r , n , m ) m | ` Group r -> let n ' , r = loop ( n + 1 ) 1 r in n ' , Group ( n , r ) r | ` Epsilon -> n , Epsilon | ` String s -> n , String s | ` OneChar -> n , OneChar | ` Set s -> n , Set s | ` BoS -> n , BoS | ` EoS -> n , EoS | ` After r -> let n , r = loop n r in n , After r | ` Before r -> let n , r = loop n r in n , Before r in loop 1 r let rec string_match t i = function [ ] -> i | u :: rest -> if Text . out_of_range t i then raise Exit else if UChar . eq ( Text . look t i ) i u then string_match t ( Text . next t i ) i rest else raise Exit let reverse_string_match t i us = let us = List . rev us in let rec loop i = function [ ] -> i | u :: rest -> if Text . out_of_range t i then raise Exit else if UChar . eq ( Text . look t i ) i u then loop ( Text . prev t i ) i rest else raise Exit in loop i us let dec_opt = function None -> None | Some m -> Some ( m - 1 ) 1 let rec exec_first groups t i = function | [ ] -> i , groups | Seq ( r1 , r2 ) r2 :: rest -> exec_first groups t i ( r1 :: r2 :: rest ) rest | Rep r :: rest as rs -> ( try exec_first groups t i rest with Exit -> exec_first groups t i ( r :: rs ) rs ) rs | Repn ( r , n , m ) m :: rest -> if n > 0 then exec_first groups t i ( r :: Repn ( r , n - 1 , dec_opt m ) m :: rest ) rest else ( match m with None -> exec_first groups t i ( Rep r :: rest ) rest | Some m -> if m <= 0 then exec_first groups t i rest else let s = Repn ( r , 0 , Some ( m - 1 ) 1 ) 1 in try exec_first groups t i rest with Exit -> exec_first groups t i ( r :: s :: rest ) rest ) rest | Par ( r1 , r2 ) r2 :: rest -> ( try exec_first groups t i ( r1 :: rest ) rest with Exit -> exec_first groups t i ( r2 :: rest ) rest ) rest | Group ( n , r ) r :: rest -> exec_first groups t i ( r :: Group_end ( n , i ) i :: rest ) rest | Group_end ( n , i0 ) i0 :: rest -> let s = SubText . refer t i0 i in exec_first ( ( n , s ) s :: groups ) groups t i rest | String t0 :: rest -> exec_first groups t ( string_match t i t0 ) t0 rest | OneChar :: rest -> if Text . out_of_range t i then raise Exit else exec_first groups t ( Text . next t i ) i rest | Set s :: rest -> ( if Text . out_of_range t i then raise Exit else match USet . mem ( Text . look t i ) i s with true -> exec_first groups t ( Text . next t i ) i rest | false -> raise Exit ) Exit | Epsilon :: rest -> exec_first groups t i rest | BoS :: rest -> if Text . compare_index t i ( Text . nth t 0 ) 0 > 0 then raise Exit else exec_first groups t i rest | EoS :: rest -> if Text . compare_index t i ( Text . last t ) t <= 0 then raise Exit else exec_first groups t i rest | After r :: rest -> let _ , groups = reverse groups t i [ r ] r in exec_first groups t i rest | Before r :: rest -> let _ , groups = exec_first groups t i [ r ] r in exec_first groups t i rest and reverse g t i = function | [ ] -> i , g | Seq ( r1 , r2 ) r2 :: rest -> reverse g t i ( r2 :: r1 :: rest ) rest | Rep r :: rest as rs -> ( try reverse g t i rest with Exit -> reverse g t i ( r :: rs ) rs ) rs | Repn ( r , n , m ) m :: rest -> if n > 0 then reverse g t i ( r :: Repn ( r , n - 1 , dec_opt m ) m :: rest ) rest else ( match m with None -> reverse g t i ( Rep r :: rest ) rest | Some m -> if m <= 0 then reverse g t i rest else let s = Repn ( r , 0 , Some ( m - 1 ) 1 ) 1 in try reverse g t i rest with Exit -> reverse g t i ( r :: s :: rest ) rest ) rest | Par ( r1 , r2 ) r2 :: rest -> ( try reverse g t i ( r1 :: rest ) rest with Exit -> reverse g t i ( r2 :: rest ) rest ) rest | Group ( n , r ) r :: rest -> reverse g t i ( r :: Group_end ( n , i ) i :: rest ) rest | Group_end ( n , j ) j :: rest -> let s = SubText . refer t i j in reverse ( ( n , s ) s :: g ) g t i rest | String t0 :: rest -> reverse g t ( reverse_string_match t i t0 ) t0 rest | OneChar :: rest -> if Text . out_of_range t i then raise Exit else reverse g t ( Text . prev t i ) i rest | Set s :: rest -> ( if Text . out_of_range t i then raise Exit else match USet . mem ( Text . look t i ) i s with true -> reverse g t ( Text . prev t i ) i rest | false -> raise Exit ) Exit | Epsilon :: rest -> reverse g t i rest | BoS :: rest -> if Text . compare_index t i ( Text . nth t 0 ) 0 > 0 then raise Exit else reverse g t i rest | EoS :: rest -> if Text . compare_index t i ( Text . last t ) t <= 0 then raise Exit else reverse g t i rest | After r :: rest -> let _ , g = reverse g t i [ r ] r in reverse g t i rest | Before r :: rest -> let _ , g = exec_first g t i [ r ] r in reverse g t i rest let rec exec_longest groups t i = function | [ ] -> i , groups | Seq ( r1 , r2 ) r2 :: rest -> exec_longest groups t i ( r1 :: r2 :: rest ) rest | Rep r :: rest as rs -> ( try let i1 , g1 = exec_longest groups t i rest in try let i2 , g2 = exec_longest groups t i ( r :: rs ) rs in if Text . compare_index t i1 i2 >= 0 then i1 , g1 else i2 , g2 with Exit -> i1 , g1 with Exit -> exec_longest groups t i ( r :: rs ) rs ) rs | Repn ( r , n , m ) m :: rest -> if n > 0 then exec_longest groups t i ( r :: Repn ( r , n - 1 , dec_opt m ) m :: rest ) rest else ( match m with None -> exec_longest groups t i ( Rep r :: rest ) rest | Some m -> if m <= 0 then exec_longest groups t i rest else let s = Repn ( r , 0 , Some ( m - 1 ) 1 ) 1 in try let i1 , g1 = exec_longest groups t i rest in try let i2 , g2 = exec_longest groups t i ( r :: s :: rest ) rest in if Text . compare_index t i1 i2 >= 0 then i1 , g1 else i2 , g2 with Exit -> i1 , g1 with Exit -> exec_longest groups t i ( r :: s :: rest ) rest ) rest | Par ( r1 , r2 ) r2 :: rest -> ( try exec_longest groups t i ( r1 :: rest ) rest with Exit -> exec_longest groups t i ( r2 :: rest ) rest ) rest | Group ( n , r ) r :: rest -> exec_longest groups t i ( r :: Group_end ( n , i ) i :: rest ) rest | Group_end ( n , i0 ) i0 :: rest -> let s = SubText . refer t i0 i in exec_longest ( ( n , s ) s :: groups ) groups t i rest | String t0 :: rest -> exec_longest groups t ( string_match t i t0 ) t0 rest | OneChar :: rest -> if Text . out_of_range t i then raise Exit else exec_longest groups t ( Text . next t i ) i rest | Set s :: rest -> ( if Text . out_of_range t i then raise Exit else match USet . mem ( Text . look t i ) i s with true -> exec_longest groups t ( Text . next t i ) i rest | false -> raise Exit ) Exit | Epsilon :: rest -> exec_longest groups t i rest | BoS :: rest -> if Text . compare_index t i ( Text . nth t 0 ) 0 > 0 then raise Exit else exec_longest groups t i rest | EoS :: rest -> if Text . compare_index t i ( Text . last t ) t <= 0 then raise Exit else exec_longest groups t i rest | After r :: rest -> let _ , g = reverse groups t i [ r ] r in exec_longest g t i rest | Before r :: rest -> let _ , g = exec_first groups t i [ r ] r in exec_longest g t i rest let rec exec_shortest groups t i = function | [ ] -> i , groups | Seq ( r1 , r2 ) r2 :: rest -> exec_shortest groups t i ( r1 :: r2 :: rest ) rest | Rep r :: rest as rs -> ( try let i1 , g1 = exec_shortest groups t i rest in try let i2 , g2 = exec_shortest groups t i ( r :: rs ) rs in if Text . compare_index t i1 i2 <= 0 then i1 , g1 else i2 , g2 with Exit -> i1 , g1 with Exit -> exec_shortest groups t i ( r :: rs ) rs ) rs | Repn ( r , n , m ) m :: rest -> if n > 0 then exec_shortest groups t i ( r :: Repn ( r , n - 1 , dec_opt m ) m :: rest ) rest else ( match m with None -> exec_shortest groups t i ( Rep r :: rest ) rest | Some m -> if m <= 0 then exec_shortest groups t i rest else let s = Repn ( r , 0 , Some ( m - 1 ) 1 ) 1 in try let i1 , g1 = exec_shortest groups t i rest in try let i2 , g2 = exec_shortest groups t i ( r :: s :: rest ) rest in if Text . compare_index t i1 i2 <= 0 then i1 , g1 else i2 , g2 with Exit -> i1 , g1 with Exit -> exec_shortest groups t i ( r :: s :: rest ) rest ) rest | Par ( r1 , r2 ) r2 :: rest -> ( try exec_shortest groups t i ( r1 :: rest ) rest with Exit -> exec_shortest groups t i ( r2 :: rest ) rest ) rest | Group ( n , r ) r :: rest -> exec_shortest groups t i ( r :: Group_end ( n , i ) i :: rest ) rest | Group_end ( n , i0 ) i0 :: rest -> let s = SubText . refer t i0 i in exec_shortest ( ( n , s ) s :: groups ) groups t i rest | String t0 :: rest -> exec_shortest groups t ( string_match t i t0 ) t0 rest | OneChar :: rest -> if Text . out_of_range t i then raise Exit else exec_shortest groups t ( Text . next t i ) i rest | Set s :: rest -> ( if Text . out_of_range t i then raise Exit else match USet . mem ( Text . look t i ) i s with true -> exec_shortest groups t ( Text . next t i ) i rest | false -> raise Exit ) Exit | Epsilon :: rest -> exec_shortest groups t i rest | BoS :: rest -> if Text . compare_index t i ( Text . nth t 0 ) 0 > 0 then raise Exit else exec_shortest groups t i rest | EoS :: rest -> if Text . compare_index t i ( Text . last t ) t <= 0 then raise Exit else exec_shortest groups t i rest | After r :: rest -> let _ , g = reverse groups t i [ r ] r in exec_shortest g t i rest | Before r :: rest -> let _ , g = exec_first groups t i [ r ] r in exec_shortest g t i rest let set_groups groups g = let rec loop = function [ ] -> ( ) | ( n , s ) s :: rest -> groups ( . n ) n <- Some s ; loop rest in loop ( List . rev g ) g let regexp_match ( ? sem ` = Longest ) Longest ( n , r ) r t i = let groups = Array . make n None in try match sem with ` First -> let j , g = exec_first [ ] t i [ r ] r in set_groups groups g ; groups ( . 0 ) 0 <- Some ( SubText . refer t i j ) j ; Some groups | ` Shortest -> let j , g = exec_shortest [ ] t i [ r ] r in set_groups groups g ; groups ( . 0 ) 0 <- Some ( SubText . refer t i j ) j ; Some groups | ` Longest -> let j , g = exec_longest [ ] t i [ r ] r in set_groups groups g ; groups ( . 0 ) 0 <- Some ( SubText . refer t i j ) j ; Some groups with Exit -> None let string_match ( _ , r ) r t i = try ignore ( exec_first [ ] t i [ r ] r ) r ; true with Exit -> false let search_forward ( ? sem ` = Longest ) Longest ( ( n , r ) r as c ) c t i = let groups = Array . make n None in let rec scan i = if Text . out_of_range t i then None else try let j , g = exec_first [ ] t i [ r ] r in Some ( i , j , g ) g with Exit -> scan ( Text . next t i ) i in match scan i with Some ( i , j , g ) g -> ( match sem with ` First -> set_groups groups g ; groups ( . 0 ) 0 <- Some ( SubText . refer t i j ) j ; Some groups | _ -> regexp_match ~ sem c t i ) i | None -> None end
module type Interface = sig type regexp = URe . regexp val regexp : string -> regexp val quote : string -> string val regexp_string : string -> regexp module type Type = sig type text type index type compiled_regexp module SubText : SubText . Type with type ur_text = text and type ur_index = index val compile : regexp -> compiled_regexp val regexp_match : ? sem : URe . match_semantics -> compiled_regexp -> text -> index -> SubText . t option array option val string_match : compiled_regexp -> text -> index -> bool val search_forward : ? sem : URe . match_semantics -> compiled_regexp -> text -> index -> SubText . t option array option end module Make ( Text : UnicodeString . Type ) Type : Type with type text = Text . t and type index = Text . index end
module Configure ( Config : ConfigInt . Type ) Type = struct type regexp = URe . regexp module Unidata = Unidata . Make ( MakeConfig ) MakeConfig module UCharInfo = UCharInfo . Make ( MakeConfig ) MakeConfig module type Type = URe . Type let property_to_set name = if name = " Any " then USet . compl ( USet . empty ) empty else try let cat = Unidata . cat_of_name name in let m = UCharInfo . load_general_category_map ( ) in UMap . map_to_set ( ( ) = cat ) cat m with Not_found -> try let script = Unidata . script_of_name name in let m = UCharInfo . load_script_map ( ) in UMap . map_to_set ( ( ) = script ) script m with Not_found -> UCharInfo . load_property_set_by_name name let regexp s = let lexbuf = Lexing . from_string s in let tree = UReStrParser . start UReStrLexer . token lexbuf in let rec g = function ` Set s -> s | ` Property name -> property_to_set name | ` Intr ( n1 , n2 ) n2 -> USet . inter ( g n1 ) n1 ( g n2 ) n2 | ` Union ( n1 , n2 ) n2 -> USet . union ( g n1 ) n1 ( g n2 ) n2 | ` Diff ( n1 , n2 ) n2 -> USet . diff ( g n1 ) n1 ( g n2 ) n2 | ` Compl n -> USet . compl ( g n ) n in let rec f = function ` Alt ( r1 , r2 ) r2 -> ` Alt ( f r1 , f r2 ) r2 | ` Seq ( r1 , r2 ) r2 -> ` Seq ( f r1 , f r2 ) r2 | ` Rep r -> ` Rep ( f r ) r | ` Repn ( r , n , m ) m -> ` Repn ( f r , n , m ) m | ` After r -> ` After ( f r ) r | ` Before r -> ` Before ( f r ) r | ` Group r -> ` Group ( f r ) r | ` SetNotation set_notation -> ` Set ( g set_notation ) set_notation | ` Set s -> ` Set s | ` String ulist -> ` String ulist | ( ` Epsilon | ` OneChar | ` BoS | ` EoS ) EoS as r -> r in f tree let quote s = let b = Buffer . create 8 in String . iter ( fun c -> match c with ' . ' -> Buffer . add_string b " . " \\ | ' * ' -> Buffer . add_string b " " \\* | ' + ' -> Buffer . add_string b " " \\+ | ' ? ' -> Buffer . add_string b " " \\? | ' [ ' ' -> Buffer . add_string b [ " " \\ | ' ] ' ' -> Buffer . add_string b ] " " \\ | ' ^ ' -> Buffer . add_string b " " \\^ | ' $ ' -> Buffer . add_string b " " \\$ | ' \\ ' -> Buffer . add_string b " " \\\\ | c -> Buffer . add_char b c ) c s ; Buffer . contents b let regexp_string s = let b = ref [ ] in UTF8 . iter ( fun u -> b := u :: ! b ) b s ; ` String ( List . rev ! b ) b module Make ( Text : UnicodeString . Type ) Type = URe . Make ( MakeText ) MakeText end
module URegexp = UReStr . Make ( UTF8 ) UTF8
let regexp_match_str r t i = let n = let p = Str . regexp_string ( " " \\ in let rec count i c = match try Some ( Str . search_forward p r i ) i with Not_found -> None with Some i -> count ( i + 1 ) 1 ( c + 1 ) 1 | None -> c in count i 0 in let g = Array . make ( n + 1 ) 1 None in if Str . string_match ( Str . regexp r ) r t i then let j = Str . match_end ( ) in g ( . 0 ) 0 <- Some ( URegexp . SubText . refer t i j ) j ; for i = 1 to n do g ( . i ) i <- try let j1 = Str . group_beginning i in let j2 = Str . group_end i in Some ( URegexp . SubText . refer t j1 j2 ) j2 with Not_found -> None done ; Some g else None
let string_of_sub s = let s0 = URegexp . SubText . excerpt s in let _ , i , _ = URegexp . SubText . context s in sprintf ( " % d , " \% s ) " " \ i s0
let string_of_subs g = let b = Buffer . create 0 in Buffer . add_string b [ " " ; | for i = 0 to Array . length g - 1 do Buffer . add_string b ( match g ( . i ) i with Some s -> string_of_sub s | None -> " ) " ; Buffer . add_string b " ; " done ; Buffer . add_string b ] " " ; | Buffer . contents b
let printer = function Some g -> string_of_subs g | None -> " No match "
let eq_match ( ? pos = 0 ) 0 r t = let r ' = UReStr . regexp r in expect_equal_app ~ msg ( : lazy t ) t ~ printer ( fun ( ) -> regexp_match_str r t pos ) pos ( ) ( fun ( ) -> URegexp . regexp_match ( URegexp . compile r ' ) r ' t pos ) pos ( )
let eq_matched_string ( ? pos = 0 ) 0 ( ? sem ` = Longest ) Longest r t t0 = let r = UReStr . regexp r in let g = URegexp . regexp_match ~ sem ( URegexp . compile r ) r t pos in match g with None -> fail ( " No match : " ^ t ) t | Some g -> match g ( . 0 ) 0 with None -> assert false | Some s -> let t = URegexp . SubText . excerpt s in expect_equal ~ msg ( : lazy t ) t ~ printer ( : fun x -> x ) x t0 t
let expect_pass desc body = test ~ desc ~ body ( : fun ( ) -> expect_pass ~ body ) body
let expect_match r t = let r = UReStr . regexp r in let r = URegexp . compile r in expect_true ~ msg ( : lazy t ) t ( URegexp . string_match r t 0 ) 0
let expect_not_match r t = let r = UReStr . regexp r in let r = URegexp . compile r in expect_true ~ msg ( : lazy t ) t ( not ( URegexp . string_match r t 0 ) 0 ) 0
let _ = expect_pass " literal " ( fun ( ) -> eq_match " a " " a " ; eq_match " a " " b " ; ) ; expect_pass " alt " ( fun ( ) -> eq_match " a \\| b " " a " ; eq_match " a \\| b " " b " ; eq_match " a \\| b " " c " ; ) ; expect_pass " seq " ( fun ( ) -> eq_match " ab " " ab " ; eq_match " ab " " ac " ; ) ; expect_pass " epsilon " ( fun ( ) -> eq_match " " " " ; eq_match " " " a " ; ) ; expect_pass " rep " ( fun ( ) -> eq_match " a " * " " ; eq_match " a " * " a " ; eq_match " a " * " aa " ; eq_match " a " * " b " ; ) ; expect_pass " rep1 " ( fun ( ) -> eq_match " a " + " a " ; eq_match " a " + " aa " ; eq_match " a " + " " ; eq_match " a " + " b " ; ) ; expect_pass " opt " ( fun ( ) -> eq_match " a " ? " " ; eq_match " a " ? " a " ; ) ; expect_pass " repn " ( fun ( ) -> eq_matched_string " a { \\ 3 } " \\ " aaa " " aaa " ; eq_matched_string " a { \\ 3 } , " \\ " aaaa " " aaaa " ; eq_matched_string " a { \\ 3 , 5 } " \\ " aaaaaaabb " " aaaaa " ; eq_matched_string " a { \\ 3 , 5 } " \\ " aaaaab " " aaaaa " ; ) ; expect_pass " bol " ( fun ( ) -> eq_match " ^ a " " ab " ; eq_match " ^ a " " b \ na " ; eq_match " ^ a " " ba " ; ) ; expect_pass " eol " ( fun ( ) -> eq_match " a " $ " ba " ; eq_match " a " $ " a \ nb " ; eq_match " a " $ " ba \ n " ; eq_match " a " $ " ab " ; ) ; expect_pass " bos " ( fun ( ) -> eq_match " ` \\ a " " ab " ; eq_match " ` \\ a " " b \ na " ; eq_match " ` \\ a " " ba " ; ) ; expect_pass " eos " ( fun ( ) -> eq_match " a \\ ' " " ba " ; eq_match " a \\ ' " " a \ nb " ; eq_match " a \\ ' " " ba \ n " ; eq_match " a \\ ' " " ab " ; ) ; expect_pass " match semantics " ( fun ( ) -> eq_match ( " \\ a \\| b ) \\* b " " aabaab " ; eq_matched_string ~ sem ` : Shortest ( " \\ a \\| b ) \\* b " " aabaab " " aab " ; eq_matched_string ~ sem ` : First ( " \\ a \\| b ) \\* b " " aabaab " " aab " ; eq_match " aa \\| aaa " " aaaa " ; eq_match " aaa \\| aa " " aaaa " ; ) ; expect_pass " group " ( fun ( ) -> eq_match ( " \\ a ) ( \\\\ a ) ( \\?\\ b ) " \\ " ab " ; ) ; expect_pass " rg " ( fun ( ) -> eq_match [ " 0 - 9 ] 9 " + " 0123456789 " ; eq_match [ " 0 - 9 ] 9 " + " a " ; eq_match [ " 0 - 9a - z ] z " + " a " ; ) ; expect_pass " compl " ( fun ( ) -> eq_match [ " ^ 0 - 9a - z ] z " + " 0 " ; eq_match [ " ^ 0 - 9a - z ] z " + " a " ; eq_match [ " ^ 0 - 9a - z ] z " + " A : Z " ; + ) ; expect_pass " pathological set " ( fun ( ) -> eq_match [ ] ] " " + ] ] ] ] ] " kk " ; eq_match [ ] " a ] a " + ] " a ] a ] aab " ; eq_match [ ] " " ^^+ " ^ abcd ^ ef " ; eq_match [ ] " " ^^+ " abcd ^ ef " ; eq_match [ " a - z ] " - " abcd - efgh " ; eq_match [ ] ] " " -^- ] ] ] [ [ [ " " ---^^^ ) ; expect_pass " escape " ( fun ( ) -> eq_matched_string [ " \\ u0000 - u \\ 00ff ] 00ff " + " abcdef漢字 " " abcdef " ) ; expect_pass " non ascii " ( fun ( ) -> eq_match " 夕供御 " " 夕供御まゐるをり " ; eq_matched_string [ " あ - ん ] ん " + " ひらがなAAAA " " ひらがな " ; expect_match [ { " . . . . . Zs } Zs ] Zs [ { . . . . . . . + Zs } Zs ] Zs . . . . . " + " ふるいけや かわずとびこむ みずのおと " ) ; expect_pass " property " ( fun ( ) -> eq_matched_string [ { " Lu } Lu ] Lu " + " AAAAAaaaaa " " AAAAA " ; eq_matched_string [ { " Uppercase } Uppercase ] Uppercase " + " AAAAA漢字 " " AAAAA " ; eq_matched_string [ { " Hiragana } Hiragana ] Hiragana " + " ひらがな漢字 " " ひらがな " ; eq_matched_string [ { " Any } Any ] Any " + " AAAAA漢字 " " AAAAA漢字 " ) ; expect_pass " set notation " ( fun ( ) -> eq_matched_string [ { [ " 0 - 9 ] 9 } 9 ] 9 " + " 12345AAAA " " 12345 " ; eq_matched_string [ { [ " 0 - 9 ] 9 & [ 0 - 5 ] 5 } 5 ] 5 " + " 123456789AAAA " " 12345 " ; eq_matched_string [ { [ " 0 - 9 ] 9 : [ 0 - 5 ] 5 } 5 ] 5 " + " 123456789AAAA " " 12345 " ; eq_matched_string [ { [ " 0 - 9 ] 9 | [ A - Z ] Z } Z ] Z " + " 12345AAAA漢字 " " 12345AAAA " ; eq_matched_string [ { [ " A - Z ] Z - [ A - C ] C } C ] C " + " DDDDCBA " " DDDD " ; eq_matched_string [ { [ " A - Zz ] Zz - [ A - C ] C | [ e - z ] z & [ a - k ] k } k ] k " + " DkzAa " " Dkz " ; ) ; let phone = [ { " . + Zs } Zs ] Zs [ Zs0 - 90 - 9 ] 9 { \\ 2 , 3 } [ { \\ Zs } Zs ] Zs " + ^ ( ( ) [ " \\\\|(\\ 0 - 90 - 9 ] 9 { \\ 3 , 4 } ( ) ) [ { \\\\\\|)\\ Zs } Zs ] Zs ( *\\-\\| ー ) [ { \\ Zs } Zs ] Zs " * ^ [ " 0 - 90 - 9 ] 9 { \\ 4 } " \\$ in expect_pass " phonebook " ( fun ( ) -> expect_match phone " 遠藤周作 03 ( 3744 ) 3744 - 7633 " ; expect_match phone " 遠藤周作 03 ( 3744 ) ー7633 " ; expect_match phone " 宮崎 駿 076 ( 943 ) 943 - 2264 " ; expect_not_match phone " 03 ( 3744 ) 3744 - 7633 遠藤周作 " ; expect_not_match phone " 遠藤周作0 ( 3744 ) 3744 - 7633 " ; expect_not_match phone " ジブリ美術館 03 ( 3744 ) 3744 " ; - ) ; let contain r t = let r = URegexp . compile ( UReStr . regexp r ) r in match URegexp . search_forward ~ sem ` : First r t 0 with Some _ -> true | None -> false in let expect_contain r t = expect_true ~ msg ( : lazy r ) r ( contain r t ) t in let expect_not_contain r t = expect_true ~ msg ( : lazy r ) r ( not ( contain r t ) t ) t in let text = " くれ竹のひとよに春の立つ霞 、 けさしも待ちいで顔に花を折り 匂ひをあらそいてなみゐたれば 、 我もひとなみなみにさしいでたり 。 つぼみ紅梅にやあらむ七つに 、 紅のうちき 、 もよぎのうはぎ 、 赤色の唐衣などにしてやらん 。 梅からくさを浮き織りたる二つ 小袖に 、 からかきの梅をぬひて侍りしをぞ着たり " 。 in expect_pass " search " ( fun ( ) -> expect_contain " うはぎ " text ; expect_contain " 侍りし " text ; expect_contain [ { " Hiragana } Hiragana ] Hiragana { \\ 7 } , " \\ text ; expect_not_contain " 如法 " text ; expect_not_contain [ { " Ideographic } Ideographic ] Ideographic { \\ 3 } , " \\ text ; ) ; expect_pass " dot " ( fun ( ) -> expect_contain " Sr . " \\ " Sra . y Sr . Zapatero - 1 " ; expect_contain " Sr [ Sr ] . " " Sra . y Sr . Zapatero - 2 " ; expect_contain " Sr \\ u002e " " Sra . y Sr . Zapatero - 3 " ; ) ; expect_pass " tag " ( fun ( ) -> eq_matched_string " ^</? a " > " < a > abcdefg - 1 </ a " > " < a " ; > eq_matched_string " </? a " > " </ a >- 2 " " </ a " ; > eq_matched_string ( ) " ^<\\/?\\ a " > " < a > abcdefg - 3 </ a " > " < a " ; > eq_matched_string ( ) " ^<\\/\\? a " > " < a > abcdefg - 4 </ a " > " < a " ; > ) ;
type component = [ | ` Scheme | ` Authority | ` Userinfo | ` Host | ` Path | ` Query | ` Query_key | ` Query_value | ` Fragment | ` Generic | ` Custom of ( component * string * string ) ]
type pct_encoder = { scheme : component ; userinfo : component ; host : component ; path : component ; query_key : component ; query_value : component ; fragment : component ; }
let rec iter_concat fn sep buf = function | last [ ] :: -> fn buf last | el :: rest -> fn buf el ; Buffer . add_string buf sep ; iter_concat fn sep buf rest | [ ] -> ( )
let rev_interject e lst = let rec aux acc = function | [ ] -> acc | x :: xs -> aux ( x :: e :: acc ) xs in match lst with | [ ] -> [ ] | h :: t -> aux [ h ] t
let compare_opt c t t ' = match t , t ' with | None , None -> 0 | Some _ , None -> 1 | None , Some _ -> - 1 | Some a , Some b -> c a b
let rec compare_list f t t ' = match t , t ' with | [ ] , [ ] -> 0 | _ :: _ , [ ] -> 1 | [ ] , _ :: _ -> - 1 | x :: xs , y :: ys -> match f x y with 0 -> compare_list f xs ys | c -> c
type safe_chars = bool array
module type Scheme = sig val safe_chars_for_component : component -> safe_chars val normalize_host : string option -> string option val canonicalize_port : int option -> int option val canonicalize_path : string list -> string list end
module Generic : Scheme = struct let sub_delims a = let subd = " ' ( ) , ; " !$&*+= in for i = 0 to String . length subd - 1 do let c = Char . code subd . [ i ] in a . ( c ) <- true done ; a let safe_chars : safe_chars = let a = Array . make 256 false in let always_safe = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_ . " -~ in for i = 0 to String . length always_safe - 1 do let c = Char . code always_safe . [ i ] in a . ( c ) <- true done ; a let pchar : safe_chars = let a = sub_delims ( Array . copy safe_chars ) in a . ( Char . code ' ' ) : <- true ; a . ( Char . code ' ' ) @ <- true ; a let safe_chars_for_scheme : safe_chars = let a = Array . copy safe_chars in a . ( Char . code ' ' ) + <- true ; a let safe_chars_for_path : safe_chars = let a = sub_delims ( Array . copy pchar ) in a . ( Char . code ' ' ) / <- false ; a let safe_chars_for_query : safe_chars = let a = Array . copy pchar in a . ( Char . code ' ' ) / <- true ; a . ( Char . code ' ' ) ? <- true ; a . ( Char . code ' ' ) & <- false ; a . ( Char . code ' ; ' ) <- false ; a . ( Char . code ' ' ) + <- false ; a let safe_chars_for_query_key : safe_chars = let a = Array . copy safe_chars_for_query in a . ( Char . code ' ' ) = <- false ; a let safe_chars_for_query_value : safe_chars = let a = Array . copy safe_chars_for_query in a . ( Char . code ' , ' ) <- false ; a let safe_chars_for_fragment : safe_chars = safe_chars_for_query let safe_chars_for_userinfo : safe_chars = let a = Array . copy safe_chars in a . ( Char . code ' ' ) : <- false ; a let rec safe_chars_for_component = function | ` Path -> safe_chars_for_path | ` Userinfo -> safe_chars_for_userinfo | ` Query -> safe_chars_for_query | ` Query_key -> safe_chars_for_query_key | ` Query_value -> safe_chars_for_query_value | ` Fragment -> safe_chars_for_fragment | ` Scheme -> safe_chars_for_scheme | ` Custom ( ( component : component ) , safe , unsafe ) -> let safe_chars = Array . copy ( safe_chars_for_component component ) in for i = 0 to String . length safe - 1 do let c = Char . code safe . [ i ] in safe_chars . ( c ) <- true done ; for i = 0 to String . length unsafe - 1 do let c = Char . code unsafe . [ i ] in safe_chars . ( c ) <- false done ; safe_chars | ` Generic | _ -> safe_chars let normalize_host hso = hso let canonicalize_port port = port let canonicalize_path path = path end
module Http : Scheme = struct include Generic let normalize_host = function | Some hs -> Some ( String . lowercase_ascii hs ) | None -> None let canonicalize_port = function | None -> None | Some 80 -> None | Some x -> Some x let canonicalize_path = function | [ ] -> [ " " ] / | x -> x end
module Https : Scheme = struct include Http let canonicalize_port = function | None -> None | Some 443 -> None | Some x -> Some x end
module File : Scheme = struct include Generic let normalize_host = function | Some hs -> let hs = String . lowercase_ascii hs in if hs " = localhost " then Some " " else Some hs | None -> None end
module Urn : Scheme = struct include Generic end
let module_of_scheme = function | Some s -> begin match String . lowercase_ascii s with | " http " -> ( module Http : Scheme ) | " https " -> ( module Https : Scheme ) | " file " -> ( module File : Scheme ) | " urn " -> ( module Urn : Scheme ) | _ -> ( module Generic : Scheme ) end | None -> ( module Generic : Scheme )
module Pct : sig type encoded type decoded val encode : ? scheme : string -> ? component : component -> decoded -> encoded val decode : encoded -> decoded val empty_decoded : decoded val cast_encoded : string -> encoded val cast_decoded : string -> decoded val uncast_encoded : encoded -> string val uncast_decoded : decoded -> string val lift_encoded : ( encoded -> encoded ) -> string -> string val lift_decoded : ( decoded -> decoded ) -> string -> string val unlift_encoded : ( string -> string ) -> encoded -> encoded val unlift_decoded : ( string -> string ) -> decoded -> decoded val unlift_decoded2 : ( string -> string -> ' a ) -> decoded -> decoded -> ' a type encoded = string type decoded = string let cast_encoded x = x let cast_decoded x = x let empty_decoded = " " let uncast_decoded x = x let uncast_encoded x = x let lift_encoded f = f let lift_decoded f = f let unlift_encoded f = f let unlift_decoded f = f let unlift_decoded2 f = f let encode ? scheme ( ? component ` = Path ) b = let module Scheme = ( val ( module_of_scheme scheme ) : Scheme ) in let safe_chars = Scheme . safe_chars_for_component component in let len = String . length b in let buf = Buffer . create len in let rec scan start cur = if cur >= len then begin Buffer . add_substring buf b start ( cur - start ) ; end else begin let c = Char . code b . [ cur ] in if safe_chars . ( c ) then scan start ( cur + 1 ) else begin if cur > start then Buffer . add_substring buf b start ( cur - start ) ; Buffer . add_string buf ( Printf . sprintf " %%% 02X " c ) ; scan ( cur + 1 ) ( cur + 1 ) end end in scan 0 0 ; Buffer . contents buf let int_of_hex_char c = let c = int_of_char ( Char . uppercase_ascii c ) - 48 in if c > 9 then if c > 16 && c < 23 then c - 7 else failwith " int_of_hex_char " else if c >= 0 then c else failwith " int_of_hex_char " let decode b = let len = String . length b in let buf = Buffer . create len in let rec scan start cur = if cur >= len then Buffer . add_substring buf b start ( cur - start ) else if b . [ cur ] = ' ' % then begin Buffer . add_substring buf b start ( cur - start ) ; let cur = cur + 1 in if cur >= len then Buffer . add_char buf ' ' % else match int_of_hex_char b . [ cur ] with | exception _ -> Buffer . add_char buf ' ' ; % scan cur cur | highbits -> begin let cur = cur + 1 in if cur >= len then begin Buffer . add_char buf ' ' ; % Buffer . add_char buf b . [ cur - 1 ] end else begin let start_at = match int_of_hex_char b . [ cur ] with | lowbits -> Buffer . add_char buf ( Char . chr ( highbits lsl 4 + lowbits ) ) ; cur + 1 | exception _ -> Buffer . add_char buf ' ' ; % Buffer . add_char buf b . [ cur - 1 ] ; cur in scan start_at start_at end end end else scan start ( cur + 1 ) in scan 0 0 ; Buffer . contents buf end
let pct_encode ? scheme ( ? component ` = Path ) s = Pct . ( uncast_encoded ( encode ? scheme ~ component ( cast_decoded s ) ) )
let pct_encoder ( ? scheme ` = Scheme ) ( ? userinfo ` = Userinfo ) ( ? host ` = Host ) ( ? path ` = Path ) ( ? query_key ` = Query_key ) ( ? query_value ` = Query_value ) ( ? fragment ` = Fragment ) ( ) = { scheme ; userinfo ; host ; path ; query_key ; query_value ; fragment }
let pct_decode s = Pct . ( uncast_decoded ( decode ( cast_encoded s ) ) )
module Userinfo = struct type t = string * string option let compare ( u , p ) ( u ' , p ' ) = match String . compare u u ' with | 0 -> compare_opt String . compare p p ' | c -> c let userinfo_of_encoded us = match Stringext . split ~ max : 2 ~ on ' ' :: us with | [ ] -> ( " " , None ) | [ u ] -> ( pct_decode u , None ) | u :: p :: _ -> ( pct_decode u , Some ( pct_decode p ) ) let encoded_of_userinfo ? scheme ~ component ( u , po ) = let len = String . ( 1 + ( length u ) + ( match po with None -> 0 | Some p -> length p ) ) in let buf = Buffer . create len in Buffer . add_string buf ( pct_encode ? scheme ~ component u ) ; begin match po with None -> ( ) ; | Some p -> Buffer . add_char buf ' ' ; : Buffer . add_string buf ( pct_encode ? scheme ~ component p ) end ; Pct . cast_encoded ( Buffer . contents buf ) end
let encoded_of_userinfo ? scheme ~ component = Userinfo . encoded_of_userinfo ? scheme ~ component
module Path = struct type t = string list let compare = compare_list String . compare let path_of_encoded ps = let tokl = Stringext . full_split ps ~ on ' ' :/ in List . map pct_decode tokl let remove_dot_segments p = let revp = List . rev p in let rec loop ascension outp = function | " " " . . " /:::: r | " . . " :: r -> loop ( ascension + 1 ) outp r | " " " . " /:::: r | " . " :: r -> loop ascension outp r | " " [ ] /:: | [ ] when List . ( length p > 0 && hd p = " " ) / -> " " /:: outp | [ ] when ascension > 0 -> List . rev_append ( " " ( /:: rev_interject " " / Array . ( to_list ( make ascension " . . " ) ) ) ) outp | [ ] -> List . ( if length outp > 0 && hd outp = " " / then tl outp else outp ) | " " " " /::/:: r when ascension > 0 -> loop ( ascension - 1 ) outp ( " " /:: r ) | " " /:: _ :: r when ascension > 0 -> loop ( ascension - 1 ) outp r | s :: r -> loop 0 ( s :: outp ) r in loop 0 [ ] revp let encoded_of_path ? scheme ~ component p = let len = List . fold_left ( fun c tok -> String . length tok + c ) 0 p in let buf = Buffer . create len in iter_concat ( fun buf -> function | " " / -> Buffer . add_char buf ' ' / | seg -> Buffer . add_string buf ( pct_encode ? scheme ~ component seg ) ) " " buf p ; Pct . cast_encoded ( Buffer . contents buf ) let merge bhost bpath relpath = match bhost , List . rev bpath with | Some _ , [ ] -> " " /:: relpath | _ , ( " " /:: rbpath | _ " " ::/:: rbpath ) -> List . rev_append ( " " /:: rbpath ) relpath | _ , _ -> relpath end
let encoded_of_path ? scheme ~ component = Path . encoded_of_path ? scheme ~ component
module Query = struct type kv = ( string * string list ) list type t = | KV of kv | Raw of string option * kv Lazy . t let compare x y = match x , y with | KV kvl , KV kvl ' | Raw ( _ , lazy kvl ) , KV kvl ' | KV kvl , Raw ( _ , lazy kvl ' ) -> compare_list ( fun ( k , vl ) ( k ' , vl ' ) -> match String . compare k k ' with | 0 -> compare_list String . compare vl vl ' | c -> c ) kvl kvl ' | Raw ( raw , _ ) , Raw ( raw ' , _ ) -> compare_opt String . compare raw raw ' let find q k = try Some ( List . assoc k q ) with Not_found -> None let split_query qs = let els = Stringext . split ~ on ' ' :& qs in let plus_to_space s = let s = Bytes . unsafe_of_string s in for i = 0 to Bytes . length s - 1 do if Bytes . get s i = ' ' + then Bytes . set s i ' ' done ; Bytes . unsafe_to_string s in let rec loop acc = function | ( k :: v :: _ ) :: tl -> let n = plus_to_space k , ( match Stringext . split ~ on ' , ' : ( plus_to_space v ) with | [ ] -> [ " " ] | l -> l ) in loop ( n :: acc ) tl | [ k ] :: tl -> let n = plus_to_space k , [ ] in loop ( n :: acc ) tl | [ ] :: tl -> loop ( ( " " , [ ] ) :: acc ) tl | [ ] -> acc in match els with | [ ] -> [ " " , [ ] ] | els -> loop [ ] ( List . rev_map ( fun el -> Stringext . split ~ on ' ' := el ~ max : 2 ) els ) let query_of_encoded qs = List . map ( fun ( k , v ) -> ( pct_decode k , List . map pct_decode v ) ) ( split_query qs ) let encoded_of_query ? scheme ( ? pct_encoder = pct_encoder ( ) ) l = let len = List . fold_left ( fun a ( k , v ) -> a + ( String . length k ) + ( List . fold_left ( fun a s -> a ( + String . length s ) + 1 ) 0 v ) + 2 ) ( - 1 ) l in let buf = Buffer . create len in iter_concat ( fun buf ( k , v ) -> Buffer . add_string buf ( pct_encode ? scheme ~ component : pct_encoder . query_key k ) ; if v <> [ ] then ( Buffer . add_char buf ' ' ; = iter_concat ( fun buf s -> Buffer . add_string buf ( pct_encode ? scheme ~ component : pct_encoder . query_value s ) ) " , " buf v ) ) " " & buf l ; Buffer . contents buf let of_raw qs = let lazy_query = Lazy . from_fun ( fun ( ) -> query_of_encoded qs ) in Raw ( Some qs , lazy_query ) let kv = function Raw ( _ , lazy kv ) | KV kv -> kv end
let encoded_of_query ? scheme = Query . encoded_of_query ? scheme
type t = { scheme : Pct . decoded option ; userinfo : Userinfo . t option ; host : Pct . decoded option ; port : int option ; path : Path . t ; query : Query . t ; fragment : Pct . decoded option ; }
let empty = { scheme = None ; userinfo = None ; host = None ; port = None ; path = [ ] ; query = Query . Raw ( None , Lazy . from_val [ ] ) ; fragment = None ; }
let compare_decoded = Pct . unlift_decoded2 String . compare
let compare_decoded_opt = compare_opt compare_decoded
let compare t t ' = ( match compare_decoded_opt t . host t ' . host with | 0 -> ( match compare_decoded_opt t . scheme t ' . scheme with | 0 -> ( match compare_opt ( fun p p ' -> if p < p ' then - 1 else if p > p ' then 1 else 0 ) t . port t ' . port with | 0 -> ( match compare_opt Userinfo . compare t . userinfo t ' . userinfo with | 0 -> ( match Path . compare t . path t ' . path with | 0 -> ( match Query . compare t . query t ' . query with | 0 -> compare_decoded_opt t . fragment t ' . fragment | c -> c ) | c -> c ) | c -> c ) | c -> c ) | c -> c ) | c -> c )
let equal t t ' = compare t t ' = 0