text
stringlengths
0
601k
let d2 d1 = critical_section ( fun ( ) -> let r = wait_until ( at 3 ) in assert ( r = Timeout ) ) ; check_after 3 ; notify d1 ; assert ( Atomic . get flag ) ; check_before 4
let ( ) = let d1 = spawn d1 in let d2 = spawn ( fun ( ) -> d2 ( get_id d1 ) ) in join d1 ; join d2 ; print_endline " ok "
type source_provenance = | File of file | Pack of string | Startup | Toplevel
type compiler_pass = | All | Parsing of file | Preprocessing of file | Typing of file | Transl of file | Generate of file | Assemble of source_provenance | Clambda of source_provenance | Cmm of source_provenance | Compile_phrases of source_provenance | Selection of source_provenance | Comballoc of source_provenance | CSE of source_provenance | Liveness of source_provenance | Deadcode of source_provenance | Spill of source_provenance | Split of source_provenance | Regalloc of source_provenance | Linearize of source_provenance | Scheduling of source_provenance | Emit of source_provenance | Flambda_pass of string * source_provenance
let timings : ( compiler_pass , float * float option ) Hashtbl . t = Hashtbl . create 20
let reset ( ) = Hashtbl . clear timings
let start pass = let time = Sys . time ( ) in Hashtbl . add timings pass ( time , None )
let stop pass = assert ( Hashtbl . mem timings pass ) ; let time = Sys . time ( ) in let ( start , stop ) = Hashtbl . find timings pass in assert ( stop = None ) ; Hashtbl . replace timings pass ( start , Some ( time . - start ) )
let time pass f x = start pass ; let r = f x in stop pass ; r
let restart pass = let previous_duration = match Hashtbl . find timings pass with | exception Not_found -> 0 . | ( _ , Some duration ) -> duration | _ , None -> assert false in let time = Sys . time ( ) in Hashtbl . replace timings pass ( time , Some previous_duration )
let accumulate pass = let time = Sys . time ( ) in match Hashtbl . find timings pass with | exception Not_found -> assert false | _ , None -> assert false | ( start , Some duration ) -> let duration = duration . + ( time . - start ) in Hashtbl . replace timings pass ( start , Some duration )
let accumulate_time pass f x = restart pass ; let r = f x in accumulate pass ; r
let get pass = match Hashtbl . find timings pass with | _start , Some duration -> Some duration | _ , None -> None | exception Not_found -> None
let kind_name = function | File f -> Printf . sprintf " sourcefile ( % s ) " f | Pack p -> Printf . sprintf " pack ( % s ) " p | Startup -> " startup " | Toplevel -> " toplevel "
let pass_name = function | All -> " all " | Parsing file -> Printf . sprintf " parsing ( % s ) " file | Preprocessing file -> Printf . sprintf " preprocessing ( % s ) " file | Typing file -> Printf . sprintf " typing ( % s ) " file | Transl file -> Printf . sprintf " transl ( % s ) " file | Generate file -> Printf . sprintf " generate ( % s ) " file | Assemble k -> Printf . sprintf " assemble ( % s ) " ( kind_name k ) | Clambda k -> Printf . sprintf " clambda ( % s ) " ( kind_name k ) | Cmm k -> Printf . sprintf " cmm ( % s ) " ( kind_name k ) | Compile_phrases k -> Printf . sprintf " compile_phrases ( % s ) " ( kind_name k ) | Selection k -> Printf . sprintf " selection ( % s ) " ( kind_name k ) | Comballoc k -> Printf . sprintf " comballoc ( % s ) " ( kind_name k ) | CSE k -> Printf . sprintf " cse ( % s ) " ( kind_name k ) | Liveness k -> Printf . sprintf " liveness ( % s ) " ( kind_name k ) | Deadcode k -> Printf . sprintf " deadcode ( % s ) " ( kind_name k ) | Spill k -> Printf . sprintf " spill ( % s ) " ( kind_name k ) | Split k -> Printf . sprintf " split ( % s ) " ( kind_name k ) | Regalloc k -> Printf . sprintf " regalloc ( % s ) " ( kind_name k ) | Linearize k -> Printf . sprintf " linearize ( % s ) " ( kind_name k ) | Scheduling k -> Printf . sprintf " scheduling ( % s ) " ( kind_name k ) | Emit k -> Printf . sprintf " emit ( % s ) " ( kind_name k ) | Flambda_pass ( pass , file ) -> Printf . sprintf " flambda ( % s ) ( % s ) " pass ( kind_name file )
let timings_list ( ) = let l = Hashtbl . fold ( fun pass times l -> ( pass , times ) :: l ) timings [ ] in List . sort ( fun ( _ , ( start1 , _ ) ) ( _ , ( start2 , _ ) ) -> compare start1 start2 ) l
let print ppf = let current_time = Sys . time ( ) in List . iter ( fun ( pass , ( start , stop ) ) -> match stop with | Some duration -> Format . fprintf ppf " % s : . % 03fs . " @ ( pass_name pass ) duration | None -> Format . fprintf ppf " % s : running since . % 03fs . " @ ( pass_name pass ) ( current_time . - start ) ) ( timings_list ( ) )
let sexp_of_t_style : [ ` Pretty | ` Internal ] ref = ref ` Pretty
module Num_key_bits : sig type t = private int [ @@ deriving compare , sexp ] include Comparable with type t := t include Invariant . S with type t := t val zero : t val max_value : t val to_int : t -> int val of_int : int -> t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val pow2 : t -> Int63 . t include Int let min_value = 0 let max_value = Int63 . num_bits - 1 let invariant t = assert ( t >= min_value ) ; assert ( t <= max_value ) ; ; let of_int i = invariant i ; i ; ; let ( + ) t1 t2 = let t = t1 + t2 in invariant t ; t ; ; let ( - ) t1 t2 = let t = t1 - t2 in invariant t ; t ; ; let pow2 t = Int63 . shift_left Int63 . one t end
module Level_bits = struct type t = Num_key_bits . t list [ @@ deriving compare , sexp ] let max_num_bits = ( Num_key_bits . max_value :> int ) let num_bits_internal t = List . fold t ~ init : Num_key_bits . zero ~ f : Num_key_bits . ( + ) let num_bits t = ( num_bits_internal t :> int ) let invariant t = assert ( not ( List . is_empty t ) ) ; List . iter t ~ f ( : fun num_key_bits -> Num_key_bits . invariant num_key_bits ; assert ( Num_key_bits . ( > ) num_key_bits Num_key_bits . zero ) ) ; Num_key_bits . invariant ( num_bits_internal t ) ; ; let t_of_sexp sexp = let t = sexp |> [ % of_sexp : t ] in invariant t ; t ; ; let create_exn ( ? extend_to_max_num_bits = false ) ints = if List . is_empty ints then failwith " Level_bits . create_exn requires a nonempty list " ; if List . exists ints ~ f ( : fun bits -> bits <= 0 ) then raise_s [ % message " Level_bits . create_exn got nonpositive num bits " ~ _ ( : ints : int list ) ] ; let num_bits = List . fold ints ~ init : 0 ~ f ( : + ) in if num_bits > max_num_bits then raise_s [ % message " Level_bits . create_exn got too many bits " ~ _ ( : ints : int list ) ~ got ( : num_bits : int ) ( max_num_bits : int ) ] ; let ints = if extend_to_max_num_bits then ints @ List . init ( max_num_bits - num_bits ) ~ f ( : const 1 ) else ints in List . map ints ~ f : Num_key_bits . of_int ; ; let default = create_exn [ 11 ; 10 ; 10 ; 10 ; 10 ; 10 ; 1 ] let trim t ~ max_num_bits = if Num_key_bits . ( <= ) ( num_bits_internal t ) max_num_bits then t else ( let rec loop t ~ remaining = match t with | [ ] -> [ ] | b :: t -> if Num_key_bits . ( >= ) b remaining then [ remaining ] else b :: loop t ~ remaining ( : Num_key_bits . ( - ) remaining b ) in loop t ~ remaining : max_num_bits ) ; ; end
module Alarm_precision : sig include Alarm_precision val num_key_bits : t -> Num_key_bits . t val interval_num : t -> Time_ns . t -> Int63 . t val interval_num_start : t -> Int63 . t -> Time_ns . t type t = int [ @@ deriving compare , hash ] let equal = [ % compare . equal : t ] let num_key_bits t = t |> Num_key_bits . of_int let to_span t = if t < 0 then raise_s [ % message " [ Alarm_precision . to_span ] of negative power of two nanoseconds " ~ _ ( : t : int ) ] ; Int63 . ( shift_left one ) t |> Time_ns . Span . of_int63_ns ; ; let sexp_of_t t = [ % sexp ( t |> to_span : Time_ns . Span . t ) ] let one_nanosecond = 0 let about_one_microsecond = 10 let about_one_millisecond = 20 let about_one_second = 30 let about_one_day = 46 let mul t ~ pow2 = t + pow2 let div t ~ pow2 = t - pow2 let interval_num t time = Int63 . shift_right ( time |> Time_ns . to_int63_ns_since_epoch ) t let interval_num_start t interval_num = Int63 . shift_left interval_num t |> Time_ns . of_int63_ns_since_epoch ; ; let of_span_floor_pow2_ns span = if Time_ns . Span . ( <= ) span Time_ns . Span . zero then raise_s [ % message " [ Alarm_precision . of_span_floor_pow2_ns ] got non - positive span " ( span : Time_ns . Span . t ) ] ; span |> Time_ns . Span . to_int63_ns |> Int63 . floor_log2 ; ; let of_span = of_span_floor_pow2_ns module Unstable = struct module T = struct type nonrec t = t [ @@ deriving compare ] let of_binable = of_span_floor_pow2_ns let to_binable = to_span let of_sexpable = of_span_floor_pow2_ns let to_sexpable = to_span end include T include Binable . Of_binable_without_uuid [ @ alert " - legacy " ] ( Time_ns . Span ) ( T ) include Sexpable . Of_sexpable ( Time_ns . Span ) ( T ) end end
module Config = struct let level_bits_default = Level_bits . default type t = { alarm_precision : Alarm_precision . Unstable . t ; level_bits : Level_bits . t [ @ default level_bits_default ] ; capacity : int option [ @ sexp . option ] } [ @@ deriving fields , sexp ] let alarm_precision t = Alarm_precision . to_span t . alarm_precision let max_num_level_bits alarm_precision = Num_key_bits . ( - ) Num_key_bits . max_value ( Alarm_precision . num_key_bits alarm_precision ) ; ; let invariant t = Invariant . invariant [ % here ] t [ % sexp_of : t ] ( fun ( ) -> assert ( Num_key_bits . ( <= ) ( Level_bits . num_bits_internal t . level_bits ) ( max_num_level_bits t . alarm_precision ) ) ; let check f = Invariant . check_field t f in Fields . iter ~ alarm_precision : ignore ~ capacity : ignore ~ level_bits ( : check Level_bits . invariant ) ) ; ; let create ? capacity ( ? level_bits = level_bits_default ) ~ alarm_precision ( ) = let level_bits = Level_bits . trim level_bits ~ max_num_bits ( : max_num_level_bits alarm_precision ) in { alarm_precision ; level_bits ; capacity } ; ; let microsecond_precision ( ) = create ( ) ~ alarm_precision : Alarm_precision . about_one_microsecond ~ level_bits ( : Level_bits . create_exn [ 10 ; 10 ; 6 ; 6 ; 5 ] ) ; ; let durations t = List . folding_map t . level_bits ~ init ( : Alarm_precision . num_key_bits t . alarm_precision |> Num_key_bits . to_int ) ~ f ( : fun num_bits_accum level_num_bits -> let num_bits_accum = num_bits_accum + ( level_num_bits |> Num_key_bits . to_int ) in let duration = Time_ns . Span . of_int63_ns ( if num_bits_accum = Int63 . num_bits - 1 then Int63 . max_value else Int63 . shift_left Int63 . one num_bits_accum ) in num_bits_accum , duration ) ; ; end
module Priority_queue : sig type ' a t [ @@ deriving sexp_of ] type ' a priority_queue = ' a t module Key : Interval_num module Elt : sig type ' a t [ @@ deriving sexp_of ] val at : ' a priority_queue -> ' a t -> Time_ns . t val key : ' a priority_queue -> ' a t -> Key . t val value : ' a priority_queue -> ' a t -> ' a val null : unit -> ' a t end module Internal_elt : sig module Pool : sig type ' a t end type ' a t val key : ' a Pool . t -> ' a t -> Key . t val max_alarm_time : ' a Pool . t -> ' a t -> with_key : Key . t -> Time_ns . t val is_null : _ t -> bool val to_external : ' a t -> ' a Elt . t end val pool : ' a t -> ' a Internal_elt . Pool . t include Invariant . S1 with type ' a t := ' a t val create : ? capacity : int -> ? level_bits : Level_bits . t -> unit -> ' a t val length : _ t -> int val min_allowed_key : _ t -> Key . t val max_allowed_key : _ t -> Key . t val min_elt_ : ' a t -> ' a Internal_elt . t val internal_add : ' a t -> key : Key . t -> at : Time_ns . t -> ' a -> ' a Internal_elt . t val remove : ' a t -> ' a Elt . t -> unit val change : ' a t -> ' a Elt . t -> key : Key . t -> at : Time_ns . t -> unit val clear : _ t -> unit val mem : ' a t -> ' a Elt . t -> bool val increase_min_allowed_key : ' a t -> key : Key . t -> handle_removed ( ' : a Elt . t -> unit ) -> unit val iter : ' a t -> f ( ' : a Elt . t -> unit ) -> unit val fire_past_alarms : ' a t -> handle_fired ( ' : a Elt . t -> unit ) -> key : Key . t -> now : Time_ns . t -> unit module Pool = Pool . Unsafe module Pointer = Pool . Pointer module Key : sig include Timing_wheel_intf . Interval_num val add_clamp_to_max : t -> Span . t -> t val succ_clamp_to_max : t -> t module Slots_mask : sig type t = private Int63 . t [ @@ deriving compare , sexp_of ] val create : level_bits : Num_key_bits . t -> t val next_slot : t -> int -> int end module Min_key_in_same_slot_mask : sig type t = private Int63 . t [ @@ deriving compare , sexp_of ] include Equal . S with type t := t val create : bits_per_slot : Num_key_bits . t -> t end val num_keys : Num_key_bits . t -> Span . t val min_key_in_same_slot : t -> Min_key_in_same_slot_mask . t -> t val slot : t -> bits_per_slot : Num_key_bits . t -> slots_mask : Slots_mask . t -> int end = struct module Slots_mask = struct type t = Int63 . t [ @@ deriving compare , sexp_of ] let create ~ level_bits = Int63 . ( - ) ( Num_key_bits . pow2 level_bits ) Int63 . one let next_slot t slot = ( slot + 1 ) land Int63 . to_int_exn t end let num_keys num_bits = Num_key_bits . pow2 num_bits module Min_key_in_same_slot_mask = struct include Int63 let create ~ bits_per_slot = bit_not ( Num_key_bits . pow2 bits_per_slot - one ) end module Span = struct include Int63 let to_int63 t = t let of_int63 i = i let scale_int t i = t * of_int i end include Int63 let of_int63 i = i let to_int63 t = t let add t i = t + i let add_clamp_to_max t i = if t > max_value - i then max_value else t + i let succ_clamp_to_max t = if t = max_value then max_value else succ t let sub t i = t - i let diff t1 t2 = t1 - t2 let slot t ( ~ bits_per_slot : Num_key_bits . t ) ~ slots_mask = to_int_exn ( bit_and ( shift_right t ( bits_per_slot :> int ) ) slots_mask ) ; ; let min_key_in_same_slot t min_key_in_same_slot_mask = bit_and t min_key_in_same_slot_mask ; ; end module Min_key_in_same_slot_mask = Key . Min_key_in_same_slot_mask module Slots_mask = Key . Slots_mask module External_elt = struct type ' a pool_slots = ( Key . t , Time_ns . t , ' a , int , ' a pool_slots Pointer . t , ' a pool_slots Pointer . t ) Pool . Slots . t6 [ @@ deriving sexp_of ] type ' a t = ' a pool_slots Pointer . t [ @@ deriving sexp_of ] let null = Pointer . null end module Internal_elt : sig module Pool : sig type ' a t [ @@ deriving sexp_of ] include Invariant . S1 with type ' a t := ' a t val create : ? capacity : int -> unit -> _ t val is_full : _ t -> bool val grow : ? capacity : int -> ' a t -> ' a t end type ' a t = private ' a External_elt . t [ @@ deriving sexp_of ] val null : unit -> _ t val is_null : _ t -> bool val is_valid : ' a Pool . t -> ' a t -> bool val external_is_valid : ' a Pool . t -> ' a External_elt . t -> bool val to_external : ' a t -> ' a External_elt . t val of_external_exn : ' a Pool . t -> ' a External_elt . t -> ' a t val equal : ' a t -> ' a t -> bool val invariant : ' a Pool . t -> ( ' a -> unit ) -> ' a t -> unit val create : ' a Pool . t -> key : Key . t -> at : Time_ns . t -> value ' : a -> level_index : int -> ' a t val free : ' a Pool . t -> ' a t -> unit val key : ' a Pool . t -> ' a t -> Key . t val at : ' a Pool . t -> ' a t -> Time_ns . t val level_index : ' a Pool . t -> ' a t -> int val next : ' a Pool . t -> ' a t -> ' a t val value : ' a Pool . t -> ' a t -> ' a val set_key : ' a Pool . t -> ' a t -> Key . t -> unit val set_at : ' a Pool . t -> ' a t -> Time_ns . t -> unit val set_level_index : ' a Pool . t -> ' a t -> int -> unit val insert_at_end : ' a Pool . t -> ' a t -> to_add ' : a t -> unit val link_to_self : ' a Pool . t -> ' a t -> unit val unlink : ' a Pool . t -> ' a t -> unit val iter : ' a Pool . t -> ' a t -> f ( ' : a t -> unit ) -> unit val length : ' a Pool . t -> ' a t -> int val max_alarm_time : ' a Pool . t -> ' a t -> with_key : Key . t -> Time_ns . t end = struct type ' a pool_slots = ' a External_elt . pool_slots [ @@ deriving sexp_of ] type ' a t = ' a External_elt . t [ @@ deriving sexp_of ] let null = Pointer . null let is_null = Pointer . is_null let equal t1 t2 = Pointer . phys_equal t1 t2 let create pool ~ key ~ at ~ value ~ level_index = Pool . new6 pool key at value level_index ( null ( ) ) ( null ( ) ) ; ; let free = Pool . free let key p t = Pool . get p t Pool . Slot . t0 let set_key p t k = Pool . set p t Pool . Slot . t0 k let at p t = Pool . get p t Pool . Slot . t1 let set_at p t x = Pool . set p t Pool . Slot . t1 x let value p t = Pool . get p t Pool . Slot . t2 let level_index p t = Pool . get p t Pool . Slot . t3 let set_level_index p t i = Pool . set p t Pool . Slot . t3 i let prev p t = Pool . get p t Pool . Slot . t4 let set_prev p t x = Pool . set p t Pool . Slot . t4 x let next p t = Pool . get p t Pool . Slot . t5 let set_next p t x = Pool . set p t Pool . Slot . t5 x let is_valid p t = Pool . pointer_is_valid p t let external_is_valid = is_valid let invariant pool invariant_a t = Invariant . invariant [ % here ] t [ % sexp_of : _ t ] ( fun ( ) -> assert ( is_valid pool t ) ; invariant_a ( value pool t ) ; let n = next pool t in assert ( is_null n || Pointer . phys_equal t ( prev pool n ) ) ; let p = prev pool t in assert ( is_null p || Pointer . phys_equal t ( next pool p ) ) ) ; ; module Pool = struct type ' a t = ' a pool_slots Pool . t [ @@ deriving sexp_of ] let invariant _invariant_a t = Pool . invariant ignore t let create ( ? capacity = 1 ) ( ) = Pool . create Pool . Slots . t6 ~ capacity let grow = Pool . grow let is_full = Pool . is_full end let to_external t = t let of_external_exn pool t = if is_valid pool t then t else raise_s [ % message " Timing_wheel got invalid alarm " ] ; ; let unlink pool t = set_next pool ( prev pool t ) ( next pool t ) ; set_prev pool ( next pool t ) ( prev pool t ) ; ; let link pool prev next = set_next pool prev next ; set_prev pool next prev ; ; let link_to_self pool t = link pool t t let insert_at_end pool t ~ to_add = let prev = prev pool t in link pool prev to_add ; link pool to_add t ; ; let iter pool first ~ f = let current = ref first in let continue = ref true in while ! continue do let next = next pool ! current in f ! current ; if phys_equal next first then continue := false else current := next done ; ; let length pool first = let r = ref 0 in let current = ref first in let continue = ref true in while ! continue do incr r ; let next = next pool ! current in if phys_equal next first then continue := false else current := next done ; ! r ; ; let max_alarm_time pool first ~ with_key = let max_alarm_time = ref Time_ns . epoch in let current = ref first in let continue = ref true in while ! continue do let next = next pool ! current in if Key . equal ( key pool ! current ) with_key then max_alarm_time := Time_ns . max ( at pool ! current ) ! max_alarm_time ; if phys_equal next first then continue := false else current := next done ; ! max_alarm_time ; ; end module Level = struct type ' a t = { index : int ; bits : Num_key_bits . t ; slots_mask : Slots_mask . t ; bits_per_slot : Num_key_bits . t ; keys_per_slot : Key . Span . t ; min_key_in_same_slot_mask : Min_key_in_same_slot_mask . t ; diff_max_min_allowed_key : Key . Span . t ; mutable length : int ; mutable min_allowed_key : Key . t ; mutable max_allowed_key : Key . t ; slots : ( ' a Internal_elt . t array [ @ sexp . opaque ] ) } [ @@ deriving fields , sexp_of ] let slot t ~ key = Key . slot key ~ bits_per_slot : t . bits_per_slot ~ slots_mask : t . slots_mask ; ; let next_slot t slot = Slots_mask . next_slot t . slots_mask slot let min_key_in_same_slot t ~ key = Key . min_key_in_same_slot key t . min_key_in_same_slot_mask ; ; let compute_min_allowed_key t ~ prev_level_max_allowed_key = if Key . equal prev_level_max_allowed_key Key . max_value then Key . max_value else min_key_in_same_slot t ~ key ( : Key . succ prev_level_max_allowed_key ) ; ; end type ' a t = { mutable length : int ; mutable pool : ' a Internal_elt . Pool . t ; mutable min_elt : ' a Internal_elt . t ; mutable elt_key_lower_bound : Key . t ; levels : ' a Level . t array } [ @@ deriving fields , sexp_of ] type ' a priority_queue = ' a t module Elt = struct type ' a t = ' a External_elt . t [ @@ deriving sexp_of ] let null = External_elt . null let at p t = Internal_elt . at p . pool ( Internal_elt . of_external_exn p . pool t ) let key p t = Internal_elt . key p . pool ( Internal_elt . of_external_exn p . pool t ) let value p t = Internal_elt . value p . pool ( Internal_elt . of_external_exn p . pool t ) end let sexp_of_t_internal = sexp_of_t let is_empty t = length t = 0 let num_levels t = Array . length t . levels let min_allowed_key t = Level . min_allowed_key t . levels . ( 0 ) let max_allowed_key t = Level . max_allowed_key t . levels . ( num_levels t - 1 ) let internal_iter t ~ f = if t . length > 0 then ( let pool = t . pool in let levels = t . levels in for level_index = 0 to Array . length levels - 1 do let level = levels . ( level_index ) in if level . length > 0 then ( let slots = level . slots in for slot_index = 0 to Array . length slots - 1 do let elt = slots . ( slot_index ) in if not ( Internal_elt . is_null elt ) then Internal_elt . iter pool elt ~ f done ) done ) ; ; let iter t ~ f = internal_iter t ~ f ( : f : _ Elt . t -> unit :> _ Internal_elt . t -> unit ) module Pretty = struct module Elt = struct type ' a t = { key : Key . t ; value : ' a } [ @@ deriving sexp_of ] end type ' a t = { min_allowed_key : Key . t ; max_allowed_key : Key . t ; elts : ' a Elt . t list } [ @@ deriving sexp_of ] end let pretty t = let pool = t . pool in { Pretty . min_allowed_key = min_allowed_key t ; max_allowed_key = max_allowed_key t ; elts = ( let r = ref [ ] in internal_iter t ~ f ( : fun elt -> r := { Pretty . Elt . key = Internal_elt . key pool elt ; value = Internal_elt . value pool elt } :: ! r ) ; List . rev ! r ) } ; ; let sexp_of_t sexp_of_a t = match ! sexp_of_t_style with | ` Internal -> [ % sexp ( t : a t_internal ) ] | ` Pretty -> [ % sexp ( pretty t : a Pretty . t ) ] ; ; let compute_diff_max_min_allowed_key ~ level_bits ~ bits_per_slot = let bits = Num_key_bits . ( + ) level_bits bits_per_slot in if Num_key_bits . equal bits Num_key_bits . max_value then Key . Span . max_value else Key . Span . pred ( Key . num_keys bits ) ; ; let invariant invariant_a t : unit = let pool = t . pool in let level_invariant level = Invariant . invariant [ % here ] level [ % sexp_of : _ Level . t ] ( fun ( ) -> let check f = Invariant . check_field level f in Level . Fields . iter ~ index ( : check ( fun index -> assert ( index >= 0 ) ) ) ~ bits : ( check ( fun bits -> assert ( Num_key_bits . ( > ) bits Num_key_bits . zero ) ) ) ~ slots_mask : ( check ( [ % test_result : Slots_mask . t ] ~ expect ( : Slots_mask . create ~ level_bits : level . bits ) ) ) ~ bits_per_slot : ( check ( fun bits_per_slot -> assert ( Num_key_bits . ( >= ) bits_per_slot Num_key_bits . zero ) ) ) ~ keys_per_slot : ( check ( fun keys_per_slot -> [ % test_result : Key . Span . t ] keys_per_slot ~ expect ( : Key . num_keys level . bits_per_slot ) ) ) ~ min_key_in_same_slot_mask : ( check ( fun min_key_in_same_slot_mask -> assert ( Min_key_in_same_slot_mask . equal min_key_in_same_slot_mask ( Min_key_in_same_slot_mask . create ~ bits_per_slot : level . bits_per_slot ) ) ) ) ~ diff_max_min_allowed_key : ( check ( [ % test_result : Key . Span . t ] ~ expect : ( compute_diff_max_min_allowed_key ~ level_bits : level . bits ~ bits_per_slot : level . bits_per_slot ) ) ) ~ length : ( check ( fun length -> assert ( length = Array . fold level . slots ~ init : 0 ~ f ( : fun n elt -> if Internal_elt . is_null elt then n else n + Internal_elt . length pool elt ) ) ) ) ~ min_allowed_key : ( check ( fun min_allowed_key -> assert ( Key . ( >= ) min_allowed_key Key . zero ) ; if Key . ( < ) min_allowed_key Key . max_value then [ % test_result : Key . Span . t ] ( Key . rem min_allowed_key level . keys_per_slot ) ~ expect : Key . Span . zero ) ) ~ max_allowed_key : ( check ( fun max_allowed_key -> [ % test_result : Key . t ] max_allowed_key ~ expect : ( Key . add_clamp_to_max level . min_allowed_key level . diff_max_min_allowed_key ) ) ) ~ slots : ( check ( fun slots -> Array . iter slots ~ f ( : fun elt -> if not ( Internal_elt . is_null elt ) then ( Internal_elt . invariant pool invariant_a elt ; Internal_elt . iter pool elt ~ f ( : fun elt -> assert ( Key . ( >= ) ( Internal_elt . key pool elt ) level . min_allowed_key ) ; assert ( Key . ( <= ) ( Internal_elt . key pool elt ) level . max_allowed_key ) ; assert ( Key . ( >= ) ( Internal_elt . key pool elt ) t . elt_key_lower_bound ) ; assert ( Internal_elt . level_index pool elt = level . index ) ; invariant_a ( Internal_elt . value pool elt ) ) ) ) ) ) ) in Invariant . invariant [ % here ] t [ % sexp_of : _ t_internal ] ( fun ( ) -> let check f = Invariant . check_field t f in assert ( Key . ( >= ) ( min_allowed_key t ) Key . zero ) ; assert ( Key . ( >= ) ( max_allowed_key t ) ( min_allowed_key t ) ) ; Fields . iter ~ length ( : check ( fun length -> assert ( length >= 0 ) ) ) ~ pool ( : check ( Internal_elt . Pool . invariant ignore ) ) ~ min_elt : ( check ( fun elt_ -> if not ( Internal_elt . is_null elt_ ) then ( assert ( Internal_elt . is_valid t . pool elt_ ) ; assert ( Key . equal t . elt_key_lower_bound ( Internal_elt . key t . pool elt_ ) ) ) ) ) ~ elt_key_lower_bound : ( check ( fun elt_key_lower_bound -> assert ( Key . ( >= ) elt_key_lower_bound ( min_allowed_key t ) ) ; assert ( Key . ( <= ) elt_key_lower_bound ( max_allowed_key t ) ) ; if not ( Internal_elt . is_null t . min_elt ) then assert ( Key . equal elt_key_lower_bound ( Internal_elt . key t . pool t . min_elt ) ) ) ) ~ levels : ( check ( fun levels -> assert ( num_levels t > 0 ) ; Array . iteri levels ~ f ( : fun level_index level -> assert ( level_index = Level . index level ) ; level_invariant level ; if level_index > 0 then ( let prev_level = levels . ( level_index - 1 ) in let module L = Level in [ % test_result : Key . Span . t ] ( L . keys_per_slot level ) ~ expect ( : Key . Span . succ prev_level . diff_max_min_allowed_key ) ; [ % test_result : Key . t ] level . min_allowed_key ~ expect : ( Level . compute_min_allowed_key level ~ prev_level_max_allowed_key : prev_level . max_allowed_key ) ) ) ) ) ) ; ; let min_elt_ t = if is_empty t then Internal_elt . null ( ) else if not ( Internal_elt . is_null t . min_elt ) then t . min_elt else ( let pool = t . pool in let min_elt_already_found = ref ( Internal_elt . null ( ) ) in let min_key_already_found = ref Key . max_value in let level_index = ref 0 in let num_levels = num_levels t in while ! level_index < num_levels do let level = t . levels . ( ! level_index ) in if Key . ( > ) ( Level . min_allowed_key level ) ! min_key_already_found then level_index := num_levels else if level . length = 0 then incr level_index else ( let slots = level . slots in let slot_min_key = ref ( Level . min_key_in_same_slot level ~ key ( : Key . max level . min_allowed_key t . elt_key_lower_bound ) ) in let slot = ref ( Level . slot level ~ key :! slot_min_key ) in while Internal_elt . is_null slots . ( ! slot ) && Key . ( < ) ! slot_min_key ! min_key_already_found do slot := Level . next_slot level ! slot ; slot_min_key := Key . add ! slot_min_key level . keys_per_slot done ; let first = slots . ( ! slot ) in if not ( Internal_elt . is_null first ) then ( let continue = ref true in let current = ref first in while ! continue do let current_key = Internal_elt . key pool ! current in if Key . ( <= ) current_key ! min_key_already_found then ( min_elt_already_found := ! current ; min_key_already_found := current_key ) ; let next = Internal_elt . next pool ! current in if phys_equal next first || ! level_index = 0 then continue := false else current := next done ) ; incr level_index ) done ; t . min_elt <- ! min_elt_already_found ; t . elt_key_lower_bound <- ! min_key_already_found ; t . min_elt ) ; ; let [ @ cold ] raise_add_elt_key_out_of_bounds t key = raise_s [ % message " Priority_queue . add_elt key out of bounds " ( key : Key . t ) ( min_allowed_key t : Key . t ) ( max_allowed_key t : Key . t ) ~ priority_queue ( : t : _ t ) ] ; ; let [ @ cold ] raise_add_elt_key_out_of_level_bounds key level = raise_s [ % message " Priority_queue . add_elt key out of level bounds " ( key : Key . t ) ( level : _ Level . t ) ] ; ; let add_elt t elt = let pool = t . pool in let key = Internal_elt . key pool elt in if not ( Key . ( >= ) key ( min_allowed_key t ) && Key . ( <= ) key ( max_allowed_key t ) ) then raise_add_elt_key_out_of_bounds t key ; let level_index = let level_index = ref 0 in while Key . ( > ) key ( Level . max_allowed_key t . levels . ( ! level_index ) ) do incr level_index done ; ! level_index in let level = t . levels . ( level_index ) in if not ( Key . ( >= ) key level . min_allowed_key && Key . ( <= ) key level . max_allowed_key ) then raise_add_elt_key_out_of_level_bounds key level ; level . length <- level . length + 1 ; Internal_elt . set_level_index pool elt level_index ; let slot = Level . slot level ~ key in let slots = level . slots in let first = slots . ( slot ) in if not ( Internal_elt . is_null first ) then Internal_elt . insert_at_end pool first ~ to_add : elt else ( slots . ( slot ) <- elt ; Internal_elt . link_to_self pool elt ) ; ; let internal_add_elt t elt = let key = Internal_elt . key t . pool elt in if Key . ( < ) key t . elt_key_lower_bound then ( t . min_elt <- elt ; t . elt_key_lower_bound <- key ) ; add_elt t elt ; t . length <- t . length + 1 ; ; let [ @ cold ] raise_got_invalid_key t key = raise_s [ % message " Timing_wheel . add_at_interval_num got invalid interval num " ~ interval_num ( : key : Key . t ) ~ min_allowed_alarm_interval_num ( : min_allowed_key t : Key . t ) ~ max_allowed_alarm_interval_num ( : max_allowed_key t : Key . t ) ] ; ; let ensure_valid_key t ~ key = if Key . ( < ) key ( min_allowed_key t ) || Key . ( > ) key ( max_allowed_key t ) then raise_got_invalid_key t key ; ; let internal_add t ~ key ~ at value = ensure_valid_key t ~ key ; if Internal_elt . Pool . is_full t . pool then t . pool <- Internal_elt . Pool . grow t . pool ; let elt = Internal_elt . create t . pool ~ key ~ at ~ value ~ level_index ( :- 1 ) in internal_add_elt t elt ; elt ; ; let remove_or_re_add_elts t ( level : _ Level . t ) first ~ t_min_allowed_key ~ handle_removed = let pool = t . pool in let current = ref first in let continue = ref true in while ! continue do let next = Internal_elt . next pool ! current in level . length <- level . length - 1 ; if Key . ( >= ) ( Internal_elt . key pool ! current ) t_min_allowed_key then add_elt t ! current else ( t . length <- t . length - 1 ; handle_removed ( Internal_elt . to_external ! current ) ; Internal_elt . free pool ! current ) ; if phys_equal next first then continue := false else current := next done ; ; let increase_level_min_allowed_key t ( level : _ Level . t ) ~ prev_level_max_allowed_key ~ t_min_allowed_key ~ handle_removed = let desired_min_allowed_key = Level . compute_min_allowed_key level ~ prev_level_max_allowed_key in let level_min_allowed_key = Level . min_key_in_same_slot level ~ key : ( Key . min desired_min_allowed_key ( Key . max level . min_allowed_key t . elt_key_lower_bound ) ) in let level_min_allowed_key = ref level_min_allowed_key in let slot = ref ( Level . slot level ~ key :! level_min_allowed_key ) in let keys_per_slot = level . keys_per_slot in let slots = level . slots in while Key . ( < ) ! level_min_allowed_key desired_min_allowed_key do if level . length = 0 then level_min_allowed_key := desired_min_allowed_key else ( let first = slots . ( ! slot ) in if not ( Internal_elt . is_null first ) then ( slots . ( ! slot ) <- Internal_elt . null ( ) ; remove_or_re_add_elts t level first ~ t_min_allowed_key ~ handle_removed ) ; slot := Level . next_slot level ! slot ; level_min_allowed_key := Key . add_clamp_to_max ! level_min_allowed_key keys_per_slot ) done ; level . min_allowed_key <- desired_min_allowed_key ; level . max_allowed_key <- Key . add_clamp_to_max desired_min_allowed_key level . diff_max_min_allowed_key ; ; let increase_min_allowed_key t ~ key ~ handle_removed = if Key . ( > ) key ( min_allowed_key t ) then ( let level_index = ref 0 in let prev_level_max_allowed_key = ref ( Key . pred key ) in let levels = t . levels in let num_levels = num_levels t in while ! level_index < num_levels do let level = levels . ( ! level_index ) in let min_allowed_key_before = level . min_allowed_key in increase_level_min_allowed_key t level ~ prev_level_max_allowed_key :! prev_level_max_allowed_key ~ t_min_allowed_key : key ~ handle_removed ; if Key . equal ( Level . min_allowed_key level ) min_allowed_key_before then level_index := num_levels else ( level_index := ! level_index + 1 ; prev_level_max_allowed_key := Level . max_allowed_key level ) done ; if Key . ( > ) key t . elt_key_lower_bound then ( t . min_elt <- Internal_elt . null ( ) ; t . elt_key_lower_bound <- min_allowed_key t ) ) ; ; let create ? capacity ? level_bits ( ) = let level_bits = match level_bits with | Some l -> l | None -> Level_bits . default in let _ , _ , levels = List . foldi level_bits ~ init ( : Num_key_bits . zero , Key . zero , [ ] ) ~ f ( : fun index ( bits_per_slot , max_level_min_allowed_key , levels ) ( level_bits : Num_key_bits . t ) -> let keys_per_slot = Key . num_keys bits_per_slot in let diff_max_min_allowed_key = compute_diff_max_min_allowed_key ~ level_bits ~ bits_per_slot in let min_key_in_same_slot_mask = Min_key_in_same_slot_mask . create ~ bits_per_slot in let min_allowed_key = Key . min_key_in_same_slot max_level_min_allowed_key min_key_in_same_slot_mask in let max_allowed_key = Key . add_clamp_to_max min_allowed_key diff_max_min_allowed_key in let level = { Level . index ; bits = level_bits ; slots_mask = Slots_mask . create ~ level_bits ; bits_per_slot ; keys_per_slot ; min_key_in_same_slot_mask ; diff_max_min_allowed_key ; length = 0 ; min_allowed_key ; max_allowed_key ; slots = Array . create ~ len ( : Int63 . to_int_exn ( Num_key_bits . pow2 level_bits ) ) ( Internal_elt . null ( ) ) } in ( Num_key_bits . ( + ) level_bits bits_per_slot , Key . succ_clamp_to_max max_allowed_key , level :: levels ) ) in { length = 0 ; pool = Internal_elt . Pool . create ? capacity ( ) ; min_elt = Internal_elt . null ( ) ; elt_key_lower_bound = Key . zero ; levels = Array . of_list_rev levels } ; ; let mem t elt = Internal_elt . external_is_valid t . pool elt let internal_remove t elt = let pool = t . pool in if Internal_elt . equal elt t . min_elt then t . min_elt <- Internal_elt . null ( ) ; t . length <- t . length - 1 ; let level = t . levels . ( Internal_elt . level_index pool elt ) in level . length <- level . length - 1 ; let slots = level . slots in let slot = Level . slot level ~ key ( : Internal_elt . key pool elt ) in let first = slots . ( slot ) in if phys_equal elt ( Internal_elt . next pool elt ) then slots . ( slot ) <- Internal_elt . null ( ) else ( if phys_equal elt first then slots . ( slot ) <- Internal_elt . next pool elt ; Internal_elt . unlink pool elt ) ; ; let remove t elt = let pool = t . pool in let elt = Internal_elt . of_external_exn pool elt in internal_remove t elt ; Internal_elt . free pool elt ; ; let fire_past_alarms t ~ handle_fired ~ key ~ now = let level = t . levels . ( 0 ) in if level . length > 0 then ( let slot = Level . slot level ~ key in let slots = level . slots in let pool = t . pool in let first = ref slots . ( slot ) in if not ( Internal_elt . is_null ! first ) then ( let current = ref ! first in let continue = ref true in while ! continue do let elt = ! current in let next = Internal_elt . next pool elt in if phys_equal next ! first then continue := false else current := next ; if Time_ns . ( <= ) ( Internal_elt . at pool elt ) now then ( handle_fired ( Internal_elt . to_external elt ) ; internal_remove t elt ; Internal_elt . free pool elt ; first := slots . ( slot ) ) done ) ) ; ; let change t elt ~ key ~ at = ensure_valid_key t ~ key ; let pool = t . pool in let elt = Internal_elt . of_external_exn pool elt in internal_remove t elt ; Internal_elt . set_key pool elt key ; Internal_elt . set_at pool elt at ; internal_add_elt t elt ; ; let clear t = if not ( is_empty t ) then ( t . length <- 0 ; let pool = t . pool in let free_elt elt = Internal_elt . free pool elt in let levels = t . levels in for level_index = 0 to Array . length levels - 1 do let level = levels . ( level_index ) in if level . length > 0 then ( level . length <- 0 ; let slots = level . slots in for slot_index = 0 to Array . length slots - 1 do let elt = slots . ( slot_index ) in if not ( Internal_elt . is_null elt ) then ( Internal_elt . iter pool elt ~ f : free_elt ; slots . ( slot_index ) <- Internal_elt . null ( ) ) done ) done ) ; ; end
type ' a t = { config : Config . t ; start : Time_ns . t ; max_interval_num : Interval_num . t ; mutable now : Time_ns . t ; mutable now_interval_num_start : Time_ns . t ; mutable max_allowed_alarm_time : Time_ns . t ; priority_queue : ' a Priority_queue . t }
type ' a timing_wheel = ' a t
type ' a t_now = ' a t
let sexp_of_t_now _ t = [ % sexp ( t . now : Time_ns . t ) ]
let alarm_precision t = Config . alarm_precision t . config
module Alarm = struct type ' a t = ' a Priority_queue . Elt . t [ @@ deriving sexp_of ] let null = Priority_queue . Elt . null let at tw t = Priority_queue . Elt . at tw . priority_queue t let value tw t = Priority_queue . Elt . value tw . priority_queue t let interval_num tw t = Priority_queue . Elt . key tw . priority_queue t end
let iter t ~ f = Priority_queue . iter t . priority_queue ~ f
module Pretty = struct module Alarm = struct type ' a t = { at : Time_ns . t ; value : ' a } [ @@ deriving fields , sexp_of ] let create t alarm = { at = Alarm . at t alarm ; value = Alarm . value t alarm } let compare t1 t2 = Time_ns . compare ( at t1 ) ( at t2 ) end type ' a t = { config : Config . t ; start : Time_ns . t ; max_interval_num : Interval_num . t ; now : Time_ns . t ; alarms : ' a Alarm . t list } [ @@ deriving sexp_of ] end
let pretty ( { config ; start ; max_interval_num ; now ; now_interval_num_start = _ ; max_allowed_alarm_time = _ ; priority_queue = _ } as t ) = let r = ref [ ] in iter t ~ f ( : fun a -> r := Pretty . Alarm . create t a :: ! r ) ; let alarms = List . sort ! r ~ compare : Pretty . Alarm . compare in { Pretty . config ; start ; max_interval_num ; now ; alarms } ; ;
let sexp_of_t sexp_of_a t = match ! sexp_of_t_style with | ` Internal -> sexp_of_t_internal sexp_of_a t | ` Pretty -> [ % sexp ( pretty t : a Pretty . t ) ] ; ;
let length t = Priority_queue . length t . priority_queue
let is_empty t = length t = 0
let interval_num_internal ~ time ~ alarm_precision = Interval_num . of_int63 ( Alarm_precision . interval_num alarm_precision time ) ; ;
let interval_num_unchecked t time = interval_num_internal ~ time ~ alarm_precision : t . config . alarm_precision ; ;
let interval_num t time = if Time_ns . ( < ) time min_time then raise_s [ % message " Timing_wheel . interval_num got time too far in the past " ( time : Time_ns . t ) ] ; interval_num_unchecked t time ; ;
let interval_num_start_unchecked t interval_num = Alarm_precision . interval_num_start t . config . alarm_precision ( interval_num |> Interval_num . to_int63 ) ; ; raise_s [ % message " Timing_wheel . interval_num_start got too small interval_num " ( interval_num : Interval_num . t ) ( min_interval_num : Interval_num . t ) ] ; ; raise_s [ % message " Timing_wheel . interval_num_start got too large interval_num " ( interval_num : Interval_num . t ) ( t . max_interval_num : Interval_num . t ) ] ; ;
let interval_num_start t interval_num = if Interval_num . ( < ) interval_num min_interval_num then raise_interval_num_start_got_too_small interval_num ; if Interval_num . ( > ) interval_num t . max_interval_num then raise_interval_num_start_got_too_large t interval_num ; interval_num_start_unchecked t interval_num ; ;
let compute_max_allowed_alarm_time t = let max_allowed_key = Priority_queue . max_allowed_key t . priority_queue in if Interval_num . ( >= ) max_allowed_key t . max_interval_num then max_time else Time_ns . add ( interval_num_start_unchecked t max_allowed_key ) ( Time_ns . Span . ( - ) ( alarm_precision t ) Time_ns . Span . nanosecond ) ; ;
let now_interval_num t = Priority_queue . min_allowed_key t . priority_queue
let max_allowed_alarm_interval_num t = interval_num t ( max_allowed_alarm_time t )
let interval_start t time = interval_num_start_unchecked t ( interval_num t time )
let invariant invariant_a t = Invariant . invariant [ % here ] t [ % sexp_of : _ t ] ( fun ( ) -> let check f = Invariant . check_field t f in Fields . iter ~ config ( : check Config . invariant ) ~ start : ( check ( fun start -> assert ( Time_ns . ( >= ) start min_time ) ; assert ( Time_ns . ( <= ) start max_time ) ) ) ~ max_interval_num : ( check ( fun max_interval_num -> [ % test_result : Interval_num . t ] ~ expect : max_interval_num ( interval_num t max_time ) ; [ % test_result : Interval_num . t ] ~ expect : max_interval_num ( interval_num t ( interval_num_start t max_interval_num ) ) ) ) ~ now : ( check ( fun now -> assert ( Time_ns . ( >= ) now t . start ) ; assert ( Time_ns . ( <= ) now max_time ) ; assert ( Interval_num . equal ( interval_num t t . now ) ( Priority_queue . min_allowed_key t . priority_queue ) ) ) ) ~ now_interval_num_start : ( check ( fun now_interval_num_start -> [ % test_result : Time_ns . t ] now_interval_num_start ~ expect ( : interval_num_start t ( now_interval_num t ) ) ) ) ~ max_allowed_alarm_time : ( check ( fun max_allowed_alarm_time -> [ % test_result : Time_ns . t ] max_allowed_alarm_time ~ expect ( : compute_max_allowed_alarm_time t ) ) ) ~ priority_queue ( : check ( Priority_queue . invariant invariant_a ) ) ; iter t ~ f ( : fun alarm -> assert ( Interval_num . equal ( Alarm . interval_num t alarm ) ( interval_num t ( Alarm . at t alarm ) ) ) ; assert ( Time_ns . ( >= ) ( interval_start t ( Alarm . at t alarm ) ) ( interval_start t ( now t ) ) ) ; assert ( Time_ns . ( > ) ( Alarm . at t alarm ) ( Time_ns . sub ( now t ) ( alarm_precision t ) ) ) ) ) ; ;
let advance_clock t ~ to_ ~ handle_fired = if Time_ns . ( > ) to_ ( now t ) then ( t . now <- to_ ; let key = interval_num_unchecked t to_ in t . now_interval_num_start <- interval_num_start_unchecked t key ; Priority_queue . increase_min_allowed_key t . priority_queue ~ key ~ handle_removed : handle_fired ; t . max_allowed_alarm_time <- compute_max_allowed_alarm_time t ) ; ;
let create ~ config ~ start = if Time_ns . ( < ) start Time_ns . epoch then raise_s [ % message " Timing_wheel . create got start before the epoch " ( start : Time_ns . t ) ] ; let t = { config ; start ; max_interval_num = interval_num_internal ~ time : max_time ~ alarm_precision : config . alarm_precision ; now = Time_ns . min_value_for_1us_rounding ; now_interval_num_start = Time_ns . min_value_for_1us_rounding ; max_allowed_alarm_time = max_time ; priority_queue = Priority_queue . create ? capacity : config . capacity ~ level_bits : config . level_bits ( ) } in advance_clock t ~ to_ : start ~ handle_fired ( : fun _ -> assert false ) ; t ; ;
let add_at_interval_num t ~ at value = Internal_elt . to_external ( Priority_queue . internal_add t . priority_queue ~ key : at ~ at ( : interval_num_start t at ) value ) ; ; raise_s [ % message " Timing_wheel cannot schedule alarm that far in the future " ( at : Time_ns . t ) ~ max_allowed_alarm_time ( : t . max_allowed_alarm_time : Time_ns . t ) ] ; ; raise_s [ % message " Timing_wheel cannot schedule alarm before start of current interval " ( at : Time_ns . t ) ~ now_interval_num_start ( : t . now_interval_num_start : Time_ns . t ) ] ; ;
let ensure_can_schedule_alarm t ~ at = if Time_ns . ( > ) at t . max_allowed_alarm_time then raise_that_far_in_the_future t at ; if Time_ns . ( < ) at t . now_interval_num_start then raise_before_start_of_current_interval t at ; ;
let add t ~ at value = ensure_can_schedule_alarm t ~ at ; Internal_elt . to_external ( Priority_queue . internal_add t . priority_queue ~ key ( : interval_num_unchecked t at ) ~ at value ) ; ;
let remove t alarm = Priority_queue . remove t . priority_queue alarm
let clear t = Priority_queue . clear t . priority_queue
let mem t alarm = Priority_queue . mem t . priority_queue alarm
let reschedule_gen t alarm ~ key ~ at = if not ( mem t alarm ) then failwith " Timing_wheel cannot reschedule alarm not in timing wheel " ; ensure_can_schedule_alarm t ~ at ; Priority_queue . change t . priority_queue alarm ~ key ~ at ; ;
let reschedule t alarm ~ at = reschedule_gen t alarm ~ key ( : interval_num_unchecked t at ) ~ at ; ;
let reschedule_at_interval_num t alarm ~ at = reschedule_gen t alarm ~ key : at ~ at ( : interval_num_start t at ) ; ;
let pool t = Priority_queue . pool t . priority_queue
let min_alarm_interval_num t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then None else Some ( Internal_elt . key ( pool t ) elt ) ; ;
let min_alarm_interval_num_exn t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then raise_s [ % message " Timing_wheel . min_alarm_interval_num_exn of empty timing_wheel " ~ timing_wheel ( : t : _ t ) ] else Internal_elt . key ( pool t ) elt ; ;
let max_alarm_time_in_list t elt = let pool = pool t in Internal_elt . max_alarm_time pool elt ~ with_key ( : Internal_elt . key pool elt ) ; ;
let max_alarm_time_in_min_interval t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then None else Some ( max_alarm_time_in_list t elt ) ; ;
let max_alarm_time_in_min_interval_exn t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then raise_s [ % message " Timing_wheel . max_alarm_time_in_min_interval_exn of empty timing wheel " ~ timing_wheel ( : t : _ t ) ] ; max_alarm_time_in_list t elt ; ;
let next_alarm_fires_at_internal t key = interval_num_start t ( Key . succ key ) ; ;
let next_alarm_fires_at t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then None else ( let key = Internal_elt . key ( pool t ) elt in if Interval_num . equal key t . max_interval_num then None else Some ( next_alarm_fires_at_internal t key ) ) ; ; raise_s [ % message " Timing_wheel . next_alarm_fires_at_exn of empty timing wheel " ~ timing_wheel ( : t : _ t ) ] ; ; raise_s [ % message " Timing_wheel . next_alarm_fires_at_exn with all alarms in max interval " ~ timing_wheel ( : t : _ t ) ] ; ;
let next_alarm_fires_at_exn t = let elt = Priority_queue . min_elt_ t . priority_queue in if Internal_elt . is_null elt then raise_next_alarm_fires_at_exn_of_empty_timing_wheel t ; let key = Internal_elt . key ( pool t ) elt in if Interval_num . equal key t . max_interval_num then raise_next_alarm_fires_at_with_all_alarms_in_max_interval t ; next_alarm_fires_at_internal t key ; ;
let fire_past_alarms t ~ handle_fired = Priority_queue . fire_past_alarms t . priority_queue ~ handle_fired ~ key ( : now_interval_num t ) ~ now : t . now ; ;
module Private = struct module Num_key_bits = Num_key_bits let interval_num_internal = interval_num_internal let max_time = max_time end
module type Interval_num = sig module Span : sig type t = private Int63 . t [ @@ deriving sexp_of ] include Comparable . S with type t := t val max : t -> t -> t val zero : t val one : t val max_value : t val of_int63 : Int63 . t -> t val to_int63 : t -> Int63 . t val of_int : int -> t val to_int_exn : t -> int val scale_int : t -> int -> t val pred : t -> t val succ : t -> t val ( + ) : t -> t -> t end type t = private Int63 . t [ @@ deriving sexp_of ] include Comparable . S with type t := t include Hashable . S with type t := t val max : t -> t -> t val min : t -> t -> t val zero : t val one : t val min_value : t val max_value : t val of_int63 : Int63 . t -> t val to_int63 : t -> Int63 . t val of_int : int -> t val to_int_exn : t -> int val add : t -> Span . t -> t val sub : t -> Span . t -> t val diff : t -> t -> Span . t val succ : t -> t val pred : t -> t val rem : t -> Span . t -> Span . t end
module type Alarm_precision = sig type t [ @@ deriving compare , sexp_of ] include Equal . S with type t := t val of_span : Time_ns . Span . t -> t [ @@ deprecated " [ since 2018 - 01 ] Use [ of_span_floor_pow2_ns ] " ] val of_span_floor_pow2_ns : Time_ns . Span . t -> t val to_span : t -> Time_ns . Span . t val one_nanosecond : t val about_one_day : t val about_one_microsecond : t val about_one_millisecond : t val about_one_second : t val mul : t -> pow2 : int -> t val div : t -> pow2 : int -> t module Unstable : sig type nonrec t = t [ @@ deriving bin_io , compare , sexp ] end end
module type Timing_wheel = sig module Alarm_precision : Alarm_precision type ' a t [ @@ deriving sexp_of ] type ' a timing_wheel = ' a t type ' a t_now = ' a t [ @@ deriving sexp_of ] module Interval_num : Interval_num module Alarm : sig type ' a t [ @@ deriving sexp_of ] val null : unit -> _ t val at : ' a timing_wheel -> ' a t -> Time_ns . t val interval_num : ' a timing_wheel -> ' a t -> Interval_num . t val value : ' a timing_wheel -> ' a t -> ' a end include Invariant . S1 with type ' a t := ' a t module Level_bits : sig type t [ @@ deriving sexp ] include Invariant . S with type t := t val max_num_bits : int val create_exn : ? extend_to_max_num_bits : bool -> int list -> t val default : t val num_bits : t -> int end module Config : sig type t [ @@ deriving sexp ] include Invariant . S with type t := t val create : ? capacity : int -> ? level_bits : Level_bits . t -> alarm_precision : Alarm_precision . t -> unit -> t val alarm_precision : t -> Time_ns . Span . t val level_bits : t -> Level_bits . t val durations : t -> Time_ns . Span . t list val microsecond_precision : unit -> t end val create : config : Config . t -> start : Time_ns . t -> ' a t val alarm_precision : _ t -> Time_ns . Span . t val now : _ t -> Time_ns . t val start : _ t -> Time_ns . t val is_empty : _ t -> bool val length : _ t -> int val iter : ' a t -> f ( ' : a Alarm . t -> unit ) -> unit val interval_num : _ t -> Time_ns . t -> Interval_num . t val now_interval_num : _ t -> Interval_num . t val interval_num_start : _ t -> Interval_num . t -> Time_ns . t val interval_start : _ t -> Time_ns . t -> Time_ns . t val advance_clock : ' a t -> to_ : Time_ns . t -> handle_fired ( ' : a Alarm . t -> unit ) -> unit val fire_past_alarms : ' a t -> handle_fired ( ' : a Alarm . t -> unit ) -> unit val max_allowed_alarm_time : _ t -> Time_ns . t val min_allowed_alarm_interval_num : _ t -> Interval_num . t val max_allowed_alarm_interval_num : _ t -> Interval_num . t val add : ' a t -> at : Time_ns . t -> ' a -> ' a Alarm . t val add_at_interval_num : ' a t -> at : Interval_num . t -> ' a -> ' a Alarm . t val mem : ' a t -> ' a Alarm . t -> bool val remove : ' a t -> ' a Alarm . t -> unit val reschedule : ' a t -> ' a Alarm . t -> at : Time_ns . t -> unit val reschedule_at_interval_num : ' a t -> ' a Alarm . t -> at : Interval_num . t -> unit val clear : _ t -> unit val min_alarm_interval_num : _ t -> Interval_num . t option val min_alarm_interval_num_exn : _ t -> Interval_num . t val max_alarm_time_in_min_interval : ' a t -> Time_ns . t option val max_alarm_time_in_min_interval_exn : ' a t -> Time_ns . t val next_alarm_fires_at : _ t -> Time_ns . t option val next_alarm_fires_at_exn : _ t -> Time_ns . t module Private : sig val max_time : Time_ns . t val interval_num_internal : time : Time_ns . t -> alarm_precision : Alarm_precision . t -> Interval_num . t module Num_key_bits : sig type t include Invariant . S with type t := t val zero : t end end end
type ' a run = Asc of ' a list | Desc of ' a list | [ ] | [ _ ] -> true | x :: y :: r -> compare x y <= 0 && sorted_list compare ( y :: r )
type ' a cmp = ' a -> ' a -> int match l with [ ] -> ( ) | [ _ ] -> ( ) | y1 :: ys -> sorted_mem cmp y1 ys | [ ] | [ _ ] -> true | x :: y :: r -> compare x y >= 0 && sorted_list_rev compare ( y :: r ) match l with [ ] -> ( ) | [ _ ] -> ( ) | y1 :: ys -> sorted_rev_mem cmp y1 ys
let rec next_asc_run_rev compare revrun last len = function | x :: xs -> if compare last x <= 0 then next_asc_run_rev compare ( last :: revrun ) x ( len + 1 ) xs else let xs = x :: xs in ( len , Desc ( last :: revrun ) , xs ) | xs -> ( len , Desc ( last :: revrun ) , xs )
let rec next_desc_run_rev compare ( revrun : ' a list ) last len = function | x :: xs -> if compare last x > 0 then next_desc_run_rev compare ( last :: revrun ) x ( len + 1 ) xs else let xs = x :: xs in ( len , Asc ( last :: revrun ) , xs ) | xs -> ( len , Asc ( last :: revrun ) , xs )
let next_run compare xs = match xs with | [ ] -> None | [ _ ] -> Some ( 1 , Asc xs , [ ] ) | x1 :: x2 :: xs -> if compare x1 x2 <= 0 then Some ( next_asc_run_rev compare [ x1 ] x2 2 xs ) else Some ( next_desc_run_rev compare [ x1 ] x2 2 xs )
let merge_asc_rev compare xs ys = let rec merge_asc_rev revacc xs ys = match ( xs , ys ) with | [ ] , zs | zs , [ ] -> List . rev_append zs revacc | x :: xs ' , y :: ys ' -> if compare x y <= 0 then merge_asc_rev ( x :: revacc ) xs ' ys else merge_asc_rev ( y :: revacc ) xs ys ' in merge_asc_rev [ ] xs ys
let merge_desc_rev compare = let rec merge_desc_rev revacc xs ys = match ( xs , ys ) with | [ ] , zs | zs , [ ] -> List . rev_append zs revacc | x :: xs ' , y :: ys ' -> if compare x y > 0 then merge_desc_rev ( x :: revacc ) xs ' ys else merge_desc_rev ( y :: revacc ) xs ys ' in merge_desc_rev [ ]
let merge compare n1 n2 r1 r2 = let run = match ( r1 , r2 ) with | Asc r1 , Asc r2 -> Desc ( merge_asc_rev compare r1 r2 ) | Desc r1 , Desc r2 -> Asc ( merge_desc_rev compare r1 r2 ) | Asc r1 , Desc r2 -> if n1 < n2 then Asc ( merge_desc_rev compare ( List . rev r1 ) r2 ) else Desc ( merge_asc_rev compare r1 ( List . rev r2 ) ) | Desc r1 , Asc r2 -> if n1 < n2 then Desc ( merge_asc_rev compare ( List . rev r1 ) r2 ) else Asc ( merge_desc_rev compare r1 ( List . rev r2 ) ) in ( n1 + n2 , run )
type ' a stack = ( int * ' a run ) list
let timsort compare l = let merge = merge compare in let next_run = next_run compare in let rec fetch_next_run remaining stack = match next_run remaining with | Some ( n , r , rem ) -> sort rem ( ( n , r ) :: stack ) | None -> stack and sort remaining stack = match stack with | ( ( n1 , r1 ) as s1 ) :: ( n2 , r2 ) :: ( ( n3 , r3 ) :: stack ' ' as stack ' ) -> ( if n3 < n1 then sort remaining ( s1 :: merge n2 n3 r2 r3 :: stack ' ' ) else if n2 <= n1 then sort remaining ( merge n1 n2 r1 r2 :: stack ' ) else if n3 <= n1 + n2 then sort remaining ( merge n1 n2 r1 r2 :: stack ' ) else match stack with | ( n4 , _ ) :: _ -> if n4 <= n3 + n2 then sort remaining ( merge n1 n2 r1 r2 :: stack ' ) else fetch_next_run remaining stack | _ -> fetch_next_run remaining stack ) | [ ( n1 , r1 ) ; ( n2 , r2 ) ] -> if n2 <= n1 then sort remaining [ merge n1 n2 r1 r2 ] else fetch_next_run remaining stack | _ -> fetch_next_run remaining stack in let rec finish = function | ( n1 , r1 ) :: ( n2 , r2 ) :: stack -> finish ( merge n1 n2 r1 r2 :: stack ) | [ ( _ , Asc r ) ] -> r | [ ( _ , Desc r ) ] -> List . rev r | [ ] -> [ ] in finish ( sort l [ ] )
type untyped_ocaml_value = UInt of int
let rec string_of_untyped = function UInt i -> Printf . sprintf " UInt % i " i List . fold_left ( ^ ) " " ( List . map ( fun x -> Printf . sprintf " % s ; " ( string_of_untyped x ) ) ( Array . to_list arr ) ) List . fold_left ( ^ ) " " ( List . map ( fun x -> Printf . sprintf " % f ; " x ) ( Array . to_list arr ) )
let rec find_tag_in_constdecls x isblock tblock tnonblock = function { pcd_name = { txt } ; pcd_args = Pcstr_tuple [ ] } :: _ when x = tnonblock && not isblock -> ( txt , [ ] )
let find_tag_in_variant_type x isblock = function | Ptype_variant constdecls -> Some ( find_tag_in_constdecls x isblock 0 0 constdecls ) | Ptype_abstract -> None | Ptype_record _ -> None | Ptype_open -> None
let rec lookup_variant_type ( env : Tinyocaml . env ) vartypename x isblock = match env with EnvType ( _ , [ { ptype_name = { txt } ; ptype_kind } ] ) :: r when txt = vartypename -> begin match find_tag_in_variant_type x isblock ptype_kind with Some x -> x | None -> lookup_variant_type r vartypename x isblock end | _ :: r -> lookup_variant_type r vartypename x isblock | [ ] -> failwith " Could not find tag and name in lookup_variant_type "
let rec read_untyped env debug_typ v typ = match v , typ . ptyp_desc with | UInt n , Ptyp_constr ( { txt = Longident . Lident " int " } , _ ) -> Int n | UInt n , Ptyp_constr ( { txt = Longident . Lident " bool " } , _ ) -> Bool ( n <> 0 ) | UInt n , Ptyp_constr ( { txt = Longident . Lident " char " } , _ ) -> Char ( char_of_int n ) | UInt 0 , Ptyp_constr ( { txt = Longident . Lident " list " } , _ ) -> Nil | UInt 0 , Ptyp_constr ( { txt = Longident . Lident " unit " } , _ ) -> Unit | UString s , Ptyp_constr ( { txt = Longident . Lident " string " } , _ ) -> String ( Bytes . of_string s ) | UDouble d , Ptyp_constr ( { txt = Longident . Lident " float " } , _ ) -> Float d | UBlock ( 0 , vs ) , Ptyp_tuple ts when Array . length vs = List . length ts -> Tuple ( List . map2 ( read_untyped env debug_typ ) ( Array . to_list vs ) ts ) | UBlock ( 0 , vs ) , Ptyp_constr ( { txt = Longident . Lident " array " } , [ elt_typ ] ) -> Array ( Array . map ( fun x -> read_untyped env debug_typ x elt_typ ) vs ) | UBlock ( 0 , [ | h ; t ] ) , | Ptyp_constr ( { txt = Longident . Lident " list " } , [ elt_typ ] ) -> Cons ( read_untyped env debug_typ h elt_typ , read_untyped env debug_typ t typ ) | UBlock ( 0 , vs ) , Ptyp_constr ( { txt = Longident . Lident " ref " } , [ elt_typ ] ) -> Record ( List . map ( fun x -> ( " contents " , ref ( read_untyped env debug_typ x elt_typ ) ) ) ( Array . to_list vs ) ) | UInt x , Ptyp_constr ( { txt = Longident . Lident vartypename } , [ elt_typ ] ) -> let name , _ = lookup_variant_type env vartypename x false in Constr ( x , name , None ) | UBlock ( x , [ | v ] ) , | Ptyp_constr ( { txt = Longident . Lident vartypename } , [ ] ) -> let name , elt_typ = lookup_variant_type env vartypename x true in Printf . printf " Located constructor name % s \ n " name ; Constr ( x , name , Some ( read_untyped env debug_typ v ( List . hd elt_typ ) ) ) | UBlock ( x , [ | v ] ) , | Ptyp_constr ( { txt = Longident . Lident vartypename } , [ elt_typ ] ) -> let name , _ = lookup_variant_type env vartypename x true in Constr ( x , name , Some ( read_untyped env debug_typ v elt_typ ) ) | UDoubleArray arr , _ -> Array ( Array . map ( fun x -> Float x ) arr ) | b , _ -> failwith ( Printf . sprintf " read_untyped : unimplemented : % s of type % s " ( string_of_untyped b ) debug_typ )
let parse_type typ = typ |> Lexing . from_string |> Parse . core_type
let of_ocaml_value env x typ = read_untyped env typ ( untyped_of_ocaml_value x ) ( parse_type typ )
type op = Add | Sub | Mul | Div
type cmp = LT | EQ | GT | EQLT | EQGT | NEQ
type control = Underline | Bold
type forkind = UpTo | DownTo
type pattern = PatAny EnvBinding of bool * binding list ref ModTypeSignature of t TypChar Unit
let rec iter f x = f x ; match x with | ( Bool _ | Float _ | Var _ | Int _ | Int32 _ | Int64 _ | NativeInt _ | Char _ | String _ | OutChannel _ | InChannel _ | Unit | Nil | ModuleIdentifier _ | Raise ( _ , None ) | ExceptionDef _ | TypeDef _ | Open _ ) -> ( ) | Control ( _ , a ) | Field ( a , _ ) | Raise ( _ , Some a ) | TryWith ( a , _ ) | ModuleBinding ( _ , a ) | ModuleConstraint ( _ , a ) | Functor ( _ , _ , a ) | Assert a | Include a | LocalOpen ( _ , a ) | Lazy a -> iter f a | Op ( _ , a , b ) | And ( a , b ) | Or ( a , b ) | Cmp ( _ , a , b ) | If ( a , b , None ) | App ( a , b ) | Seq ( a , b ) | Annot ( _ , a , b ) | SetField ( a , _ , b ) | ModuleApply ( a , b ) | Cons ( a , b ) | Append ( a , b ) -> iter f a ; iter f b | If ( e , e1 , Some e2 ) -> iter f e ; iter f e1 ; iter f e2 | Let ( recflag , bindings , e ) -> List . iter ( fun ( _ , v ) -> iter f v ) bindings ; iter f e | LetDef ( recflag , bindings ) -> List . iter ( fun ( _ , v ) -> iter f v ) bindings | Fun ( label , n , fexp , e ) -> iter_label f label ; iter f fexp | While ( a , b , c , d ) -> iter f a ; iter f b ; iter f c ; iter f d | For ( v , a , x , b , c , copy ) -> iter f a ; iter f b ; iter f c ; iter f copy | Array xs -> Array . iter ( iter f ) xs | Record items -> List . iter ( fun ( _ , v ) -> iter f ! v ) items | CallBuiltIn ( _ , _ , args , _ ) -> List . iter f args | Struct ( _ , l ) | Sig l | Tuple l -> List . iter ( iter f ) l | Function ( patmatch , _ ) -> List . iter ( iter_case f ) patmatch | Constr ( _ , _ , e ) -> iter_option f e | Match ( e , cases ) -> iter f e ; List . iter ( iter_case f ) cases None -> ( ) begin match guard with None -> ( ) | Some g -> f g end ; f rhs | Optional ( s , Some x ) -> iter f x | _ -> ( )
let rec recurse f exp = match exp with | ( Bool _ | Float _ | Var _ | Int _ | Int32 _ | Int64 _ | NativeInt _ | Char _ | String _ | OutChannel _ | InChannel _ | Unit | Nil | ModuleIdentifier _ ) as x -> x | Op ( op , a , b ) -> Op ( op , f a , f b ) | And ( a , b ) -> And ( f a , f b ) | Or ( a , b ) -> Or ( f a , f b ) | Cmp ( cmp , a , b ) -> Cmp ( cmp , f a , f b ) | If ( e , e1 , e2 ) -> If ( f e , f e1 , recurse_option f e2 ) | Let ( recflag , bindings , e ) -> Let ( recflag , List . map ( fun ( n , v ) -> ( n , f v ) ) bindings , f e ) | LetDef ( recflag , bindings ) -> LetDef ( recflag , List . map ( fun ( n , v ) -> ( n , f v ) ) bindings ) | Fun ( label , n , fexp , env ) -> Fun ( recurse_label f label , n , f fexp , env ) | App ( a , b ) -> App ( f a , f b ) | Seq ( a , b ) -> Seq ( f a , f b ) | While ( a , b , c , d ) -> While ( f a , f b , f c , f d ) | For ( v , a , x , b , c , copy ) -> For ( v , f a , x , f b , f c , f copy ) | Control ( c , x ) -> Control ( c , f x ) | Annot ( n , x , y ) -> Annot ( n , f x , f y ) | Array xs -> Array . iteri ( fun n c -> xs . ( n ) <- f c ) xs ; Array xs | Record items -> List . iter ( fun ( k , v ) -> v := f ! v ) items ; Record items | Field ( a , n ) -> Field ( f a , n ) | SetField ( a , n , b ) -> SetField ( f a , n , f b ) | Raise s -> Raise s | TryWith ( a , s ) -> TryWith ( f a , s ) | ExceptionDef e -> ExceptionDef e | TypeDef e -> TypeDef e | CallBuiltIn ( typ , name , args , fn ) -> CallBuiltIn ( typ , name , List . map f args , fn ) | Struct ( b , l ) -> Struct ( b , List . map f l ) | Sig l -> Sig ( List . map f l ) | ModuleBinding ( n , m ) -> ModuleBinding ( n , f m ) | ModuleConstraint ( t , e ) -> ModuleConstraint ( t , f e ) | ModuleApply ( m1 , m2 ) -> ModuleApply ( f m1 , f m2 ) | Functor ( x , mt , me ) -> Functor ( x , mt , f me ) | Cons ( e , e ' ) -> Cons ( f e , f e ' ) | Constr ( tag , n , None ) -> Constr ( tag , n , None ) | Constr ( tag , n , Some t ) -> Constr ( tag , n , Some ( f t ) ) | Append ( e , e ' ) -> Append ( f e , f e ' ) | Match ( e , patmatch ) -> Match ( e , List . map ( recurse_case f ) patmatch ) | Function ( patmatch , env ) -> Function ( List . map ( recurse_case f ) patmatch , env ) | Tuple l -> Tuple ( List . map f l ) | Assert e -> Assert ( f e ) | Open n -> Open n | LocalOpen ( n , e ) -> LocalOpen ( n , f e ) | Lazy e -> Lazy ( f e ) | Include e -> Include ( f e ) | Optional ( s , Some x ) -> Optional ( s , Some ( f x ) ) | x -> x None -> None ( pat , begin match guard with None -> None | Some g -> Some ( f g ) end , f rhs )
let string_of_op = function Add -> " " + | Sub -> " " - | Mul -> " " * | Div -> " " /
let string_of_cmp = function LT -> " " < | EQ -> " " = | GT -> " " > | EQLT -> " " <= | EQGT -> " " >= | NEQ -> " " <>
let op_of_string = function " " + -> Add | " " - -> Sub | " " * -> Mul | " " / -> Div
let cmp_of_string = function " " < -> LT | " " = -> EQ | " " > -> GT | " " <= -> EQLT | " " >= -> EQGT | " " <> -> NEQ
let string_of_coretype t = let f = Format . str_formatter in Pprintast . core_type f t ; Format . flush_str_formatter ( )