text
stringlengths
12
786k
let await_timeout cb = if is_expired cb then Deferred . return ( ) else match cb . expiration with | None -> Deferred . never ( ) | Some expires_at -> after ( Time_ns . Span . to_span_float_round_nearest @@ Time_ns . diff expires_at ( Time_ns . now ( ) ) )
let await cb = if is_expired cb then ( record_timeout_metrics cb ; Deferred . return None ) None else match cb . expiration with | None -> Ivar . read cb . signal >>| Option . some | Some expires_at -> ( match % map Timeout . await ( ) ~ timeout_duration ( : Time_ns . diff expires_at ( Time_ns . now ( ) ) ) ( Ivar . read cb . signal ) signal with | ` Ok result -> let validation_time = Time_ns . abs_diff expires_at ( Time_ns . now ( ) ) |> Time_ns . Span . to_ms |> Time . Span . of_ms in record_validation_metrics cb . message_type result validation_time ; Some result | ` Timeout -> record_timeout_metrics cb ; None )
let await_exn cb = match % map await cb with None -> failwith " timeout " | Some result -> result
let fire_if_not_already_fired cb result = if not ( is_expired cb ) cb then ( if Ivar . is_full cb . signal then [ % log ' error ( Logger . create ( ) ) ] " Ivar . fill bug is here " ! ; Ivar . fill cb . signal result )
let set_message_type t x = t . message_type <- x
type error += Oversized_operation of { size : int ; max : int }
type error += | Future_block_header of { block : Block_hash . t ; block_time : Time . Protocol . t ; time : Time . System . t ; }
let ( ) = register_error_kind ` Permanent ~ id " : node . prevalidation . parse_error " ~ title " : Parsing error in prevalidation " ~ description : " Raised when an operation has not been parsed correctly during \ prevalidation . " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Operation parsing error in prevalidation . " ) Data_encoding . empty ( function Parse_error -> Some ( ) | _ -> None ) ( fun ( ) -> Parse_error ) ; register_error_kind ` Temporary ~ id " : node . prevalidation . too_many_operations " ~ title " : Too many pending operations in prevalidation " ~ description " : The prevalidation context is full . " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Too many operations in prevalidation context . " ) Data_encoding . empty ( function Too_many_operations -> Some ( ) | _ -> None ) ( fun ( ) -> Too_many_operations ) ; register_error_kind ` Permanent ~ id " : node . prevalidation . oversized_operation " ~ title " : Oversized operation " ~ description " : The operation size is bigger than allowed . " ~ pp ( : fun ppf ( size , max ) -> Format . fprintf ppf " Oversized operation ( size : % d , max : % d ) " size max ) Data_encoding . ( obj2 ( req " size " int31 ) ( req " max_size " int31 ) ) ( function Oversized_operation { size ; max } -> Some ( size , max ) | _ -> None ) ( fun ( size , max ) -> Oversized_operation { size ; max } ) ; register_error_kind ` Temporary ~ id " : node . prevalidation . future_block_header " ~ title " : Future block header " ~ description " : The block was annotated with a time too far in the future . " ~ pp ( : fun ppf ( block , block_time , time ) -> Format . fprintf ppf " Future block header ( block : % a , block_time : % a , time : % a ) " Block_hash . pp block Time . System . pp_hum ( Time . System . of_protocol_exn block_time ) Time . System . pp_hum time ) Data_encoding . ( obj3 ( req " block " Block_hash . encoding ) ( req " block_time " Time . Protocol . encoding ) ( req " time " Time . System . encoding ) ) ( function | Future_block_header { block ; block_time ; time } -> Some ( block , block_time , time ) | _ -> None ) ( fun ( block , block_time , time ) -> Future_block_header { block ; block_time ; time } ) ; Error_monad . register_error_kind ` Permanent ~ id " : block_validation . cannot_serialize_metadata " ~ title " : Cannot serialize metadata " ~ description " : Unable to serialize metadata " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Unable to serialize the metadata for an operation . " ) Data_encoding . empty ( function Cannot_serialize_operation_metadata -> Some ( ) | _ -> None ) ( fun ( ) -> Cannot_serialize_operation_metadata )
type error += Unknown_chain of Chain_id . t
type error += Block_not_invalid of Block_hash . t
let ( ) = register_error_kind ` Permanent ~ id " : node . state . unknown_chain " ~ title " : Unknown chain " ~ description : " The chain identifier could not be found in the chain identifiers table . " ~ pp ( : fun ppf id -> Format . fprintf ppf " Unknown chain % a " Chain_id . pp id ) Data_encoding . ( obj1 ( req " chain " Chain_id . encoding ) ) ( function Unknown_chain x -> Some x | _ -> None ) ( fun x -> Unknown_chain x ) ; register_error_kind ` Permanent ~ id " : node . state . bad_data_dir " ~ title " : Bad data directory " ~ description : " The data directory could not be read . This could be because it was \ generated with an old version of the tezos - node program . Deleting and \ regenerating this directory may fix the problem . " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Bad data directory . " ) Data_encoding . empty ( function Bad_data_dir -> Some ( ) | _ -> None ) ( fun ( ) -> Bad_data_dir ) ; register_error_kind ` Permanent ~ id " : node . state . block_not_invalid " ~ title " : Block not invalid " ~ description " : The invalid block to be unmarked was not actually invalid . " ~ pp ( : fun ppf block -> Format . fprintf ppf " Block % a was expected to be invalid , but was not actually invalid . " Block_hash . pp block ) Data_encoding . ( obj1 ( req " block " Block_hash . encoding ) ) ( function Block_not_invalid block -> Some block | _ -> None ) ( fun block -> Block_not_invalid block )
type error += Inconsistent_hash of Context_hash . t * Context_hash . t
type error += Missing_block_metadata_hash of Block_hash . t
type error += Missing_operation_metadata_hashes of Block_hash . t
let ( ) = register_error_kind ` Permanent ~ id " : node . state . block . inconsistent_context_hash " ~ title " : Inconsistent commit hash " ~ description : " When committing the context of a block , the announced context hash was \ not the one computed at commit time . " ~ pp ( : fun ppf ( got , exp ) -> Format . fprintf ppf " [ @< v 2 > Inconsistent hash :@ got : % a @ expected : % a " Context_hash . pp got Context_hash . pp exp ) Data_encoding . ( obj2 ( req " wrong_context_hash " Context_hash . encoding ) ( req " expected_context_hash " Context_hash . encoding ) ) ( function Inconsistent_hash ( got , exp ) -> Some ( got , exp ) | _ -> None ) ( fun ( got , exp ) -> Inconsistent_hash ( got , exp ) ) ; register_error_kind ` Permanent ~ id " : node . state . block . missing_block_metadata_hash " ~ title " : Missing block metadata hash " ~ description : " A block was expected to commit to a block metadata hash , however none \ was given . " ~ pp ( : fun ppf block -> Format . fprintf ppf " [ @< v 2 > Missing block metadata hash at block : % a " Block_hash . pp block ) Data_encoding . ( obj1 ( req " block " Block_hash . encoding ) ) ( function Missing_block_metadata_hash block -> Some block | _ -> None ) ( fun block -> Missing_block_metadata_hash block ) ; register_error_kind ` Permanent ~ id " : node . state . block . missing_operation_metadata_hashes " ~ title " : Missing operation metadata hashes " ~ description : " A block was expected to commit to operation metadata hashes , however \ none were given . " ~ pp ( : fun ppf block -> Format . fprintf ppf " [ @< v 2 > Missing operation metadata hashes at block : % a " Block_hash . pp block ) Data_encoding . ( obj1 ( req " block " Block_hash . encoding ) ) ( function | Missing_operation_metadata_hashes block -> Some block | _ -> None ) ( fun block -> Missing_operation_metadata_hashes block )
type error += Invalid_locator of P2p_peer . Id . t * Block_locator . t
type error += Too_short_locator of P2p_peer . Id . t * Block_locator . t
let ( ) = register_error_kind ` Permanent ~ id " : node . bootstrap_pipeline . invalid_locator " ~ title " : Invalid block locator " ~ description " : Block locator is invalid . " ~ pp ( : fun ppf ( id , locator ) -> Format . fprintf ppf " Invalid block locator on peer % a :\ n % a " P2p_peer . Id . pp id Block_locator . pp locator ) Data_encoding . ( obj2 ( req " id " P2p_peer . Id . encoding ) ( req " locator " Block_locator . encoding ) ) ( function Invalid_locator ( id , loc ) -> Some ( id , loc ) | _ -> None ) ( fun ( id , loc ) -> Invalid_locator ( id , loc ) ) ; register_error_kind ` Permanent ~ id " : node . bootstrap_pipeline . too_short_locator " ~ title " : Too short locator " ~ description " : Block locator is too short . " ~ pp ( : fun ppf ( id , locator ) -> Format . fprintf ppf " Too short locator on peer % a :\ n % a " P2p_peer . Id . pp id Block_locator . pp locator ) Data_encoding . ( obj2 ( req " id " P2p_peer . Id . encoding ) ( req " locator " Block_locator . encoding ) ) ( function Too_short_locator ( id , loc ) -> Some ( id , loc ) | _ -> None ) ( fun ( id , loc ) -> Too_short_locator ( id , loc ) )
type protocol_error = Compilation_failed | Dynlinking_failed
type error += | Invalid_protocol of { hash : Protocol_hash . t ; error : protocol_error }
let protocol_error_encoding = let open Data_encoding in union [ case ( Tag 0 ) ~ title " : Compilation failed " ( obj1 ( req " error " ( constant " compilation_failed " ) ) ) ( function Compilation_failed -> Some ( ) | _ -> None ) ( fun ( ) -> Compilation_failed ) ; case ( Tag 1 ) ~ title " : Dynlinking failed " ( obj1 ( req " error " ( constant " dynlinking_failed " ) ) ) ( function Dynlinking_failed -> Some ( ) | _ -> None ) ( fun ( ) -> Dynlinking_failed ) ; ]
let pp_protocol_error ppf = function | Compilation_failed -> Format . fprintf ppf " compilation error " | Dynlinking_failed -> Format . fprintf ppf " dynlinking error "
let ( ) = register_error_kind ` Permanent ~ id " : node . protocol_validator . invalid_protocol " ~ title " : Invalid protocol " ~ description " : Invalid protocol . " ~ pp ( : fun ppf ( protocol , error ) -> Format . fprintf ppf " [ @< v 2 > Invalid protocol % a @ % a ] " @ Protocol_hash . pp_short protocol pp_protocol_error error ) Data_encoding . ( merge_objs ( obj1 ( req " invalid_protocol " Protocol_hash . encoding ) ) protocol_error_encoding ) ( function | Invalid_protocol { hash ; error } -> Some ( hash , error ) | _ -> None ) ( fun ( hash , error ) -> Invalid_protocol { hash ; error } )
type error += Cannot_load_protocol of Protocol_hash . t
let ( ) = register_error_kind ` Permanent ~ id " : node . protocol_validator . cannot_load_protocol " ~ title " : Cannot load protocol " ~ description " : Cannot load protocol from disk " ~ pp ( : fun ppf protocol -> Format . fprintf ppf " Failed to load the protocol % a from disk : the corresponding files \ might be missing or corrupted . " Protocol_hash . pp protocol ) Data_encoding . ( obj1 ( req " protocol " Protocol_hash . encoding ) ) ( function Cannot_load_protocol protocol -> Some protocol | _ -> None ) ( fun protocol -> Cannot_load_protocol protocol )
type error += Unknown_ancestor | Known_invalid
let ( ) = register_error_kind ` Permanent ~ id " : node . peer_validator . unknown_ancestor " ~ title " : Unknown ancestor " ~ description " : Unknown ancestor block found in the peer ' s chain " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Unknown ancestor " ) Data_encoding . empty ( function Unknown_ancestor -> Some ( ) | _ -> None ) ( fun ( ) -> Unknown_ancestor ) ; register_error_kind ` Permanent ~ id " : node . peer_validator . known_invalid " ~ title " : Known invalid " ~ description " : Known invalid block found in the peer ' s chain " ~ pp ( : fun ppf ( ) -> Format . fprintf ppf " Known invalid " ) Data_encoding . empty ( function Known_invalid -> Some ( ) | _ -> None ) ( fun ( ) -> Known_invalid )
type error += Inactive_chain of Chain_id . t
type error += Checkpoint_error of Block_hash . t * P2p_peer . Id . t option
let ( ) = register_error_kind ` Branch ~ id " : node . validator . inactive_chain " ~ title " : Inactive chain " ~ description " : Attempted validation of a block from an inactive chain . " ~ pp ( : fun ppf chain -> Format . fprintf ppf " Tried to validate a block from chain % a , that is not currently \ considered active . " Chain_id . pp chain ) Data_encoding . ( obj1 ( req " inactive_chain " Chain_id . encoding ) ) ( function Inactive_chain chain -> Some chain | _ -> None ) ( fun chain -> Inactive_chain chain ) ; register_error_kind ` Branch ~ id " : node . validator . checkpoint_error " ~ title " : Block incompatible with the current checkpoint . " ~ description : " The block belongs to a branch that is not compatible with the current \ checkpoint . " ~ pp ( : fun ppf ( block , peer ) -> match peer with | None -> Format . fprintf ppf " The block % a is incompatible with the current checkpoint . " Block_hash . pp_short block | Some peer -> Format . fprintf ppf " The peer % a send us a block which is a sibling of the configured \ checkpoint ( % a ) . " P2p_peer . Id . pp peer Block_hash . pp_short block ) Data_encoding . ( obj2 ( req " block " Block_hash . encoding ) ( opt " peer " P2p_peer . Id . encoding ) ) ( function | Checkpoint_error ( block , peer ) -> Some ( block , peer ) | _ -> None ) ( fun ( block , peer ) -> Checkpoint_error ( block , peer ) )
type ( ' time_received , ' genesis_state , ' proof , ' delta_block_chain , ' frontier_dependencies , ' staged_ledger_diff , ' protocol_versions ) t = ' time_received * ' genesis_state * ' proof * ' delta_block_chain * ' frontier_dependencies * ' staged_ledger_diff * ' protocol_versions constraint ' delta_block_chain = [ ` Delta_block_chain ] * ( State_hash . t Non_empty_list . t , _ ) _ Truth . t constraint ' frontier_dependencies = [ ` Frontier_dependencies ] * ( unit , _ ) _ Truth . t constraint ' staged_ledger_diff = [ ` Staged_ledger_diff ] * ( unit , _ ) _ Truth . t constraint ' protocol_versions = [ ` Protocol_versions ] * ( unit , _ ) _ Truth . t ) *
type fully_invalid = ( [ ` Time_received ] * unit Truth . false_t , [ ` Genesis_state ] * unit Truth . false_t , [ ` Proof ] * unit Truth . false_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . false_t , [ ` Frontier_dependencies ] * unit Truth . false_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . false_t ) t
type initial_valid = ( [ ` Time_received ] * unit Truth . true_t , [ ` Genesis_state ] * unit Truth . true_t , [ ` Proof ] * unit Truth . true_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . true_t , [ ` Frontier_dependencies ] * unit Truth . false_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . true_t ) t
type almost_valid = ( [ ` Time_received ] * unit Truth . true_t , [ ` Genesis_state ] * unit Truth . true_t , [ ` Proof ] * unit Truth . true_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . true_t , [ ` Frontier_dependencies ] * unit Truth . true_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . true_t ) t
type fully_valid = ( [ ` Time_received ] * unit Truth . true_t , [ ` Genesis_state ] * unit Truth . true_t , [ ` Proof ] * unit Truth . true_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . true_t , [ ` Frontier_dependencies ] * unit Truth . true_t , [ ` Staged_ledger_diff ] * unit Truth . true_t , [ ` Protocol_versions ] * unit Truth . true_t ) t
type ( ' time_received , ' genesis_state , ' proof , ' delta_block_chain , ' frontier_dependencies , ' staged_ledger_diff , ' protocol_versions ) with_block = Block . with_hash * ( ' time_received , ' genesis_state , ' proof , ' delta_block_chain , ' frontier_dependencies , ' staged_ledger_diff , ' protocol_versions ) t
type fully_invalid_with_block = ( [ ` Time_received ] * unit Truth . false_t , [ ` Genesis_state ] * unit Truth . false_t , [ ` Proof ] * unit Truth . false_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . false_t , [ ` Frontier_dependencies ] * unit Truth . false_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . false_t ) with_block
type initial_valid_with_block = ( [ ` Time_received ] * unit Truth . true_t , [ ` Genesis_state ] * unit Truth . true_t , [ ` Proof ] * unit Truth . true_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . true_t , [ ` Frontier_dependencies ] * unit Truth . false_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . true_t ) with_block
type almost_valid_with_block = ( [ ` Time_received ] * unit Truth . true_t , [ ` Genesis_state ] * unit Truth . true_t , [ ` Proof ] * unit Truth . true_t , [ ` Delta_block_chain ] * State_hash . t Non_empty_list . t Truth . true_t , [ ` Frontier_dependencies ] * unit Truth . true_t , [ ` Staged_ledger_diff ] * unit Truth . false_t , [ ` Protocol_versions ] * unit Truth . true_t ) with_block
type fully_valid_with_block = Block . with_hash * fully_valid
let fully_invalid : fully_invalid = ( ( ` Time_received , Truth . False ) False , ( ` Genesis_state , Truth . False ) False , ( ` Proof , Truth . False ) False , ( ` Delta_block_chain , Truth . False ) False , ( ` Frontier_dependencies , Truth . False ) False , ( ` Staged_ledger_diff , Truth . False ) False , ( ` Protocol_versions , Truth . False ) False )
type t = { state : Store . t ; db : Distributed_db . t ; block_validator : Block_validator . t ; chain_validator_limits : Chain_validator . limits ; peer_validator_limits : Peer_validator . limits ; block_validator_limits : Block_validator . limits ; prevalidator_limits : Prevalidator . limits ; start_testchain : bool ; valid_block_input : Store . Block . t Lwt_watcher . input ; chains_input : ( Chain_id . t * bool ) Lwt_watcher . input ; active_chains : Chain_validator . t Chain_id . Table . t ; }
let create state db peer_validator_limits block_validator_limits block_validator_kind prevalidator_limits chain_validator_limits ~ start_testchain = Block_validator . create block_validator_limits db block_validator_kind ~ start_testchain >>=? fun block_validator -> let valid_block_input = Lwt_watcher . create_input ( ) in let chains_input = Lwt_watcher . create_input ( ) in return { state ; db ; start_testchain ; block_validator ; block_validator_limits ; prevalidator_limits ; peer_validator_limits ; chain_validator_limits ; valid_block_input ; chains_input ; active_chains = Chain_id . Table . create 7 ; }
let activate v ~ start_prevalidator ~ validator_process chain_store = let chain_id = Store . Chain . chain_id chain_store in Validator_event . ( emit activate_chain ) chain_id >>= fun ( ) -> match Chain_id . Table . find v . active_chains chain_id with | Some chain -> return chain | None -> Chain_validator . create ~ start_prevalidator ~ start_testchain : v . start_testchain ~ active_chains : v . active_chains ~ block_validator_process : validator_process v . peer_validator_limits v . prevalidator_limits v . block_validator v . valid_block_input v . chains_input v . db chain_store v . chain_validator_limits
let get { active_chains ; _ } chain_id = match Chain_id . Table . find active_chains chain_id with | Some nv -> Ok nv | None -> error ( Validation_errors . Inactive_chain chain_id )
let get_active_chains { active_chains ; _ } = let l = Chain_id . Table . fold ( fun c _ acc -> c :: acc ) active_chains [ ] in List . rev l
let read_block store h = Store . all_chain_stores store >>= fun chain_stores -> Lwt_utils . find_map_s ( fun chain_store -> Store . Block . read_block_opt chain_store h >|= Option . map ( fun b -> ( Store . Chain . chain_id chain_store , b ) ) ) chain_stores
let read_block_header db h = read_block ( Distributed_db . store db ) h >|= Option . map ( fun ( chain_id , block ) -> ( chain_id , Store . Block . header block ) )
let validate_block v ( ? force = false ) ? chain_id bytes operations = let hash = Block_hash . hash_bytes [ bytes ] in match Block_header . of_bytes bytes with | None -> failwith " Cannot parse block header . " | Some block -> if not ( Clock_drift . is_not_too_far_in_the_future block . shell . timestamp ) then failwith " Block in the future . " else ( match chain_id with | None -> ( read_block_header v . db block . shell . predecessor >>= function | None -> failwith " Unknown predecessor ( % a ) , cannot inject the block . " Block_hash . pp_short block . shell . predecessor | Some ( chain_id , _bh ) -> Lwt . return ( get v chain_id ) ) | Some chain_id -> ( Lwt . return ( get v chain_id ) >>=? fun nv -> if force then return nv else Distributed_db . Block_header . known ( Chain_validator . chain_db nv ) block . shell . predecessor >>= function | true -> return nv | false -> failwith " Unknown predecessor ( % a ) , cannot inject the block . " Block_hash . pp_short block . shell . predecessor ) ) >>=? fun nv -> let validation = Chain_validator . validate_block nv ~ force hash block operations in return ( hash , validation )
let shutdown { active_chains ; block_validator ; _ } = let chain_validator_jobs = List . of_seq @@ Seq . map ( fun ( id , nv ) -> Validator_event . ( emit shutdown_chain_validator ) id >>= fun ( ) -> Chain_validator . shutdown nv ) ( Chain_id . Table . to_seq active_chains ) in Lwt . join chain_validator_jobs >>= fun ( ) -> Validator_event . ( emit shutdown_block_validator ) ( ) >>= fun ( ) -> Block_validator . shutdown block_validator
let watcher { valid_block_input ; _ } = Lwt_watcher . create_stream valid_block_input
let chains_watcher { chains_input ; _ } = Lwt_watcher . create_stream chains_input
let inject_operation v ? chain_id ~ force op = let inject_operation_on nv ~ handle_missing_prevalidator = match Chain_validator . prevalidator nv with | Some pv -> Prevalidator . inject_operation pv ~ force op | None -> handle_missing_prevalidator in let handle_missing_prevalidator = failwith " Prevalidator is not running , cannot inject the operation . " in match chain_id with | None -> ( read_block_header v . db op . Operation . shell . branch >>= function | None -> if force then Chain_id . Table . iter_es ( fun _chain_id chain -> inject_operation_on chain ~ handle_missing_prevalidator : return_unit ) v . active_chains else failwith " Unknown branch ( % a ) , cannot inject the operation . " Block_hash . pp_short op . shell . branch | Some ( chain_id , _bh ) -> get v chain_id >>?= fun nv -> inject_operation_on nv ~ handle_missing_prevalidator ) | Some chain_id -> get v chain_id >>?= fun nv -> inject_operation_on nv ~ handle_missing_prevalidator
let distributed_db { db ; _ } = db
let section = [ " node " ; " validator " ]
let activate_chain = declare_1 ~ section ~ name " : activate_chain " ~ msg " : activate chain { chain } " ~ level : Notice ( " chain " , Chain_id . encoding )
let shutdown_block_validator = declare_0 ~ section ~ name " : shutdown_block_validator " ~ msg " : shutting down the block validator " ~ level : Notice ( )
let shutdown_chain_validator = declare_1 ~ section ~ name " : shutdown_chain_validator " ~ msg " : shutting down the chain validator { chain } " ~ level : Notice ( " chain " , Chain_id . encoding )
type t = | Empty | Node of t * key * t * int * Int64 . t
let height = function | Empty -> 0 | Node ( _ , _ , _ , h , _ ) -> h
let accval = function | Empty -> 0L | Node ( _ , _ , _ , _ , acc ) -> acc
let weight = function | Empty -> 0L | Node ( l , _ , r , _ , acc ) -> Int64 . sub ( Int64 . sub acc ( accval l ) ) ( accval r )
let rec print f = function | Empty -> Pp . empty_set f | Node ( l , k , r , _ , acc ) as x -> Format . fprintf f " [ @< hov 2 ><% d , % Li ( % Li ) , [ >@% a , @|% a , ] " @ k acc ( weight x ) print l print r
let create l key acc r = let hl = height l in let hr = height r in Node ( l , key , r , succ ( min hl hr ) , acc )
let bal l x w r = let hl = height l in let hr = height r in if hl > hr + 2 then begin match l with | Empty -> invalid_arg " Val_map . bal " | Node ( ll , lv , lr , _ , acc_l ) -> let acc_r = accval r in if height ll >= height lr then create ll lv ( Int64 . add ( Int64 . add acc_l w ) acc_r ) ( create lr x ( Int64 . add ( Int64 . add w ( accval lr ) ) acc_r ) r ) else begin match lr with Empty -> invalid_arg " Val_map . bal " | Node ( lrl , lrv , lrr , _ , _ ) -> let acc_lrr = accval lrr in create ( create ll lv ( Int64 . sub acc_l acc_lrr ) lrl ) lrv ( Int64 . add ( Int64 . add acc_l w ) acc_r ) ( create lrr x ( Int64 . add ( Int64 . add acc_lrr w ) acc_r ) r ) end end else if hr > hl + 2 then begin match r with | Empty -> invalid_arg " Val_map . bal " | Node ( rl , rv , rr , _ , acc_r ) -> let acc_l = accval l in if height rr >= height rl then create ( create l x ( Int64 . add ( Int64 . add acc_l w ) ( accval rl ) ) rl ) rv ( Int64 . add ( Int64 . add acc_l w ) acc_r ) rr else begin match rl with | Empty -> invalid_arg " Val_map . bal " | Node ( rll , rlv , rlr , _ , _ ) -> let acc_rll = accval rll in create ( create l x ( Int64 . add ( Int64 . add acc_l w ) acc_rll ) rll ) rlv ( Int64 . add ( Int64 . add acc_l w ) acc_r ) ( create rlr rv ( Int64 . sub acc_r acc_rll ) rr ) end end else let acc_l = accval l in let acc_r = accval r in create l x ( Int64 . add ( Int64 . add acc_l w ) acc_r ) r
let is_empty = function Empty -> true | Node _ -> false
let rec add key weight = function | Empty -> Node ( Empty , key , Empty , 1 , Int64 . of_int weight ) | Node ( l , key ' , r , h , acc ) -> if key = key ' then Node ( l , key , r , h , Int64 . add ( Int64 . add ( Int64 . of_int weight ) ( accval l ) ) ( accval r ) ) else let weight ' = Int64 . sub ( Int64 . sub acc ( accval l ) ) ( accval r ) in if key < key ' then bal ( add key weight l ) key ' weight ' r else bal l key ' weight ' ( add key weight r )
let rec find_acc aim_acc = function | Empty -> raise Not_found | Node ( l , key , r , _ , acc ) -> if aim_acc >= acc then raise Not_found else let acc_l = accval l in let acc_r = accval r in if acc_l > aim_acc then find_acc aim_acc l else if Int64 . add acc_r acc_l > aim_acc then find_acc ( Int64 . sub aim_acc acc_l ) r else key
let rec mem key = function | Empty -> false | Node ( l , key ' , r , _ , _ ) -> let c = Mods . int_compare key key ' in c = 0 || ( mem key ( if c < 0 then l else r ) )
let rec min_binding = function | Empty -> raise Not_found | Node ( Empty , x , r , _ , acc ) -> ( x , Int64 . sub acc ( accval r ) ) | Node ( l , _ , _ , _ , _ ) -> min_binding l
let rec remove_min_binding = function | Empty -> invalid_arg " Val_map . remove_min_elt " | Node ( Empty , _ , r , _ , _ ) -> r | Node ( l , x , r , _ , acc ) -> let weight = Int64 . sub ( Int64 . sub acc ( accval l ) ) ( accval r ) in bal ( remove_min_binding l ) x weight r
let merge t1 t2 = match ( t1 , t2 ) with | ( Empty , t ) -> t | ( t , Empty ) -> t | ( Node _ , Node _ ) -> let ( x , w ) = min_binding t2 in bal t1 x w ( remove_min_binding t2 )
let rec remove x = function | Empty -> Empty | Node ( l , v , r , _ , acc ) -> let c = compare x v in if c = 0 then merge l r else let weight = Int64 . sub ( Int64 . sub acc ( accval l ) ) ( accval r ) in if c < 0 then bal ( remove x l ) v weight r else bal l v weight ( remove x r )
let random state m = try let r = Random . State . int64 state ( accval m ) in find_acc r m with | Invalid_argument _ -> invalid_arg " Val_map . random_val "
module type DFA = sig type states val states : states Fin . set type transitions val transitions : transitions Fin . set type label val label : transitions Fin . elt -> label val source : transitions Fin . elt -> states Fin . elt val target : transitions Fin . elt -> states Fin . elt end
module type INPUT = sig include DFA val initials : ( states Fin . elt -> unit ) -> unit val finals : ( states Fin . elt -> unit ) -> unit val refinements : refine ( : iter ( ( : states Fin . elt -> unit ) -> unit ) -> unit ) -> unit end
let index_transitions ( type state ) ( type transition ) ( states : state Fin . set ) ( transitions : transition Fin . set ) ( target : transition Fin . elt -> state Fin . elt ) : state Fin . elt -> ( transition Fin . elt -> unit ) -> unit = let f = Array . make ( Fin . Set . cardinal states + 1 ) 0 in Fin . Set . iter transitions ( fun t -> let state = ( target t :> int ) in f . ( state ) <- f . ( state ) + 1 ) ; for i = 0 to Fin . Set . cardinal states - 1 do f . ( i + 1 ) <- f . ( i + 1 ) + f . ( i ) done ; let a = Array . make ( Fin . Set . cardinal transitions ) ( Fin . Elt . of_int transitions 0 ) in Fin . Set . rev_iter transitions ( fun t -> let state = ( target t :> int ) in let index = f . ( state ) - 1 in f . ( state ) <- index ; a . ( index ) <- t ) ; ( fun st fn -> let st = ( st : state Fin . elt :> int ) in for i = f . ( st ) to f . ( st + 1 ) - 1 do fn a . ( i ) done )
let discard_unreachable ( type state ) ( type transition ) ( blocks : state Partition . t ) ( transitions_of : state Fin . elt -> ( transition Fin . elt -> unit ) -> unit ) ( target : transition Fin . elt -> state Fin . elt ) = Partition . iter_marked_elements blocks 0 ( fun state -> transitions_of state ( fun transition -> Partition . mark blocks ( target transition ) ) ) ; Partition . discard_unmarked blocks
module Minimize ( Label : Map . OrderedType ) ( In : INPUT with type label := Label . t ) : sig include DFA with type label = Label . t val initials : states Fin . elt array val finals : states Fin . elt array val transport_state : In . states Fin . elt -> states Fin . elt option val transport_transition : In . transitions Fin . elt -> transitions Fin . elt option val represent_state : states Fin . elt -> In . states Fin . elt val represent_transition : transitions Fin . elt -> In . transitions Fin . elt let blocks = Partition . create In . states let ( ) = In . initials ( Partition . mark blocks ) ; let transitions_source = index_transitions In . states In . transitions In . source in discard_unreachable blocks transitions_source In . target let transitions_targeting = index_transitions In . states In . transitions In . target let ( ) = In . finals ( Partition . mark blocks ) ; discard_unreachable blocks transitions_targeting In . source let ( ) = In . finals ( Partition . mark blocks ) ; Partition . split blocks let ( ) = let refine ~ iter = iter ( Partition . mark blocks ) ; Partition . split blocks in In . refinements ~ refine let cords = let partition t1 t2 = Label . compare ( In . label t1 ) ( In . label t2 ) in Partition . create In . transitions ~ partition let ( ) = Partition . discard cords ( fun t -> Partition . set_of blocks ( In . source t ) = - 1 || Partition . set_of blocks ( In . target t ) = - 1 ) let ( ) = let block_set = ref 1 in let cord_set = ref 0 in while ! cord_set < Partition . set_count cords do Partition . iter_elements cords ! cord_set ( fun transition -> Partition . mark blocks ( In . source transition ) ) ; Partition . split blocks ; while ! block_set < Partition . set_count blocks do Partition . iter_elements blocks ! block_set ( fun state -> transitions_targeting state ( Partition . mark cords ) ) ; Partition . split cords ; incr block_set ; done ; incr cord_set ; done module States = Strong . Natural . Nth ( struct let n = Partition . set_count blocks end ) type states = States . n let states = States . n module Transitions = Fin . Array . Of_array ( struct type a = In . transitions Fin . elt let table = let count = ref 0 in Fin . Set . iter In . transitions ( fun tr -> if Partition . is_first blocks ( In . source tr ) && Partition . set_of blocks ( In . target tr ) > - 1 then incr count ) ; match ! count with | 0 -> [ ] || | n -> Array . make n ( Fin . Elt . of_int In . transitions 0 ) let ( ) = let count = ref 0 in Fin . Set . iter In . transitions ( fun tr -> if Partition . is_first blocks ( In . source tr ) && Partition . set_of blocks ( In . target tr ) > - 1 then ( let index = ! count in incr count ; table . ( index ) <- tr ) ) ; end ) type transitions = Transitions . n let transitions = Transitions . n type label = Label . t let transport_state_unsafe = let table = Fin . Array . init In . states ( Partition . set_of blocks ) in Fin . Array . get table let represent_state = let table = Fin . Array . init states ( fun st -> Partition . choose blocks ( st : states Fin . elt :> int ) ) in Fin . Array . get table let represent_transition transition = Fin . ( Transitions . table . ( transition ) ) let label transition : Label . t = In . label ( represent_transition transition ) let source transition = Fin . Elt . of_int states ( transport_state_unsafe ( In . source ( represent_transition transition ) ) ) let target transition = Fin . Elt . of_int states ( transport_state_unsafe ( In . target ( represent_transition transition ) ) ) let initials = In . initials ( Partition . mark blocks ) ; let sets = Partition . marked_sets blocks in Partition . clear_marks blocks ; Array . map ( Fin . Elt . of_int states ) ( Array . of_list sets ) let finals = In . finals ( Partition . mark blocks ) ; let sets = Partition . marked_sets blocks in Partition . clear_marks blocks ; Array . map ( Fin . Elt . of_int states ) ( Array . of_list sets ) let transport_state state = match transport_state_unsafe state with | - 1 -> None | n -> Some ( Fin . Elt . of_int states n ) let transport_transition = let table = Fin . Array . make In . transitions None in Fin . Array . iteri ( fun tr trin -> assert ( Fin . Array . get table trin = None ) ; Fin . Array . set table trin ( Some tr ) ; ) Transitions . table ; Fin . Array . get table end
type t = | Int of int | Int32 of Int32 . t | Int64 of Int64 . t | Nativeint of Nativeint . t | Float of float | Float_array of float array | String of string | Object of t array | Block of int * t array
let rec bprint buf value = let open Printf in match value with | Int n -> bprintf buf " % d " n | Int32 n -> bprintf buf " % ldl " n | Int64 n -> bprintf buf " % LdL " n | Nativeint n -> bprintf buf " % ndn " n | Float f -> bprintf buf " % F " f | Float_array t -> bprint_mlarray ( fun buf f -> bprintf buf " % F " f ) buf t | String s -> bprintf buf " % S " s | Object o -> bprint_array " " < " ; " " " > bprint buf o | Block ( tag , b ) -> bprint_array ( sprintf " [ % d " | tag ) " ; " " ] " bprint buf b
let to_string value = let buf = Buffer . create 16 in bprint buf value ; Buffer . contents buf
let rec of_obj obj = let tag = Obj . tag obj in if tag = Obj . lazy_tag then fail " unexpected lazy block " ; if tag = Obj . closure_tag then fail " unexpected closure " ; if tag = Obj . infix_tag then fail " unexpected closure " ; if tag = Obj . abstract_tag then fail " unexpected abstract block " ; if tag = Obj . object_tag then let size = Obj . size obj in let tab = Array . init size ( fun i -> of_obj ( Obj . field obj i ) ) in Object tab else if tag = Obj . string_tag then String ( Obj . obj obj : string ) else if tag = Obj . double_tag then Float ( Obj . obj obj : float ) else if tag = Obj . double_array_tag then Float_array ( Obj . obj obj : float array ) else if tag = Obj . custom_tag then let key = Obj . field obj 0 in if key = Obj . field ( Obj . repr 0l ) 0 then Int32 ( Obj . obj obj : int32 ) else if key = Obj . field ( Obj . repr 0L ) 0 then Int64 ( Obj . obj obj : int64 ) else if key = Obj . field ( Obj . repr 0n ) 0 then Nativeint ( Obj . obj obj : nativeint ) else fail " unknown custom block " else if tag = Obj . int_tag then Int ( Obj . obj obj : int ) else if tag = Obj . out_of_heap_tag then fail " unexpected block out of heap " else if tag >= Obj . no_scan_tag then fail " unexpected block " else ( assert ( tag < Obj . no_scan_tag ) ; let size = Obj . size obj in let tab = Array . init size ( fun i -> of_obj ( Obj . field obj i ) ) in Block ( tag , tab ) )
let make_to_obj ( ) = let float_htbl = Hashtbl . create 16 in let int32_htbl = Hashtbl . create 16 in let int64_htbl = Hashtbl . create 16 in let nativeint_htbl = Hashtbl . create 16 in let unify htbl v = try Hashtbl . find htbl v with Not_found -> let o = Obj . repr v in Hashtbl . add htbl v o ; o in let rec to_obj value = match value with | Int n -> Obj . repr n | Int32 n -> unify int32_htbl n | Int64 n -> unify int64_htbl n | Nativeint n -> unify nativeint_htbl n | Float f -> unify float_htbl f | Float_array t -> Obj . repr t | String s -> Obj . repr s | Object o -> let len = Array . length o in let obj = Obj . new_block Obj . object_tag len in for i = 0 to len - 1 do Obj . set_field obj i ( to_obj o . ( i ) ) done ; obj | Block ( tag , b ) -> let len = Array . length b in let blk = Obj . new_block tag len in for i = 0 to len - 1 do Obj . set_field blk i ( to_obj b . ( i ) ) done ; blk in to_obj
module type Value = sig type t val zero : t val zero_of_type : type_t -> t val compare : t -> t -> int val to_string : t -> string end
module type Valuation = functor ( V : Value ) -> sig type key = string type value_t = V . t type t val make : string list -> V . t list -> t val vars : t -> string list val bound : string -> t -> bool val value : string -> t -> V . t val consistent : t -> t -> bool val add : t -> string -> V . t -> t val bind : t -> ( string * string ) list -> t val extend : t -> t -> string list -> t val apply : t -> key list -> V . t list val to_string : t -> string end
module AbstractValuation : Valuation = functor ( V : Value ) -> struct module StringMap = Map . Make ( String ) type key = StringMap . key type value_t = V . t type t = V . t StringMap . t let make vars values = List . fold_left ( fun acc ( k , v ) -> StringMap . add k v acc ) StringMap . empty ( List . combine vars values ) let to_string theta : string = StringMap . fold ( fun k v acc -> acc ( ^ if acc = " " then " " else " \ n " ) ^ k " " ( ^->^ V . to_string v ) ) theta " " let to_list m = StringMap . fold ( fun s n l -> ( s , n ) :: l ) m [ ] let vars theta = StringMap . fold ( fun k _ acc -> k :: acc ) theta [ ] let bound var theta = StringMap . mem var theta let value var theta = StringMap . find var theta let consistent theta1 theta2 = List . for_all ( fun ( k , v ) -> ( not ( StringMap . mem k theta2 ) ) || ( ( StringMap . find k theta2 ) = v ) ) ( to_list theta1 ) let add theta var value = StringMap . add var value theta let bind theta bindings = List . fold_left ( fun acc ( decl , def ) -> StringMap . add decl ( value def acc ) acc ) theta bindings let extend theta1 theta2 ext = List . fold_left ( fun acc k -> StringMap . add k ( value k theta2 ) acc ) theta1 ext let apply theta l = List . map ( fun x -> try StringMap . find x theta with Not_found -> failwith ( " No valuation for " ^ x " ^ in " ( ^ to_string theta ) ) ) l end
module rec K3Value : sig type single_map_t = t K3ValuationMap . t and map_t = single_map_t K3ValuationMap . t and t = | Unit | BaseValue of Constants . const_t | Tuple of t list | Fun of ( t -> t ) | SingleMap of single_map_t | DoubleMap of map_t | FloatList of t list | TupleList of t list | SingleMapList of ( t list * single_map_t ) list | ListCollection of t list | MapCollection of t K3ValuationMap . t module Map : SliceableMap . S with type key_elt = t and type ' a t = ' a K3ValuationMap . t val zero : t val zero_of_type : type_t -> t val compare : t -> t -> int val string_of_value : ? sep : string -> t -> string val string_of_smap : ? sep : string -> single_map_t -> string val string_of_map : ? sep : string -> map_t -> string val to_string : t -> string val to_hashtbl : t -> ( Constants . const_t list , Constants . const_t list ) Hashtbl . t struct module Map = K3ValuationMap type single_map_t = t K3ValuationMap . t and map_t = single_map_t K3ValuationMap . t and t = | Unit | BaseValue of Constants . const_t | Tuple of t list | Fun of ( t -> t ) | SingleMap of single_map_t | DoubleMap of map_t | FloatList of t list | TupleList of t list | SingleMapList of ( t list * single_map_t ) list | ListCollection of t list | MapCollection of t K3ValuationMap . t let zero = BaseValue ( CFloat ( 0 . 0 ) ) let zero_of_type zt = BaseValue ( Constants . zero_of_type zt ) let compare = Stdlib . compare let rec key_to_string k = ListExtras . ocaml_of_list string_of_value k and string_of_vmap ( ? sep = " ; \ n " ) sm = K3ValuationMap . to_string ~ sep : sep key_to_string string_of_value sm and string_of_smap ( ? sep = " ; \ n " ) sm = string_of_vmap ~ sep : sep sm and string_of_map ( ? sep = " ; \ n " ) m = K3ValuationMap . to_string ~ sep : sep key_to_string string_of_smap m and string_of_value ( ? sep = " ; \ n " ) v = begin match v with | Unit -> " unit " | BaseValue ( c ) -> if Debug . active " PARSEABLE - VALUES " then sql_of_const c else string_of_const c | Tuple ( fl ) -> " ( " ( ^ String . concat " , " ( List . map ( string_of_value ~ sep : sep ) fl ) ) " ) " ^ | Fun ( f ) -> " < fun " > | SingleMap ( sm ) -> " SingleMap ( " ( ^ string_of_smap ~ sep : sep sm ) " ) " ^ | DoubleMap ( dm ) -> " DoubleMap ( " ( ^ string_of_map ~ sep : sep dm ) " ) " ^ | FloatList ( fl ) -> " [ " ( ^ String . concat " ; " ( List . map ( string_of_value ~ sep : sep ) fl ) ) " ] " ^ | TupleList ( kvl ) -> " TupleList ( [ " ^ ( String . concat sep ( List . map ( fun tuple -> match tuple with | Tuple ( fl ) -> let ( keys , values ) = ListExtras . split_at_last fl in ( string_of_value ~ sep : sep ( FloatList keys ) ) " " ^->^ ( string_of_value ~ sep : sep ( if values <> [ ] then List . hd values else BaseValue ( CInt ( 1 ) ) ) ) | _ -> failwith " TupleList contains elements other than tuples " ) kvl ) ) ^ " ] ) " | SingleMapList ( sml ) -> ( " SingleMapList ( [ " ( ^ List . fold_left ( fun acc ( k , m ) -> ( if acc = " " then " " else acc " ; " ) ^^ ( string_of_value ~ sep : sep ( Tuple k ) ) " , " ^^ ( string_of_value ~ sep : sep ( SingleMap m ) ) ) " " sml ) " ] ) " ) ^ | ListCollection ( vl ) -> " ListCollection ( " ( ^ String . concat " , " ( List . map ( string_of_value ~ sep : sep ) vl ) ) " ) " ^ | MapCollection ( m ) -> " MapCollection ( " ( ^ string_of_vmap ~ sep : sep m ) " ) " ^ end let to_string v = string_of_value v let base_const_of v = match v with | BaseValue ( c ) -> c | _ -> failwith " Invalid argument : not a K3 base value " ! let is_const_zero c = ( c = Constants . zero_of_type ( type_of_const c ) ) let to_hashtbl v = match v with | Unit -> Hashtbl . create 10 | BaseValue ( c ) -> let hashtbl = Hashtbl . create 10 in if not ( is_const_zero c ) then Hashtbl . add hashtbl [ ] [ c ] ; hashtbl | SingleMap ( sm ) -> K3ValuationMap . fold ( fun keys value tbl -> let key_consts = List . map base_const_of keys in let value_const = base_const_of value in if not ( is_const_zero value_const ) then Hashtbl . replace tbl key_consts [ value_const ] ; tbl ) ( Hashtbl . create 10 ) sm | TupleList ( kvl ) -> List . fold_left ( fun tbl tuple -> match tuple with | Tuple ( fl ) -> let ( keys , values ) = ListExtras . split_at_last fl in let key_consts = List . map base_const_of keys in let value_consts = List . map base_const_of values in if value_consts <> [ ] && not ( is_const_zero ( List . hd value_consts ) ) then Hashtbl . replace tbl key_consts value_consts ; tbl | _ -> failwith " TupleList contains elements other than tuples " ) ( Hashtbl . create 10 ) kvl | _ -> failwith " Unsupported ( yet ) conversion of a K3Value into a hash table " end = SliceableMap . Make ( K3Value )
module Make ( D : Debugger . S ) = struct module V = D . Value let rec copy0 ( v : V . t ) : ' a = if debug then begin Format . printf " Value_copier . copy0 % a \ n " %! V . print v end ; if V . is_int v then begin if debug then begin Format . printf " Value is an immediate . \ n " %! end ; match V . int v with | None -> failwith " Synthetic integer value : not yet implemented " | Some i -> Obj . repr i end else begin if debug then begin Format . printf " Value is a pointer . \ n " %! end ; assert ( V . is_block v ) ; let tag = V . tag_exn v in let size = V . size_exn v in if debug then begin Format . printf " Tag % d size % d . \ n " %! tag size end ; if size < 0 || size > 1024 * 1024 then begin failwith " Outsize value " end ; let block = Obj . new_block tag size in if tag < Obj . no_scan_tag then begin for field = 0 to size - 1 do match V . field_exn v field with | None -> failwith " Value only partially available " | Some field_contents -> Obj . set_field block field ( copy0 field_contents ) done end else begin if tag = Obj . double_tag || tag = Obj . double_array_tag || tag = Obj . string_tag then begin for field = 0 to size - 1 do match V . field_exn v field with | None -> failwith " Value only partially available " | Some field_contents -> match V . raw field_contents with | None -> failwith " Cannot get raw value of field " | Some field_contents -> D . write_nativeint_into_field field_contents block ~ field done end else begin failwith " Cannot copy value " end end ; block end let copy v = Obj . magic ( copy0 v ) end
module type Make_subtype_arg = sig type value val here : Source_code_position . t val name : string val is_in_subtype : value -> bool end
type ' a funcall = ? should_profile : bool -> ' a
module type Funcall = sig type t type value val funcall0 : ( t -> value ) funcall val funcall1 : ( t -> value -> value ) funcall val funcall2 : ( t -> value -> value -> value ) funcall val funcall3 : ( t -> value -> value -> value -> value ) funcall val funcall4 : ( t -> value -> value -> value -> value -> value ) funcall val funcall5 : ( t -> value -> value -> value -> value -> value -> value ) funcall val funcallN : ( t -> value list -> value ) funcall val funcallN_array : ( t -> value array -> value ) funcall val funcall0_i : ( t -> unit ) funcall val funcall1_i : ( t -> value -> unit ) funcall val funcall2_i : ( t -> value -> value -> unit ) funcall val funcall3_i : ( t -> value -> value -> value -> unit ) funcall val funcall4_i : ( t -> value -> value -> value -> value -> unit ) funcall val funcall5_i : ( t -> value -> value -> value -> value -> value -> unit ) funcall val funcallN_i : ( t -> value list -> unit ) funcall val funcallN_array_i : ( t -> value array -> unit ) funcall val funcall_int_int_value_value_unit : ( t -> int -> int -> value -> value -> unit ) funcall val funcall_int_int_value_unit : ( t -> int -> int -> value -> unit ) funcall end
module type Subtype = sig type value type t = private value [ @@ deriving sexp_of ] val eq : t -> t -> bool val is_in_subtype : value -> bool include Valueable0 . S with type t := t end
module type Type = sig type value type ' a t val create : Sexp . t -> ( ' a -> Sexp . t ) -> ( value -> ' a ) -> ( ' a -> value ) -> ' a t val with_of_value_exn : ' a t -> ( value -> ' a ) -> ' a t val to_sexp : ' a t -> ' a -> Sexp . t val bool : bool t val float : float t val ignored : unit t val int : int t val string : string t val string_cached : string t val unit : unit t val value : value t val list : ' a t -> ' a list t val vector : ' a t -> ' a array t val array_as_list : ' a t -> ' a array t val option : ' a t -> ' a option t val nil_or : ' a t -> ' a option t val alist : ' a t -> ' b t -> ( ' a * ' b ) list t val tuple : ' a t -> ' b t -> ( ' a * ' b ) t val tuple2_as_list : ' a t -> ' b t -> ( ' a * ' b ) t val sexpable : ( module Sexpable with type t = ' a ) -> name : Sexp . t -> ' a t val path_list : string list t end
module type Value = sig type t = Value0 . t [ @@ deriving sexp_of ] include Funcall with type t := t with type value := t val intern : string -> t val nil : t val t : t val list : t list -> t val cons : t -> t -> t val car_exn : t -> t val cdr_exn : t -> t val to_list_exn : t -> f ( : t -> ' a ) -> ' a list val vector : t array -> t val to_array_exn : t -> f ( : t -> ' a ) -> ' a array val type_of : t -> t val list_to_array_exn : t -> f ( : t -> ' a ) -> ' a array val is_array : t -> bool val is_buffer : t -> bool val is_command : t -> bool val is_event : t -> bool val is_float : t -> bool val is_font : t -> bool val is_frame : t -> bool val is_function : t -> bool val is_hash_table : t -> bool val is_integer : t -> bool val is_keymap : t -> bool val is_marker : t -> bool val is_nil : t -> bool val is_not_nil : t -> bool val is_process : t -> bool val is_string : t -> bool val is_symbol : t -> bool val is_syntax_table : t -> bool val is_timer : t -> bool val is_vector : t -> bool val is_window : t -> bool val is_window_configuration : t -> bool val is_cons : ? car ( : t -> bool ) -> ? cdr ( : t -> bool ) -> t -> bool val eq : t -> t -> bool val equal : t -> t -> bool val of_bool : bool -> t val to_bool : t -> bool val emacs_min_int : int val emacs_max_int : int val of_int_exn : int -> t val to_int_exn : t -> int val of_float : float -> t val to_float_exn : t -> float val of_utf8_bytes : string -> t val of_utf8_bytes_cached : string -> t val to_utf8_bytes_exn : t -> string val vec_get : t -> int -> t val vec_set : t -> int -> t -> unit val vec_size : t -> int val message : string -> unit val messagef : ( ' a , unit , string , unit ) format4 -> ' a val message_s : Sexp . t -> unit val prin1_to_string : t -> string module Type : sig type value type ' a t [ @@ deriving sexp_of ] module type Enum = Enum . S [ @@ deprecated " [ since 2021 - 07 ] Use [ Enum . S ] . " ] module type S = Type with type value := value with type ' a t := ' a t include S val id : ' a t -> ' a Type_equal . Id . t val to_value : ' a t -> ' a -> value val of_value_exn : ' a t -> value -> ' a val name : _ t -> Sexp . t val map : ' a t -> name : Sexp . t -> of_ ( ' : a -> ' b ) -> to_ ( ' : b -> ' a ) -> ' b t val to_sexp : ' a t -> ' a -> Sexp . t val map_id : ' a t -> Sexp . t -> ' a t val enum : Sexp . t -> ( module Enum . S with type t = ' a ) -> ( ' a -> value ) -> ' a t val enum_symbol : Sexp . t -> ( module Enum . S with type t = ' a ) -> ' a t val stringable : Sexp . t -> ( module Stringable . S with type t = ' a ) -> ' a t end with type value := t module type Funcall = Funcall with type value := t module type Make_subtype_arg = Make_subtype_arg with type value := t module type Subtype = Subtype with type value := t with type ' a type_ := ' a Type . t module Make_subtype ( Subtype : Make_subtype_arg ) : Subtype module Expert : sig val have_active_env : unit -> bool val raise_if_emacs_signaled : unit -> unit val non_local_exit_signal : exn -> unit end module Stat : sig type t = { emacs_free_performed : int ; emacs_free_scheduled : int } [ @@ deriving sexp_of ] val now : unit -> t val diff : t -> t -> t end module For_testing : sig val all_interned_symbols : unit -> string list exception Elisp_signal of { symbol : t ; data : t } exception Elisp_throw of { tag : t ; value : t } val map_elisp_signal : ( unit -> ' a ) -> f ( : symbol : t -> data : t -> reraise ( : symbol : t -> data : t -> Nothing . t ) -> Nothing . t ) -> ' a val map_elisp_signal_omit_data : ( unit -> ' a ) -> ' a end module Private : sig val ecaml_profile_print_length : int option ref val ecaml_profile_print_level : int option ref module Block_on_async : sig type t = { f : ' a . Source_code_position . t -> ? context : Sexp . t Lazy . t -> ( unit -> ' a Deferred . t ) -> ' a } val set_once : t Set_once . t end module Enqueue_foreground_block_on_async : sig type t = { f : Source_code_position . t -> ? context : Sexp . t Lazy . t -> ? raise_exceptions_to_monitor : Monitor . t -> ( unit -> unit Deferred . t ) -> unit } val set_once : t Set_once . t end module Run_outside_async : sig type t = { f : ' a . Source_code_position . t -> ? allowed_in_background : bool -> ( unit -> ' a ) -> ' a Deferred . t } val set_once : t Set_once . t end val block_on_async : Source_code_position . t -> ? context : Sexp . t Lazy . t -> ( unit -> ' a Deferred . t ) -> ' a val enqueue_foreground_block_on_async : Source_code_position . t -> ? context : Sexp . t Lazy . t -> ? raise_exceptions_to_monitor : Monitor . t -> ( unit -> unit Deferred . t ) -> unit val run_outside_async : Source_code_position . t -> ? allowed_in_background : bool -> ( unit -> ' a ) -> ' a Deferred . t val message_zero_alloc : t -> unit val message_t : t -> unit end end
module Make ( D : Debugger . S ) ( Cmt_cache : Cmt_cache_intf . S ) ( Type_helper : Type_helper_intf . S with module Cmt_cache := Cmt_cache with module D := D ) ( Type_printer : Type_printer_intf . S with module Cmt_cache := Cmt_cache ) = struct module Our_type_oracle = Type_oracle . Make ( D ) ( Cmt_cache ) module V = D . Value module Our_value_copier = Value_copier . Make ( D ) type t = { cmt_cache : Cmt_cache . t ; type_oracle : Our_type_oracle . t ; type_printer : Type_printer . t ; } type operator = | Nothing | Separator | Application type state = { summary : bool ; depth : int ; max_depth : int ; max_string_length : int ; print_sig : bool ; formatter : Format . formatter ; max_array_elements_etc_to_print : int ; only_print_short_type : bool ; only_print_short_value : bool ; operator_above : operator ; visited : V . Set . t ; } let descend state ~ current_operator = { state with depth = state . depth + 1 ; print_sig = false ; operator_above = current_operator ; } let create cmt_cache type_printer = { type_oracle = Our_type_oracle . create ~ cmt_cache ; cmt_cache ; type_printer ; } let rec value_looks_like_list t value = if V . is_int value && V . int value = Some 0 then true else if ( not ( V . is_int value ) ) && V . is_block value && V . tag_exn value = 0 && V . size_exn value = 2 then match V . field_exn value 1 with | None -> false | Some next -> value_looks_like_list t next else false let maybe_parenthesise state ~ current_operator f = let needs_parentheses = match state . operator_above , current_operator with | Application , Application -> true | ( Nothing | Separator | Application ) , _ -> false in let formatter = state . formatter in if needs_parentheses then begin Format . fprintf formatter " ( " end ; f ( ) ; if needs_parentheses then begin Format . fprintf formatter " ) " end let rec print_value t ~ state ~ type_of_ident : type_and_env v : unit = let formatter = state . formatter in let env = match type_and_env with | None -> None | Some ( _ty , env , _is_parameter ) -> Some env in let _is_parameter = match type_and_env with | None -> Is_parameter . local | Some ( _ty , _env , is_parameter ) -> is_parameter in let type_info = let type_and_env = match type_and_env with | None -> None | Some ( ty , env , _is_parameter ) -> Some ( ty , env ) in Our_type_oracle . find_type_information t . type_oracle ~ formatter type_and_env ~ scrutinee : v in if ( state . summary && state . depth > 2 ) || state . depth > state . max_depth then begin Format . fprintf formatter " _ " end else if V . Set . mem v state . visited then begin Format . fprintf formatter " < circularity " > end else begin let state = { state with visited = V . Set . add v state . visited ; } in match type_info with | Obj_immediate -> print_int t ~ state v | Obj_immediate_but_should_be_boxed -> if V . int v = Some 0 then Format . fprintf formatter " { @< function_name_colour ( ) } " >@ else begin match V . raw v with | Some v -> Format . fprintf formatter " { @< error_colour > 0x % nx } " v | None -> Format . fprintf formatter " < synthetic pointer " > end | Obj_boxed_traversable -> if state . summary then Format . fprintf formatter " . . . " else print_multiple_without_type_info t ~ state v | Obj_boxed_not_traversable -> begin match V . raw v with | Some raw -> Format . fprintf formatter " { @< error_colour >< 0x % nx , tag % d } " >@ raw ( V . tag_exn v ) | None -> Format . fprintf formatter " < synthetic pointer " > end | Unit -> Format . fprintf formatter " ( ) " | Int -> begin match V . int v with | Some _ -> print_int t ~ state v | None -> Format . fprintf formatter " { @< error_colour >< Int } " ?>@ end | Char -> print_char t ~ state v | Abstract path -> begin match env with | None -> Format . fprintf formatter " { @< address_colour ><% s } " >@ ( Path . name path ) | Some env -> Printtyp . wrap_printing_env ~ error : false env ( fun ( ) -> Format . fprintf formatter " { @< address_colour ><% a } " >@ Printtyp . path path ) end | Array ( ty , env ) -> print_array t ~ state ~ ty ~ env v | List ( ty , env ) -> print_list t ~ state ~ ty_and_env ( : Some ( Cmt_file . Core ty , env , Is_parameter . local ) ) v | Ref ( ty , env ) -> print_ref t ~ state ~ ty ~ env v | Tuple ( tys , env ) -> print_tuple t ~ state ~ tys ~ env v | Constant_constructor ( name , kind ) -> print_constant_constructor t ~ state ~ kind ~ name | Non_constant_constructor ( path , ctor_decls , params , instantiated_params , env , kind ) -> print_non_constant_constructor t ~ state ~ path ~ ctor_decls ~ params ~ instantiated_params ~ env ~ kind v | Record ( path , params , args , fields , record_repr , env ) -> print_record t ~ state ~ path ~ params ~ args ~ fields ~ record_repr ~ env v | Open -> Format . fprintf formatter " < value of open type " > | String -> print_string t ~ state v | Float -> print_float t ~ state v | Float_array -> print_float_array t ~ state v | Closure -> print_closure t ~ state ~ scrutinee : v | Lazy -> Format . fprintf formatter " < lazy " > | Object -> Format . fprintf formatter " < object " > | Abstract_tag -> Format . fprintf formatter " < block with Abstract_tag " > | Format6 -> print_format6 t ~ state v | Stdlib_set { env ; element_ty ; } -> print_stdlib_set t state env ~ element_ty v | Stdlib_map { key_env ; key_ty ; datum_env ; datum_ty ; } -> print_stdlib_map t state ~ key_env ~ key_ty ~ datum_env ~ datum_ty v | Stdlib_hashtbl { key_env ; key_ty ; datum_env ; datum_ty ; } -> print_stdlib_hashtbl t state ~ key_env ~ key_ty ~ datum_env ~ datum_ty v | Custom -> print_custom_block t ~ state v | Module mod_ty -> let env = match env with | None -> Env . empty | Some env -> env in print_module t state env mod_ty v | Unknown -> Format . fprintf formatter " unknown " end ; if state . print_sig then begin match type_info with | Unit | Module _ -> ( ) | _ -> let ( _type_printed : bool ) = Type_printer . print_given_type_and_env formatter type_and_env in ( ) end and print_multiple_without_type_info t ~ state value = let formatter = state . formatter in if value_looks_like_list t value then begin if state . summary then Format . fprintf formatter " { @< error_colour [ . . . ] } " >?@ else begin print_list t ~ state ~ ty_and_env : None value ; Format . fprintf formatter " { @< error_colour } " >?@ end end else begin let need_outer_box = match state . operator_above with | Nothing -> false | _ -> true in if need_outer_box then begin Format . fprintf formatter " [ @< hov 2 " > end ; Format . fprintf formatter " { @< error_colour [ } { >@@< variable_name_colour > tag % d } :@ " ( V . tag_exn value ) ; let original_size = V . size_exn value in let max_size = if state . summary then 2 else state . max_array_elements_etc_to_print in let size , truncated = if original_size > max_size then max_size , true else original_size , false in for field = 0 to size - 1 do if field > 0 then begin Format . fprintf formatter " { @< error_colour ; } >@@ " end ; match V . field_exn value field with | None -> Format . fprintf formatter " % s " optimized_out | Some field_value -> let state = descend state ~ current_operator : Separator in Format . fprintf formatter " { @< error_colour " ; > print_value t ~ state ~ type_of_ident : None field_value ; Format . fprintf formatter " } " @ | exception D . Read_error -> Format . fprintf formatter " { @< error_colour >< field % d read failed } " >@ field done ; if truncated then begin Format . fprintf formatter " <% d elements follow " > ( original_size - max_size ) end ; Format . fprintf formatter " { @< error_colour ] } " ; >@ if need_outer_box then begin Format . fprintf formatter " ] " @ end end and print_multiple_with_type_info ? print_prefix _t ~ state ~ printers ~ current_operator ~ opening_delimiter ~ separator ~ closing_delimiter ~ spaces_inside_delimiters ~ can_elide_delimiters ~ break_after_opening_delimiter value = let formatter = state . formatter in let original_size = V . size_exn value in let max_size = if state . summary then 2 else state . max_array_elements_etc_to_print in let size , truncated = if original_size > max_size then max_size , true else original_size , false in let indent = String . length opening_delimiter + ( if spaces_inside_delimiters then 1 else 0 ) in let need_outer_box = match state . operator_above with | Nothing -> false | _ -> true in if need_outer_box then begin Format . pp_open_hovbox formatter indent end ; begin match print_prefix with | None -> ( ) | Some print_prefix -> print_prefix formatter ( ) end ; let elide_delimiters = can_elide_delimiters && size = 1 in if not elide_delimiters then begin Format . fprintf formatter " % s " opening_delimiter ; if spaces_inside_delimiters then begin Format . fprintf formatter " @ " end ; if break_after_opening_delimiter && size > 0 then begin Format . fprintf formatter " , " @ end end ; for field = 0 to size - 1 do if field > 0 then begin Format . fprintf formatter " % s @ " separator end ; match V . field_exn value field with | None -> Format . fprintf formatter " % s " optimized_out | Some field_value -> let state = descend state ~ current_operator in printers . ( field ) state field_value | exception D . Read_error -> Format . fprintf formatter " { @< error_colour >< field % d read failed } " >@ field done ; if truncated then begin Format . fprintf formatter " % s @ <% d elements follow " > separator ( original_size - max_size ) end ; if not elide_delimiters then begin if spaces_inside_delimiters && size > 1 then begin Format . fprintf formatter " @ " end ; Format . fprintf formatter " % s " closing_delimiter end ; if need_outer_box then begin Format . fprintf formatter " ] " @ end and print_int _t ~ state v = let formatter = state . formatter in match V . int v with | None -> Format . fprintf formatter " < synthetic pointer " > | Some v -> if v = Stdlib . min_int then Format . fprintf formatter " { @< variable_name_colour > Stdlib . min_int } " @ else if v = Stdlib . max_int then Format . fprintf formatter " { @< variable_name_colour > Stdlib . max_int } " @ else Format . fprintf formatter " % d " v and print_char _t ~ state v = let formatter = state . formatter in match V . int v with | None -> Format . fprintf formatter " < synthetic pointer " > | Some value -> if value >= 0 && value <= 255 then Format . fprintf formatter " ' % s ' " ( Char . escaped ( Char . chr value ) ) else match V . raw v with | Some v -> Format . fprintf formatter " % nd " v | None -> Format . fprintf formatter " < synthetic pointer " > and print_string _t ~ state v = let formatter = state . formatter in let s = V . string v in if String . length s > state . max_string_length then Format . fprintf formatter " % S " ( String . sub s 0 state . max_string_length ) ( String . length s - state . max_string_length ) else Format . fprintf formatter " % S " ( V . string v ) and print_tuple t ~ state ~ tys ~ env v = let component_types = Array . of_list tys in let size_ok = Array . length component_types = V . size_exn v in let printers = Array . map ( fun ty state v -> let type_of_ident = if size_ok then Some ( Cmt_file . Core ty , env , Is_parameter . local ) else None in print_value t ~ state ~ type_of_ident v ) component_types in print_multiple_with_type_info t ~ state ~ printers ~ current_operator : Separator ~ opening_delimiter " ( " : ~ separator " , " : ~ closing_delimiter " ) " : ~ spaces_inside_delimiters : false ~ can_elide_delimiters : true ~ break_after_opening_delimiter : false v and print_array t ~ state ~ ty ~ env v = let size = V . size_exn v in let printers = Array . init size ( fun _ty state v -> let type_of_ident = Some ( Cmt_file . Core ty , env , Is_parameter . local ) in print_value t ~ state ~ type_of_ident v ) in print_multiple_with_type_info t ~ state ~ printers ~ current_operator : Separator ~ opening_delimiter " [ " :| ~ separator " ; " : ~ closing_delimiter " ] " :| ~ spaces_inside_delimiters : true ~ can_elide_delimiters : false ~ break_after_opening_delimiter : false v and print_list t ~ state ~ ty_and_env v : unit = let formatter = state . formatter in let print_element = let state = descend state ~ current_operator : Separator in print_value t ~ state ~ type_of_ident : ty_and_env in let max_elements = if state . summary then 2 else state . max_array_elements_etc_to_print in let rec aux v ~ element_index = if V . is_block v then begin if element_index >= max_elements then Format . fprintf formatter " . . . " else begin try begin match V . field_exn v 0 with | None -> Format . fprintf formatter " < list element unavailable " > | Some elt -> print_element elt end ; begin match V . field_exn v 1 with | None -> Format . fprintf formatter " ; @ < list next pointer unavailable " > | Some next -> if V . is_block next then Format . fprintf formatter " ; @ " ; aux next ~ element_index ( : element_index + 1 ) end ; with D . Read_error -> Format . fprintf formatter " < list element read failed " > end end in let need_outer_box = match state . operator_above with | Nothing -> false | _ -> true in if need_outer_box then begin Format . fprintf formatter " [ @< hov 1 " > end ; Format . fprintf formatter " [ " ; aux v ~ element_index : 0 ; Format . fprintf formatter " ] " ; if need_outer_box then begin Format . fprintf formatter " ] " @ end and print_ref t ~ state ~ ty ~ env v = let formatter = state . formatter in let current_operator : operator = Application in maybe_parenthesise state ~ current_operator ( fun ( ) -> Format . fprintf formatter " { @< function_name_colour > ref } @ " ; match V . field_exn v 0 with | None -> Format . fprintf formatter " % s " optimized_out | Some contents -> let state = descend state ~ current_operator in print_value t ~ state ~ type_of_ident ( : Some ( Cmt_file . Core ty , env , Is_parameter . local ) ) contents ) and print_record t ~ state ~ path : _ ~ params ~ args ~ fields ~ record_repr ~ env v = let formatter = state . formatter in if state . summary then Format . fprintf formatter " { . . . } " else if List . length fields <> V . size_exn v then Format . fprintf formatter " { { @< error_colour >< expected % d fields , target has % d } } " >@ ( List . length fields ) ( V . size_exn v ) else begin let fields = Array . of_list fields in let type_for_field ~ index = begin match record_repr with | Types . Record_float -> Predef . type_float | Types . Record_regular -> let field_type = fields . ( index ) . Types . ld_type in begin try Ctype . apply env params field_type args with Ctype . Cannot_apply -> field_type end | Types . Record_extension | Types . Record_inlined _ | Types . Record_unboxed _ -> Predef . type_int end in let fields_helpers = Array . mapi ( fun index ld -> let typ = type_for_field ~ index in let printer v = let state = descend state ~ current_operator : Separator in print_value t ~ state ~ type_of_ident ( : Some ( Cmt_file . Core typ , env , Is_parameter . local ) ) v in Ident . name ld . Types . ld_id , printer ) fields in if state . depth = 0 && Array . length fields > 1 then begin Format . pp_print_newline formatter ( ) ; Format . fprintf formatter " [ @< v 2 > " end ; let nb_fields = V . size_exn v in Format . fprintf formatter " [ @< hv 0 { > " ; Format . fprintf formatter " [ @< hv 0 " ; > for field_nb = 0 to nb_fields - 1 do if field_nb > 0 then Format . fprintf formatter " @ " ; try let ( field_name , printer ) = fields_helpers . ( field_nb ) in Format . fprintf formatter " [ @< hov 2 { >@< variable_name_colour >% s } @@ =@ " field_name ; match V . field_exn v field_nb with | None -> Format . fprintf formatter " % s " optimized_out ; Format . fprintf formatter " ; ] " @ | Some v -> printer v ; Format . fprintf formatter " ; ] " @ with D . Read_error -> Format . fprintf formatter " { @< error_colour >< could not read field % d } " > field_nb done ; Format . fprintf formatter " ] ; } ] " ; @@@ if state . depth = 0 && Array . length fields > 1 then begin Format . fprintf formatter " ] " @ end end and print_closure _t ~ state ~ scrutinee : v = let formatter = state . formatter in try if state . summary then Format . fprintf formatter " < fun " > else begin match V . field_exn v 1 with | None -> Format . fprintf formatter " < fun ( code pointer unavailable ) " > | Some pc -> let pc = V . int pc in let partial , pc = match pc with | None -> None , V . field_as_addr_exn v 0 | Some arity -> if arity < 2 then None , V . field_as_addr_exn v 0 else let partial_app_pc = V . field_as_addr_exn v 0 in let pc = V . field_as_addr_exn v 2 in match D . symbol_at_pc partial_app_pc with | None -> None , pc | Some symbol -> match Naming_conventions . is_currying_wrapper symbol with | None -> None , pc | Some ( total_num_args , num_args_so_far ) -> match begin let v = ref v in for _i = 1 to num_args_so_far do if V . size_exn ! v <> 5 then raise Exit ; match V . field_exn ! v 4 with | None -> raise Exit | Some new_v -> v := new_v done ; ! v end with | exception Exit -> None , pc | v -> match V . field_exn v 1 with | None -> None , pc | Some arity -> match V . int arity with | None -> None , pc | Some arity when arity <= 1 -> None , pc | Some _arity -> Some ( total_num_args , num_args_so_far ) , V . field_as_addr_exn v 2 in let partial , partial ' , partial_args = match partial with | None -> " " , " " , " " | Some ( total_num_args , args_so_far ) -> " partial " , " partially - applied " , Printf . sprintf " ( got % d of % d args ) " args_so_far total_num_args in begin match D . symbol_at_pc pc with | None -> Format . fprintf formatter " <% sfun > ( % a ) % s " partial D . Target_memory . print_addr pc partial_args | Some symbol -> Format . fprintf formatter " % s { @< function_name_colour >% s } @% s " partial ' symbol partial_args end end with D . Read_error -> Format . fprintf formatter " < closure " ?> and print_constant_constructor _t ~ state ~ kind ~ name = let formatter = state . formatter in Format . fprintf formatter " { @< function_name_colour >% s % s } " @ ( Variant_kind . to_string_prefix kind ) name and print_non_constant_constructor t ~ state ~ path : _ ~ ctor_decls ~ params ~ instantiated_params ~ env ~ kind v = let formatter = state . formatter in let kind = Variant_kind . to_string_prefix kind in if debug then begin List . iter params ~ f ( : fun ty -> Format . fprintf formatter " param " ; >> Printtyp . reset_and_mark_loops ty ; Printtyp . type_expr formatter ty ; Format . fprintf formatter " " ) ; << List . iter instantiated_params ~ f ( : fun ty -> Format . fprintf formatter " iparam " ; >> Printtyp . reset_and_mark_loops ty ; Printtyp . type_expr formatter ty ; Format . fprintf formatter " " ) << end ; let non_constant_ctors , _ = List . fold_left ctor_decls ~ init ( [ ] , : 0 ) ~ f ( : fun ( non_constant_ctors , next_ctor_number ) ctor_decl -> let ident = ctor_decl . Types . cd_id in match ctor_decl . Types . cd_args with | Cstr_tuple [ ] -> non_constant_ctors , next_ctor_number | Cstr_tuple arg_tys -> ( next_ctor_number , ( ident , arg_tys ) ) :: non_constant_ctors , next_ctor_number + 1 | Cstr_record label_decls -> let arg_tys = List . map label_decls ~ f ( : fun ( label_decl : Types . label_declaration ) -> label_decl . ld_type ) in ( next_ctor_number , ( ident , arg_tys ) ) :: non_constant_ctors , next_ctor_number + 1 ) in let ctor_info = let tag = V . tag_exn v in try Some ( List . assoc tag non_constant_ctors ) with Not_found -> None in begin match ctor_info with | None -> print_multiple_without_type_info t ~ state v | Some ( cident , args ) -> let current_operator : operator = Application in maybe_parenthesise state ~ current_operator ( fun ( ) -> if state . summary then begin Format . fprintf formatter " % s % s ( . . . ) " kind ( Ident . name cident ) end else if List . length args <> V . size_exn v then begin Format . fprintf formatter " [ @% s % s ( { @< error_colour >< arg count mismatch , expected % d , \ heap value has % d } ) ] " >@@ kind ( Ident . name cident ) ( List . length args ) ( V . size_exn v ) end else begin let printers = let args = Array . of_list args in Array . map ( fun arg_ty state v -> let arg_ty = try Ctype . apply env params arg_ty instantiated_params with Ctype . Cannot_apply -> arg_ty in print_value t ~ state ~ type_of_ident ( : Some ( Cmt_file . Core arg_ty , env , Is_parameter . local ) ) v ) args in let print_prefix ppf ( ) = let name = Ident . name cident in Format . fprintf ppf " { @< function_name_colour >% s % s } @@ " kind name in print_multiple_with_type_info ~ print_prefix t ~ state ~ printers ~ current_operator ~ opening_delimiter " ( " : ~ separator " , " : ~ closing_delimiter " ) " : ~ spaces_inside_delimiters : false ~ can_elide_delimiters : true ~ break_after_opening_delimiter : false v end ) end and print_float _t ~ state v = let formatter = state . formatter in try Format . fprintf formatter " % f " ( V . float_field_exn v 0 ) with D . Read_error -> Format . fprintf formatter " < double read failed " > and print_float_array _t ~ state v = let formatter = state . formatter in let size = V . size_exn v in if size = 0 then Format . fprintf formatter " [ [ @| ] | ] " @ else if state . summary then Format . fprintf formatter " [ [ . . . ] ] " @||@ else begin Format . fprintf formatter " [ @< 1 [ >| " ; for i = 0 to size - 1 do Format . fprintf formatter " % f " ( V . float_field_exn v i ) ; if i < size - 1 then Format . fprintf formatter " ; ; @< 1 0 " > done ; Format . fprintf formatter " ] | ] " @ end and print_format6 _t ~ state v = if debug then begin Printf . printf " print_format6 \ n " end ; let formatter = state . formatter in let format_string : _ format6 = Our_value_copier . copy v in Format . fprintf formatter " % S " ( string_of_format format_string ) and print_custom_block _t ~ state v = let formatter = state . formatter in if V . size_exn v < 2 then Format . fprintf formatter " < malformed custom block " > else match V . field_exn v 0 with | None -> Format . fprintf formatter " < custom block ; ops pointer unavailable " > | Some custom_ops -> let identifier = V . c_string_field_exn custom_ops 0 in let data_ptr = V . field_as_addr_exn v 1 in let integer ~ suffix = match V . field_exn v 1 with | None -> Format . fprintf formatter " < Int32 . t ( unavailable ) " > | Some i -> match V . raw i with | None -> Format . fprintf formatter " < Int32 . t ( unavailable ) " > | Some i -> Format . fprintf formatter " % nd % c " i suffix in match Naming_conventions . examine_custom_block_identifier identifier with | Bigarray -> Format . fprintf formatter " < Bigarray : data at % a " > D . Target_memory . print_addr data_ptr | Systhreads_mutex -> Format . fprintf formatter " < Mutex . t % a > " D . Target_memory . print_addr data_ptr | Systhreads_condition -> Format . fprintf formatter " < Condition . t % a > " D . Target_memory . print_addr data_ptr | Int32 -> integer ~ suffix ' : l ' | Int64 -> integer ~ suffix ' : L ' | Nativeint -> integer ~ suffix ' : n ' | Channel -> Format . fprintf formatter " < channel on fd % Ld " > ( D . Target_memory . read_int64_exn data_ptr ) | Unknown -> Format . fprintf formatter " < custom block ' % s ' pointing at % a " > identifier D . Target_memory . print_addr data_ptr and print_stdlib_set t state env ~ element_ty v = let formatter = state . formatter in if state . summary then begin Format . fprintf formatter " { . . . } " end else begin Format . fprintf formatter " [ @< hov 2 { >@< function_name_colour > Stdlib . Set } @ { " ; let first = ref true in let malformed ( ) = first := false ; Format . fprintf formatter " { @< error_colour >< malformed } " >@ in let one_elt_unavailable ( ) = first := false ; Format . fprintf formatter " { @< error_colour >< one element unavailable } " >@ in let one_or_more_elts_unavailable ( ) = first := false ; Format . fprintf formatter " { @< error_colour >< one or more elements unavailable } " >@ in let elt_state = descend state ~ current_operator : Separator in let rec print v = if not ! first then begin Format . fprintf formatter " , @ " end ; if V . is_int v then begin match V . int v with | Some 0 -> ( ) | _ -> malformed ( ) end else begin match V . tag_exn v with | 0 -> begin match V . size_exn v with | 4 -> begin match V . field_exn v 0 with | exception _ -> one_or_more_elts_unavailable ( ) | None -> one_or_more_elts_unavailable ( ) | Some left -> print left end ; first := false ; begin match V . field_exn v 1 with | exception _ -> one_elt_unavailable ( ) | None -> one_elt_unavailable ( ) | Some elt -> print_value t ~ state : elt_state ~ type_of_ident ( : Some ( Cmt_file . Core element_ty , env , Is_parameter . local ) ) elt end ; begin match V . field_exn v 2 with | exception _ -> one_or_more_elts_unavailable ( ) | None -> one_or_more_elts_unavailable ( ) | Some right -> print right end | _ -> malformed ( ) end | _ -> malformed ( ) end in print v ; if not ! first then begin Format . fprintf formatter " " end ; Format . fprintf formatter " } ] " @ end and print_stdlib_map t state ~ key_env ~ key_ty ~ datum_env ~ datum_ty v = let formatter = state . formatter in if state . summary then begin Format . fprintf formatter " { . . . } " end else if V . is_int v && V . int v = Some 0 then begin Format . fprintf formatter " ( empty map ) " end else begin Format . fprintf formatter " [ @< hv 0 [ >@< hv 2 { >@< function_name_colour > Stdlib . Map } @ { @ " ; let next_row ( ) = Format . pp_force_newline formatter ( ) in let rule = " " ------------------------------ in let rule_off ( ) = Format . fprintf formatter " % s % s " rule rule ; next_row ( ) in rule_off ( ) ; ) * let next_row ( ) = ( ) in let malformed ( ) = Format . fprintf formatter " { @< error_colour >< malformed } " ; >@ next_row ( ) in let min_num_bindings = ref 0 in let one_binding_unavailable ( ) = incr min_num_bindings ; Format . fprintf formatter " { @< error_colour >< one binding unavailable } " ; >@ next_row ( ) in let one_or_more_bindings_unavailable ( ) = incr min_num_bindings ; Format . fprintf formatter " { @< error_colour >< one or more bindings unavailable } " ; >@ next_row ( ) in let binding_state = descend state ~ current_operator : Separator in let rec print v = if V . is_int v then begin match V . int v with | Some 0 -> ( ) | _ -> malformed ( ) end else begin match V . tag_exn v with | 0 -> begin match V . size_exn v with | 5 -> begin match V . field_exn v 0 with | exception _ -> one_or_more_bindings_unavailable ( ) | None -> one_or_more_bindings_unavailable ( ) | Some left -> print left end ; begin match V . field_exn v 1 with | exception _ -> one_binding_unavailable ( ) | None -> one_binding_unavailable ( ) | Some key -> match V . field_exn v 2 with | exception _ -> one_binding_unavailable ( ) | None -> one_binding_unavailable ( ) | Some datum -> if ! min_num_bindings > 0 then begin Format . fprintf formatter " @ " end ; incr min_num_bindings ; Format . fprintf formatter " [ @< hov 2 " ; > print_value t ~ state : binding_state ~ type_of_ident ( : Some ( Cmt_file . Core key_ty , key_env , Is_parameter . local ) ) key ; Format . fprintf formatter " { @< file_name_colour } >==>@@ " ; print_value t ~ state : binding_state ~ type_of_ident ( : Some ( Cmt_file . Core datum_ty , datum_env , Is_parameter . local ) ) datum ; Format . fprintf formatter " ; ] " ; @ end ; begin match V . field_exn v 3 with | exception _ -> one_or_more_bindings_unavailable ( ) | None -> one_or_more_bindings_unavailable ( ) | Some right -> print right end | _ -> malformed ( ) end | _ -> malformed ( ) end in print v ; Format . fprintf formatter " ] ; ] } " ; @@@ end and print_stdlib_hashtbl t state ~ key_env ~ key_ty ~ datum_env ~ datum_ty v = let formatter = state . formatter in let binding_state = descend state ~ current_operator : Separator in let first = ref true in let rec print_bucket_list bucket_list = if V . is_int bucket_list then match V . int bucket_list with | Some 0 -> ( ) | _ -> Format . fprintf formatter " { @< error_colour } >< bucket list malformed " > else match V . tag_exn bucket_list with | exception _ -> Format . fprintf formatter " { @< error_colour } >< bucket list tag read failed " > | 0 -> begin match V . size_exn bucket_list with | exception _ -> Format . fprintf formatter " { @< error_colour } >< bucket list size read failed " > | 3 -> if not ! first then begin Format . fprintf formatter " @ " ; end ; first := false ; Format . fprintf formatter " [ @< hov 2 " ; > begin match V . field_exn bucket_list 0 with | exception Not_found -> Format . fprintf formatter " { @< error_colour } >< key read failed " > | None -> Format . fprintf formatter " { @< error_colour } >< key unavailable " > | Some key -> print_value t ~ state : binding_state ~ type_of_ident ( : Some ( Cmt_file . Core key_ty , key_env , Is_parameter . local ) ) key end ; Format . fprintf formatter " { @< file_name_colour } >==>@@ " ; begin match V . field_exn bucket_list 1 with | exception Not_found -> Format . fprintf formatter " { @< error_colour } >< datum read failed " > | None -> Format . fprintf formatter " { @< error_colour } >< datum unavailable " > | Some datum -> print_value t ~ state : binding_state ~ type_of_ident ( : Some ( Cmt_file . Core datum_ty , datum_env , Is_parameter . local ) ) datum end ; Format . fprintf formatter " ] " ; @ begin match V . field_exn bucket_list 2 with | exception Not_found -> Format . fprintf formatter " { @< error_colour } >< next read failed " > | None -> Format . fprintf formatter " { @< error_colour } >< next unavailable " > | Some next -> print_bucket_list next end ; | _size -> Format . fprintf formatter " { @< error_colour } >< bucket list has wrong size " > end | _tag -> Format . fprintf formatter " { @< error_colour } >< bucket list has wrong tag " > in if state . summary then begin Format . fprintf formatter " { . . . } " end else begin if not ( V . is_block v ) then begin Format . fprintf formatter " { @< error_colour >< malformed Stdlib . Hashtbl ( not a block ) } " >@ end else begin match V . tag_exn v with | 0 -> begin match V . size_exn v with | 4 -> begin match V . field_exn v 1 with | exception _ -> Format . fprintf formatter " { @< error_colour >< Stdlib . Hashtbl ( target read failed ) } " >@ | None -> Format . fprintf formatter " { @< error_colour >< Stdlib . Hashtbl ( unavailable ) } " >@ | Some data -> Format . fprintf formatter " [ @< hv 0 { >@< function_name_colour > Stdlib . Hashtbl } @ { " ; Format . fprintf formatter " [ @< hv 0 " ; > begin match V . size_exn data with | exception _ -> Format . fprintf formatter " { @< error_colour >< Stdlib . Hashtbl ( target read failed \ on size ) } " >@ | size -> for data_index = 0 to size - 1 do match V . field_exn data data_index with | exception _ -> Format . fprintf formatter " { @< error_colour } >< bucket list read failed " > | None -> Format . fprintf formatter " { @< error_colour } >< bucket list unavailable " > | Some bucket_list -> print_bucket_list bucket_list done end ; Format . fprintf formatter " ] ; } ] " @@@ end | _ -> Format . fprintf formatter " { @< error_colour >< malformed Stdlib . Hashtbl ( wrong size ) } " >@ end | _ -> Format . fprintf formatter " { @< error_colour >< malformed Stdlib . Hashtbl ( wrong tag ) } " >@ end end and print_module t state env ( mod_ty : Types . module_type ) v = let formatter = state . formatter in let sg = match mod_ty with | Mty_signature sg -> Some sg | Mty_ident _ | Mty_functor _ | Mty_alias _ -> None in match state . summary , sg with | true , _ | _ , None -> Format . fprintf formatter " < module block " > | _ , Some sg -> assert ( V . is_block v ) ; let actual_module_block_size = V . size_exn v in if state . depth = 0 && actual_module_block_size > 1 then begin Format . pp_print_newline formatter ( ) ; Format . fprintf formatter " [ @< v 2 > " end ; Format . fprintf formatter " [ @< hv 2 > struct @ " ; let rec print_sig_items ~ pos ~ first ~ in_type_group env ( sig_items : Types . signature_item list ) = match sig_items with | [ ] -> ( ) | ( sig_item :: sig_items ) as sig_items ' -> let in_type_group = Printtyp . still_in_type_group env in_type_group sig_item in let sg , sig_items = Printtyp . filter_rem_sig sig_item sig_items in Printtyp . hide_rec_items sig_items ' ; Printtyp . protect_rec_items sig_items ' ; Printtyp . reset_naming_context ( ) ; let env = Env . add_signature ( sig_item :: sg ) env in let pos , first = match pos with | None -> None , first | Some pos -> if pos >= actual_module_block_size then begin Format . fprintf formatter " { @< error_colour >< module block at % a \ has % d fields but expected at least % d } " > V . print v actual_module_block_size ( pos + 1 ) ; None , first end else begin if not first then begin Format . fprintf formatter " ; " @ end ; let print_ident ( ? print_type = fun _ppf ( ) -> ( ) ) what ident = Format . fprintf formatter " [ @< hov 2 >% s { @< variable_name_colour >% s } @% a @ =@ " what ( Ident . name ident ) print_type ( ) in let print_field_raw ( ) = try match V . field_exn v pos with | None -> Format . fprintf formatter " % s " optimized_out | Some v -> Format . fprintf formatter " % a " V . print v with D . Read_error -> Format . fprintf formatter " { @< error_colour >< could not read field % d \ of module block } " > pos in let print_field ty = try match V . field_exn v pos with | None -> Format . fprintf formatter " % s " optimized_out | Some v -> let state = descend state ~ current_operator : Separator in let type_of_ident = match ty with | None -> None | Some ty -> Some ( ty , env , Is_parameter . local ) in print_value t ~ state ~ type_of_ident v with D . Read_error -> Format . fprintf formatter " { @< error_colour >< could not read field % d \ of module block } " > pos in let next_pos = match sig_item with | Sig_value ( ident , { val_type ; val_kind ; _ } ) -> print_ident ~ print_type ( : fun formatter ( ) -> Format . fprintf formatter " @ : { @< type_colour >% a } " @ Printtyp . type_scheme val_type ) " let " ident ; let ty : Cmt_file . core_or_module_type = Core val_type in print_field ( Some ty ) ; begin match val_kind with | Val_prim _ -> pos | _ -> pos + 1 end | Sig_typext ( ident , ctor_decl , _ ) -> Format . fprintf formatter " [ @< hov 2 { >@< type_colour >% a } @ = " ( Printtyp . extension_constructor ident ) ctor_decl ; print_field_raw ( ) ; Format . fprintf formatter " =@ " ; print_field None ; pos + 1 | Sig_module ( ident , { md_type ; _ } , _ ) -> print_ident " module " ident ; let ty : Cmt_file . core_or_module_type = Module md_type in print_field ( Some ty ) ; pos + 1 | Sig_class ( ident , _ , _ ) -> print_ident " class " ident ; pos + 1 | Sig_type ( ident , type_decl , _ ) -> Format . fprintf formatter " [ @< hov 2 { >@< type_colour >% a } " @ ( Printtyp . type_declaration ident ) type_decl ; pos | Sig_modtype ( ident , mod_type_decl ) -> Format . fprintf formatter " [ @< hov 2 { >@< type_colour >% a } " @ ( Printtyp . modtype_declaration ident ) mod_type_decl ; pos | Sig_class_type ( ident , class_type_decl , _ ) -> Format . fprintf formatter " [ @< hov 2 { >@< type_colour >% a } " @ ( Printtyp . cltype_declaration ident ) class_type_decl ; pos in Format . fprintf formatter " ] " ; @ Some next_pos , false end in print_sig_items ~ pos ~ first ~ in_type_group env sig_items in Printtyp . wrap_env ( fun env -> env ) ( fun sg -> print_sig_items ~ pos ( : Some 0 ) ~ first : true ~ in_type_group : false env sg ) sg ; Format . fprintf formatter " ] @@ end " ; if state . depth = 0 && actual_module_block_size > 1 then begin Format . fprintf formatter " ] " @ end let print_short_value t ~ state ~ type_of_ident : type_and_env v : unit = let formatter = state . formatter in match Our_type_oracle . find_type_information t . type_oracle ~ formatter type_and_env ~ scrutinee : v with | Obj_immediate -> Format . fprintf formatter " unboxed " | Obj_immediate_but_should_be_boxed -> if V . int v = Some 0 then Format . fprintf formatter " unboxed / uninited " else Format . fprintf formatter " unboxed ( ) " ? | Obj_boxed_traversable -> Format . fprintf formatter " boxed " | Obj_boxed_not_traversable -> Format . fprintf formatter " boxed - not - trav . " | Int -> begin match V . int v with | Some i -> Format . fprintf formatter " % d " i | None -> Format . fprintf formatter " unavailable " end | Char -> print_char t ~ state v | Unit -> Format . fprintf formatter " ( ) " | Abstract _ -> Format . fprintf formatter " abstract " | Array _ -> Format . fprintf formatter " [ | . . . ] " | | List _ when not ( V . is_block v ) && not ( V . is_null v ) -> Format . fprintf formatter " [ ] " | List _ -> Format . fprintf formatter " [ . . . ] " | Ref _ -> Format . fprintf formatter " ref . . . " | Tuple _ -> Format . fprintf formatter " ( . . . ) " | Constant_constructor _ -> Format . fprintf formatter " variant " | Non_constant_constructor _ -> Format . fprintf formatter " variant " | Record _ -> Format . fprintf formatter " { . . . } " | Open -> Format . fprintf formatter " open " | String -> print_string t ~ state { : state with max_string_length = 10 ; } v | Float -> print_float t ~ state v | Float_array -> Format . fprintf formatter " [ | . . . ] " | | Closure -> Format . fprintf formatter " function " | Lazy -> Format . fprintf formatter " lazy " | Object -> Format . fprintf formatter " object " | Abstract_tag -> Format . fprintf formatter " abstract - tag " | Format6 -> Format . fprintf formatter " format6 " | Stdlib_set _ -> Format . fprintf formatter " Stdlib . Set " | Stdlib_map _ -> Format . fprintf formatter " Stdlib . Map " | Stdlib_hashtbl _ -> Format . fprintf formatter " Stdlib . Hashtbl " | Custom -> Format . fprintf formatter " custom " | Module _ -> Format . fprintf formatter " < module block " > | Unknown -> Format . fprintf formatter " unknown " let print_short_type t ~ state ~ type_of_ident : type_and_env v : unit = let formatter = state . formatter in match Our_type_oracle . find_type_information t . type_oracle ~ formatter type_and_env ~ scrutinee : v with | Obj_immediate -> Format . fprintf formatter " unboxed " | Obj_immediate_but_should_be_boxed -> if V . int v = Some 0 then Format . fprintf formatter " unboxed / uninited " else Format . fprintf formatter " unboxed ( ) " ? | Obj_boxed_traversable -> Format . fprintf formatter " boxed " | Obj_boxed_not_traversable -> Format . fprintf formatter " boxed - not - trav . " | Int -> begin match V . int v with | Some _ -> Format . fprintf formatter " int " | None -> Format . fprintf formatter " int ( ) " ? end | Char -> Format . fprintf formatter " char " | Unit -> Format . fprintf formatter " unit " | Abstract _ -> Format . fprintf formatter " abstract " | Array _ -> Format . fprintf formatter " array " | List _ -> Format . fprintf formatter " list " | Ref _ -> Format . fprintf formatter " ref " | Tuple _ -> Format . fprintf formatter " tuple " | Constant_constructor _ -> Format . fprintf formatter " variant " | Non_constant_constructor _ -> Format . fprintf formatter " variant " | Record _ -> Format . fprintf formatter " record " | Open -> Format . fprintf formatter " open " | String -> Format . fprintf formatter " string " | Float -> Format . fprintf formatter " float " | Float_array -> Format . fprintf formatter " float array " | Closure -> Format . fprintf formatter " function " | Lazy -> Format . fprintf formatter " lazy " | Object -> Format . fprintf formatter " object " | Abstract_tag -> Format . fprintf formatter " abstract - tag " | Format6 -> Format . fprintf formatter " format6 " | Stdlib_set _ -> Format . fprintf formatter " Stdlib . Set " | Stdlib_map _ -> Format . fprintf formatter " Stdlib . Map " | Stdlib_hashtbl _ -> Format . fprintf formatter " Stdlib . Hashtbl " | Custom -> Format . fprintf formatter " custom " | Module _ -> Format . fprintf formatter " < module " > | Unknown -> Format . fprintf formatter " unknown " let print t frame ~ scrutinee ~ dwarf_type ~ summary ~ max_depth ~ max_string_length ~ cmt_file_search_path : _ ~ formatter ~ only_print_short_type ~ only_print_short_value = Clflags . real_paths := false ; D . with_formatter_margins formatter ~ summary ( fun formatter -> if debug then begin Format . printf " Value_printer . print % a type % s \ n " %! V . print scrutinee dwarf_type end ; let type_of_ident = match Cmt_cache . find_cached_type t . cmt_cache ~ cached_type : dwarf_type with | Some type_and_env -> Some type_and_env | None -> Type_helper . type_and_env_from_dwarf_type ~ dwarf_type ~ cmt_cache : t . cmt_cache frame in let is_unit = match type_of_ident with | None | Some ( Module _ , _ , _ ) -> false | Some ( Core ty , _env , _ ) -> match ty . desc with | Tconstr ( path , _ , _ ) -> Path . same path Predef . path_unit | _ -> false in if V . is_null scrutinee && ( not only_print_short_type ) && ( not is_unit ) then begin Format . fprintf formatter " % s " optimized_out ; Format . pp_print_flush formatter ( ) end else begin if debug then Printf . printf " Value_printer . print entry point \ n " ; %! let state = { summary ; depth = 0 ; max_depth ; max_string_length ; print_sig = true ; formatter ; max_array_elements_etc_to_print = 10 ; only_print_short_type ; only_print_short_value ; operator_above = Nothing ; visited = V . Set . empty ; } in let env = match type_of_ident with | None -> Env . empty | Some ( _ , env , _ ) -> env in Printtyp . wrap_printing_env ~ error : false env ( fun ( ) -> if only_print_short_type then begin let type_of_ident = match type_of_ident with | None -> None | Some ( ty , env , _ ) -> Some ( ty , env ) in print_short_type t ~ state ~ type_of_ident scrutinee end else if only_print_short_value then begin let type_of_ident = match type_of_ident with | None -> None | Some ( ty , env , _ ) -> Some ( ty , env ) in print_short_value t ~ state ~ type_of_ident scrutinee end else begin Format . fprintf formatter " [ @< hov 2 " ; > print_value t ~ state ~ type_of_ident scrutinee ; Format . fprintf formatter " ] " @ end ) ; Format . pp_print_flush formatter ( ) end ) end
type ' a t = { symbol : Symbol . t ; type_ : ' a Value . Type . t }
let sexp_of_t _ { symbol ; type_ } = [ % message " " ~ _ ( : symbol : Symbol . t ) ~ _ ( : type_ : _ Value . Type . t ) ] ; ;
type ' a var = ' a t [ @@ deriving sexp_of ]
let create symbol type_ = { symbol ; type_ = Value . Type . with_of_value_exn type_ ( fun value -> try Value . Type . of_value_exn type_ value with | exn -> raise_s [ % message " " ~ _ ( : concat [ " invalid value for variable : " ; symbol |> Symbol . name ] ) ~ _ ( : exn : exn ) ] ) } ; ;