text
stringlengths
12
786k
let update_sequence_state = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state ( ) = let open Deferred . Let_syntax in let % map parties = update_sequence_state ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates zkApp state " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and sequence_state0 = Param . flag " -- sequence - state0 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . required ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state1 = Param . flag " -- sequence - state1 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state2 = Param . flag " -- sequence - state2 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state3 = Param . flag " -- sequence - state3 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) in let fee = Option . value ~ default : Flags . default_fee fee in let sequence_state = List . filter_map ~ f ( : fun s -> if List . is_empty s then None else Some ( Array . of_list s ) s ) s [ sequence_state0 ; sequence_state1 ; sequence_state2 ; sequence_state3 ] in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state ) )
let update_token_symbol = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth ( ) = let open Deferred . Let_syntax in let % map parties = update_token_symbol ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates token symbol " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and snapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and token_symbol = Param . flag " -- token - symbol " ~ doc " : TOKEN_SYMBOL The string to be used as the updated token symbol " Param ( . required string ) string and auth = Param . flag " -- auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change the token symbol " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let auth = Util . auth_of_string auth in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth ) )
let update_permissions = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth ( ) = let open Deferred . Let_syntax in let % map parties = update_permissions ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary : " Generate a zkApp transaction that updates the permissions of a zkApp \ account " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and edit_state = Param . flag " -- edit - state " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and send = Param . flag " -- send " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and receive = Param . flag " -- receive " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_permissions = Param . flag " -- set - permissions " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_delegate = Param . flag " -- set - delegate " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_verification_key = Param . flag " -- set - verification - key " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_zkapp_uri = Param . flag " -- set - zkapp - uri " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and edit_sequence_state = Param . flag " -- set - sequence - state " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_token_symbol = Param . flag " -- set - token - symbol " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and increment_nonce = Param . flag " -- increment - nonce " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_voting_for = Param . flag " -- set - voting - for " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and current_auth = Param . flag " -- current - auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change permissions " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let permissions : Permissions . t Zkapp_basic . Set_or_keep . t = Zkapp_basic . Set_or_keep . Set { Permissions . Poly . edit_state = Util . auth_of_string edit_state ; send = Util . auth_of_string send ; receive = Util . auth_of_string receive ; set_permissions = Util . auth_of_string set_permissions ; set_delegate = Util . auth_of_string set_delegate ; set_verification_key = Util . auth_of_string set_verification_key ; set_zkapp_uri = Util . auth_of_string set_zkapp_uri ; edit_sequence_state = Util . auth_of_string edit_sequence_state ; set_token_symbol = Util . auth_of_string set_token_symbol ; increment_nonce = Util . auth_of_string increment_nonce ; set_voting_for = Util . auth_of_string set_voting_for } in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth ( : Util . auth_of_string current_auth ) current_auth ) )
let test_zkapp_with_genesis_ledger = Command ( . let open Let_syntax in Command . async ~ summary : " Generate a trivial zkApp transaction and genesis ledger with \ verification key for testing " ( let % map keyfile = Param . flag " -- fee - payer - key " ~ doc : " KEYFILE Private key file for the fee payer of the transaction \ ( should be in the genesis ledger ) ledger " Param ( . required string ) string and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file to create a new zkApp account " Param ( . required string ) string and config_file = Param . flag " -- config - file " ~ aliases [ : " config - file " ] ~ doc : " PATH path to a configuration file consisting the genesis ledger " Param ( . required string ) string in test_zkapp_with_genesis_ledger_main keyfile zkapp_keyfile config_file ) )
let txn_commands = [ ( " create - zkapp - account " , create_zkapp_account ) create_zkapp_account ; ( " upgrade - zkapp " , upgrade_zkapp ) upgrade_zkapp ; ( " transfer - funds " , transfer_funds ) transfer_funds ; ( " update - state " , update_state ) update_state ; ( " update - zkapp - uri " , update_zkapp_uri ) update_zkapp_uri ; ( " update - sequence - state " , update_sequence_state ) update_sequence_state ; ( " update - token - symbol " , update_token_symbol ) update_token_symbol ; ( " update - permissions " , update_permissions ) update_permissions ; ( " test - zkapp - with - genesis - ledger " , test_zkapp_with_genesis_ledger ) test_zkapp_with_genesis_ledger ]
let ( ) = Command . run ( Command . group ~ summary " : ZkApp test transaction " ~ preserve_subcommand_order ( ) : txn_commands )
let crc_table = Array . init 256 ( fun n -> let crc = ref ( Int32 . of_int n ) n in for j = 0 to 7 do crc := if Int32 . to_int ( Int32 . logand ( ! crc ) crc 1l ) 1l <> 0 then Int32 . logxor ( Int32 . shift_right_logical ( ! crc ) crc 1 ) 1 polynom else Int32 . shift_right_logical ( ! crc ) crc 1 ; done ; ! crc ) crc
let compress ( ? level = 6 ) 6 ( ? header = true ) true refill flush = let inbuf = Bytes . create buffer_size and outbuf = Bytes . create buffer_size in let zs = Extc . zlib_deflate_init2 level ( if header then max_wbits else - max_wbits ) max_wbits in let rec compr inpos inavail = if inavail = 0 then begin let incount = refill inbuf in if incount = 0 then compr_finish ( compr_finish ) compr_finish else compr 0 incount end else begin let res = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_NO_FLUSH in let used_in , used_out = res . z_read , res . z_wrote in flush outbuf used_out ; compr ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and compr_finish ( ) = let ret = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : 0 ~ slen : 0 ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_FINISH in let ( finished , _ , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then compr_finish ( compr_finish ) compr_finish in compr 0 0 ; Extc . zlib_deflate_end zs
let compress_direct ( ? level = 6 ) 6 ( ? header = true ) true flush = let outbuf = Bytes . create buffer_size in let zs = Extc . zlib_deflate_init2 level ( if header then max_wbits else - max_wbits ) max_wbits in let rec compr inbuf inpos inavail = if inavail = 0 then ( ) else begin let res = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_NO_FLUSH in let used_in , used_out = res . z_read , res . z_wrote in flush outbuf used_out ; compr inbuf ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and compr_finish ( ) = let ret = Extc . zlib_deflate zs ~ src " " : ~ spos : 0 ~ slen : 0 ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_FINISH in let ( finished , _ , used_out ) used_out = ret . z_finish , ( ) , ret . z_wrote in flush outbuf used_out ; if not finished then compr_finish ( compr_finish ) compr_finish in compr , compr_finish
let uncompress ( ? header = true ) true refill flush = let inbuf = Bytes . create buffer_size and outbuf = Bytes . create buffer_size in let zs = Extc . zlib_inflate_init2 ( if header then max_wbits else - max_wbits ) max_wbits in let rec uncompr inpos inavail = if inavail = 0 then begin let incount = refill inbuf in if incount = 0 then uncompr_finish true else uncompr 0 incount end else begin let ret = Extc . zlib_inflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_SYNC_FLUSH in let ( finished , used_in , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then uncompr ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and uncompr_finish first_finish = let dummy_byte = if first_finish && not header then 1 else 0 in let ret = Extc . zlib_inflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : 0 ~ slen : dummy_byte ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_SYNC_FLUSH in let ( finished , _ , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then uncompr_finish false in uncompr 0 0 ; Extc . zlib_inflate_end zs
let update_crc crc buf pos len = let c = ref ( Int32 . lognot crc ) crc in for i = pos to ( len + pos - 1 ) 1 do let b = Int32 . of_int ( int_of_char ( Bytes . get buf i ) i ) i in c := Int32 . logxor ( Array . get crc_table ( Int32 . to_int ( Int32 . logand ( Int32 . logxor ! c b ) b 0xFFl ) 0xFFl ) 0xFFl ) 0xFFl ( Int32 . shift_right_logical ! c 8 ) 8 ; done ; let ret = Int32 . lognot ! c in ret
type location = Loc of int * int
let input_name = ref " "
let input_chan = ref stdin
let initialize iname = input_name := iname ; input_chan := open_in iname
let output_lines ff char1 char2 charline1 line1 line2 = let n1 = char1 - charline1 and n2 = char2 - charline1 in if line2 > line1 then fprintf ff " , line % d -% d , characters % d -% d :\ n " line1 line2 n1 n2 else fprintf ff " , line % d , characters % d -% d :\ n " line1 n1 n2 ; ( )
let output_loc ff input seek line_flag ( Loc ( pos1 , pos2 ) ) = let pr_chars n c = for i = 1 to n do pp_print_char ff c done in let skip_line ( ) = try while input ( ) != ' \ n ' do ( ) done with End_of_file -> ( ) in let copy_line ( ) = let c = ref ' ' in begin try while c := input ( ) ; ! c != ' \ n ' do pp_print_char ff ! c done with End_of_file -> pp_print_string ff " < EOF " > end ; pp_print_char ff ' \ n ' in let pr_line first len ch = let c = ref ' ' and f = ref first and l = ref len in try while c := input ( ) ; ! c != ' \ n ' do if ! f > 0 then begin f := ! f - 1 ; pp_print_char ff ( if ! c == ' \ t ' then ! c else ' ' ) end else if ! l > 0 then begin l := ! l - 1 ; pp_print_char ff ( if ! c == ' \ t ' then ! c else ch ) end else ( ) done with End_of_file -> if ! f = 0 && ! l > 0 then pr_chars 5 ch in let pos = ref 0 and line1 = ref 1 and line1_pos = ref 0 and line2 = ref 1 and line2_pos = ref 0 in seek 0 ; begin try while ! pos < pos1 do incr pos ; if input ( ) == ' \ n ' then begin incr line1 ; line1_pos := ! pos ; ( ) end done with End_of_file -> ( ) end ; line2 := ! line1 ; line2_pos := ! line1_pos ; begin try while ! pos < pos2 do incr pos ; if input ( ) == ' \ n ' then begin incr line2 ; line2_pos := ! pos ; ( ) end done with End_of_file -> ( ) end ; if line_flag then output_lines ff pos1 pos2 ! line1_pos ! line1 ! line2 ; if ! line1 == ! line2 then begin seek ! line1_pos ; pp_print_string ff error_prompt ; copy_line ( ) ; seek ! line1_pos ; pp_print_string ff error_prompt ; pr_line ( pos1 - ! line1_pos ) ( pos2 - pos1 ) ' ' ; ^ pp_print_char ff ' \ n ' end else begin seek ! line1_pos ; pp_print_string ff error_prompt ; pr_line 0 ( pos1 - ! line1_pos ) ' . ' ; seek pos1 ; copy_line ( ) ; if ! line2 - ! line1 <= 8 then for i = ! line1 + 1 to ! line2 - 1 do pp_print_string ff error_prompt ; copy_line ( ) done else begin for i = ! line1 + 1 to ! line1 + 3 do pp_print_string ff error_prompt ; copy_line ( ) done ; pp_print_string ff error_prompt ; pp_print_string ff " . . . . . . . . . . \ n " ; for i = ! line1 + 4 to ! line2 - 4 do skip_line ( ) done ; for i = ! line2 - 3 to ! line2 - 1 do pp_print_string ff error_prompt ; copy_line ( ) done end ; begin try pp_print_string ff error_prompt ; for i = ! line2_pos to pos2 - 1 do pp_print_char ff ( input ( ) ) done ; pr_line 0 100 ' . ' with End_of_file -> pp_print_string ff " < EOF " > end ; pp_print_char ff ' \ n ' end
let output_location ff loc = let p = pos_in ! input_chan in fprintf ff " File " \% s " " \ ! input_name ; output_loc ff ( fun ( ) -> input_char ! input_chan ) ( seek_in ! input_chan ) true loc ; seek_in ! input_chan p
let output_input_name ff = fprintf ff " File " \% s " , \ line 1 :\ n " ! input_name
type carray = ( float , float64_elt , c_layout ) Array1 . t
type zarray = ( int32 , int32_elt , c_layout ) Array1 . t
let cmake n = let r = Array1 . create float64 c_layout n in Array1 . fill r 0 . 0 ; r
let zmake n = let r = Array1 . create int32 c_layout n in Array1 . fill r 0l ; r
let get_zin v i = Array1 . get v i <> 0l
let zzero zinvec length = for i = 0 to length - 1 do Array1 . set zinvec i 0l done
type ' s f_alloc = unit -> ' s
type ' s f_maxsize = ' s -> int * int
type ' s f_csize = ' s -> int
type ' s f_zsize = ' s -> int
type ( ' s , ' o ) f_step = ' s -> carray -> carray -> zarray -> float -> ' o
type ' s f_ders = ' s -> carray -> carray -> zarray -> carray -> float -> unit
type ' s f_zero = ' s -> carray -> zarray -> carray -> float -> unit
type ' s f_reset = ' s -> unit
type ' s f_horizon = ' s -> float
let time_eq f1 f2 = if abs_float ( f1 . - f2 ) < min_float then true else let rel_error = if abs_float f1 > abs_float f2 then abs_float ( ( f1 . - f2 ) . / f1 ) else abs_float ( ( f1 . - f2 ) . / f2 ) in ( rel_error <= 0 . 000001 )
let time_leq t1 t2 = t1 < t2 || time_eq t1 t2
let time_geq t1 t2 = t1 > t2 || time_eq t1 t2
module type STATE_SOLVER = sig type t type nvec val cmake : int -> nvec val unvec : nvec -> carray type rhsfn = float -> carray -> carray -> unit type dkyfn = nvec -> float -> int -> unit val initialize : rhsfn -> nvec -> t val reinitialize : t -> float -> nvec -> unit val step : t -> float -> nvec -> float val get_dky : t -> dkyfn val set_stop_time : t -> float -> unit val set_min_step : t -> float -> unit val set_max_step : t -> float -> unit val set_tolerances : t -> float -> float -> unit end
module type STATE_SOLVER_SENS = sig include STATE_SOLVER type sensmat val smake : int -> int -> sensmat val arrays_of_sensmat : sensmat -> float array array type rhsfn = carray -> float -> carray -> carray -> unit type dkysensfn = sensmat -> float -> int -> unit val initialize : rhsfn -> carray -> nvec -> sensmat -> t val reinitialize : t -> float -> nvec -> sensmat -> unit val get_sens_dky : t -> dkysensfn end
module type ZEROC_SOLVER = sig type t type zcfn = float -> carray -> carray -> unit val initialize : int -> zcfn -> carray -> t val initialize_only : int -> zcfn -> carray -> t val reinitialize : t -> float -> carray -> unit val step : t -> float -> carray -> unit val takeoff : t -> bool val has_roots : t -> bool val find : t -> ( ( float -> int -> unit ) * carray ) -> zarray -> float end
module type RUNTIME = sig val go : unit hsimu -> unit val check : bool hsimu -> int -> unit end
module type DISCRETE_RUNTIME = sig val go : float -> ( unit -> unit ) -> unit end
type file_kind = ZLS | ZLI ; ;
let file_dependencies_as kind source_file = try if Sys . file_exists source_file then begin match kind with | ZLS -> zls_file_dependencies source_file | ZLI -> zli_file_dependencies source_file end with x -> let report_err = function | Zlexer . Lexical_error ( err , range ) -> lexical_error err range | Zparser . Error -> ( ) | Sys_error msg -> fprintf Format . err_formatter " [ @ I / O error :@ % s ] . " @@ msg | Preprocessing_error -> fprintf Format . err_formatter " [ @ Preprocessing error on file % s ] . " @@ source_file | x -> raise x in error_occurred := true ; report_err x
let file_dependencies source_file = if Filename . check_suffix source_file " . zls " then file_dependencies_as ZLS source_file else if Filename . check_suffix source_file " . zli " then file_dependencies_as ZLI source_file else ( )
let usage = " Usage : zlsdep [ options ] < source files >\ nOptions are " :
let _ = try add_to_load_path Filename . current_dir_name ; Arg . parse [ " - I " , Arg . String add_to_load_path , " < dir > Add < dir > to the list of include directories " ; " - impl " , Arg . String ( file_dependencies_as ZLS ) , " < f > Process < f > as a . zls file " ; " - intf " , Arg . String ( file_dependencies_as ZLI ) , " < f > Process < f > as a . zli file " ; " - pp " , Arg . String ( fun s -> preprocessor := Some s ) , " < cmd > Pipe sources through preprocessor < cmd " ; > " - slash " , Arg . Set force_slash , " ( Windows ) Use forward slash / instead of backslash \\ in file paths " ; ] file_dependencies usage ; exit ( if ! error_occurred then 2 else 0 ) with | Zmisc . Error -> exit 2 ; ;
sig val enable_logging : unit -> unit val min_step_size : float option ref val max_step_size : float option ref val max_sim_time : float option ref val speedup : float ref val step : ' s Zls . f_alloc -> ' s Zls . f_csize -> ' s Zls . f_zsize -> ' s Zls . f_horizon -> ' s Zls . f_maxsize -> ' s Zls . f_ders -> ( ' s , ' o ) Zls . f_step -> ' s Zls . f_zero -> ' s Zls . f_reset -> ( unit -> ' o option * bool * float )
module Make ( SSolver : Zls . STATE_SOLVER ) ( ZSolver : Zls . ZEROC_SOLVER ) = let no_time_in_solver = - 1 . 0 let add_margin h = h . + ( 2 . 0 . * epsilon_float . * h ) let max_sim_time = ref None let min_step_size = ref None let max_step_size = ref None let always_reinit = ref true let precise_logging = ref false let color_logging = ref true let max_c_step = ref 100 . 0 let rel_tol = ref ( None : float option ) let abs_tol = ref ( None : float option ) let log = ref false let log_gcalls = ref false let log_fcalls = ref false let log_dcalls = ref false let show_stats = ref false let speedup = ref 1 . 0 let enable_logging ( ) = ( log := true ) let set_param set_fn s param = ( match ! param with Some v -> set_fn s v | _ -> ( ) ) let set_param2 set_fn s param1 param2 = ( match ! param1 , ! param2 with Some v1 , Some v2 -> set_fn s v1 v2 | _ -> ( ) ) let set_color s = if ! color_logging then print_string s let set_err_color s = if ! color_logging then prerr_string s let print_time ( s1 , s2 ) t = if ! precise_logging then Printf . printf " % s . % 15e % s " s1 t s2 else Printf . printf " % s % e % s " s1 t s2 let print_black_newline ( ) = set_color black ; print_newline ( ) ; flush stdout let print_black_endline s = print_string s ; print_black_newline ( ) let carray_log l t c = let pr = if ! precise_logging then printf " \ t % . 15e " else printf " \ t % e " in if ! precise_logging then printf " % s . % 15e " l t else printf " % s % e " l t ; for i = 0 to Bigarray . Array1 . dim c - 1 do pr c . { i } done ; print_black_newline ( ) let zarray_log l t z = if ! precise_logging then printf " % s . % 15e " l t else printf " % s % e " l t ; for i = 0 to Bigarray . Array1 . dim z - 1 do printf " \ t % s " ( Int32 . to_string z . { i } ) done ; print_black_newline ( ) let print_roots zs t rin = if ! log then ( set_color boldred ; zarray_log " Z : " t rin ) let print_states label t cs = if ! log then carray_log label t cs let print_horizon t t_horizon reinit = if ! log then begin set_color yellow ; print_time ( " H : " , " " ) t ; print_time ( " \ t horizon " , = if reinit then " ( reinit ) " else " " ) t_horizon ; print_black_newline ( ) end let print_help_key ( ) = if ! log then begin print_endline " " ; print_endline " I : initial solver state " ; print_endline " C : result of continuous solver " ; print_endline " C ' : state given to the discrete solver ( last values ) " ; set_color boldred ; print_black_endline " Z : zero - crossings triggering the discrete solver " ; print_endline " D : result of discrete solver " ; set_color yellow ; print_black_endline " H : time horizon set for a continuous phase " ; print_newline ( ) ; print_string " M : time " ; print_newline ( ) ; print_string " --+\ n " ; flush stdout end let print_terminated t = if ! log then begin print_time ( " --+ terminated at " , " \ n " ) t ; flush stdout end ; if ! show_stats then begin let stats = Gc . stat ( ) in printf " gc collections : minor =% d major =% d compact =% d \ n " stats . Gc . minor_collections stats . Gc . major_collections stats . Gc . compactions ; printf " gc words : minor . =% 0f promoted . =% 0f major . =% 0f \ n " stats . Gc . minor_words stats . Gc . promoted_words stats . Gc . major_words ; flush stdout end let args n_eq = Arg . align ( [ ( " - maxt " , Arg . Float ( fun m -> max_sim_time := Some m ) , " < float > maximum simulation time " ) ; ( " - speedup " , Arg . Float ( fun m -> speedup := m ) , " < float > relate simulation and wall clock times ( 2 . 0 = twice as fast ) " ) ; ( " - fullspeed " , Arg . Unit ( fun ( ) -> speedup := 0 . 0 ) , " Do not try to relate simulation and wall clock times " ) ; ( " - maxcstep " , Arg . Float ( fun m -> max_c_step := m ) , " < float > maximum length of a C step ( if ' too big ' the solver may behave strangely ) " ) ; ( " - maxstep " , Arg . Float ( fun m -> max_step_size := Some m ) , " < float > maximum step size ( of solver ) " ) ; ( " - minstep " , Arg . Float ( fun m -> min_step_size := Some m ) , " < float > minimum step size ( of solver ) " ) ; ( " - reltol " , Arg . Float ( fun t -> rel_tol := Some t ) , " < float > Set relative tolerance ( only effective if - abstol is also given ) . " ) ; ( " - abstol " , Arg . Float ( fun t -> abs_tol := Some t ) , " < float > Set absolute tolerance ( only effective if - reltol is also given ) . " ) ; ( " - precisetime " , Arg . Set precise_logging , " Log time values with higher precision . " ) ; ( " - nocolor " , Arg . Clear color_logging , " Disable color logging ( no ASCII escape sequences ) . " ) ; ( " - avoidreinit " , Arg . Clear always_reinit , " Only reinitialize the solver when continuous state values change . " ) ; ( " - l " , Arg . Set log , " Log state variables and zero - crossings to stdout . " ) ; ( " - lgcalls " , Arg . Set log_gcalls , " Log zero - crossing function calls to stdout . " ) ; ( " - lfcalls " , Arg . Set log_fcalls , " Log differential function calls to stdout . " ) ; ( " - ldcalls " , Arg . Set log_dcalls , " Log discrete function calls to stdout . " ) ; ( " - stats " , Arg . Set show_stats , " Show statistics on termination ( with - maxt ) . " ) ; ] ) type model_disc_next = | Continue of bool * float | Goagain of bool | EndSimulation type sim_state_i = { discrete_ready : bool ; reset_required : bool ; init_horizon : float ; } type sim_state_d = { ssolver : SSolver . t ; zsolver : ZSolver . t ; t_sim : float ; t_nextmesh : float ; t_horizon : float ; after_c : bool ; roots_valid : bool ; needs_reset : bool ; } type sim_state = | SimI of sim_state_i | SimD of sim_state_d | SimC of sim_state_d | SimF let step ( f_alloc : ' s Zls . f_alloc ) ( f_csize : ' s Zls . f_csize ) ( f_zsize : ' s Zls . f_zsize ) ( f_horizon : ' s Zls . f_horizon ) ( f_maxsize : ' s Zls . f_maxsize ) ( f_ders : ' s Zls . f_ders ) ( f_step : ( ' s , ' o ) Zls . f_step ) ( f_zero : ' s Zls . f_zero ) ( f_reset : ' s Zls . f_reset ) = let dstate = f_alloc ( ) in let n_cstates , n_zeros = f_maxsize dstate in Arg . parse ( args n_cstates ) ( fun _ -> ( ) ) " Zélus simulation loop " ; let no_roots_in = Zls . zmake n_zeros in let no_roots_out = Zls . cmake n_zeros in let roots = Zls . zmake n_zeros in let ignore_der = Zls . cmake n_cstates in let cstates_nv = SSolver . cmake n_cstates in let cstates = SSolver . unvec cstates_nv in let pre_cstates = Zls . cmake ( if ! always_reinit then 0 else n_cstates ) in let f_main t cs ds = if ! log_fcalls then begin set_color before_loggedcall ; carray_log " * FC " : t cs ; ignore ( f_ders dstate cs ds no_roots_in no_roots_out no_time_in_solver ) ; set_color after_loggedcall ; carray_log " FD " : t ds end else ignore ( f_ders dstate cs ds no_roots_in no_roots_out no_time_in_solver ) ; in let g_main t cs rs = if ! log_gcalls then begin set_color before_loggedcall ; carray_log " * ZC " : t cs ; ignore ( f_zero dstate cs no_roots_in rs no_time_in_solver ) ; set_color after_loggedcall ; carray_log " ZR " : t rs end else ignore ( f_zero dstate cs no_roots_in rs no_time_in_solver ) ; in let g_setup t cs ri = if ! log_gcalls then begin set_color before_loggedcall ; carray_log " * ZS " : t cs ; ignore ( f_zero dstate cs ri no_roots_out no_time_in_solver ) ; set_color after_loggedcall end else ignore ( f_zero dstate cs ri no_roots_out no_time_in_solver ) ; in let d_main t rin = let o = if ! log_dcalls then begin set_color before_loggedcall ; carray_log " * DC " : t cstates ; let r = f_step dstate cstates ignore_der no_roots_in t in set_color after_loggedcall ; carray_log " DR " : t cstates ; r end else f_step dstate cstates ignore_der no_roots_in t in let t_horizon = f_horizon dstate in if t_horizon <= t then o , Goagain true else o , Continue ( true , t_horizon ) in let simstate = ref ( SimI { discrete_ready = false ; reset_required = true ; init_horizon = 0 . 0 } ) in let setup_discrete_step t roots = g_setup no_time_in_solver cstates roots ; if not ! always_reinit then Bigarray . Array1 . blit cstates pre_cstates in let exists_state_reset ( ) = let rec check i = if i = n_cstates then false else if cstates . { i } <> pre_cstates . { i } then true else check ( i + 1 ) in ! always_reinit || check 0 in let step ( ) = match ! simstate with | SimI { discrete_ready = false ; reset_required } -> begin if reset_required then begin print_help_key ( ) ; f_reset dstate end ; let step_out , step_status = d_main 0 . 0 no_roots_in in let goagain , t_horizon = match step_status with | Continue ( _ , t_horizon ) -> ( false , t_horizon ) | Goagain reset -> ( true , infinity ) | EndSimulation -> failwith " End of simulation at first call " ! in print_states ( if goagain then " D . : " else " D : " ) 0 . 0 cstates ; print_horizon 0 . 0 t_horizon false ; simstate := SimI { discrete_ready = not goagain ; reset_required = false ; init_horizon = t_horizon } ; Some step_out , false , 0 . 0 end | SimI { discrete_ready = true ; init_horizon } -> begin if not ! always_reinit then Bigarray . Array1 . blit cstates pre_cstates ; let ss = SSolver . initialize f_main cstates_nv in let zs = ZSolver . initialize n_zeros g_main cstates in set_param SSolver . set_stop_time ss max_sim_time ; set_param SSolver . set_min_step ss min_step_size ; set_param SSolver . set_max_step ss max_step_size ; set_param2 SSolver . set_tolerances ss rel_tol abs_tol ; print_states " I : " 0 . 0 cstates ; print_horizon 0 . 0 init_horizon false ; let params = { ssolver = ss ; zsolver = zs ; t_sim = 0 . 0 ; t_nextmesh = 0 . 0 ; t_horizon = init_horizon ; after_c = false ; roots_valid = false ; needs_reset = false ; } in simstate := SimC params ; None , false , 0 . 0 end | SimC ( { ssolver = ss ; zsolver = zs ; t_sim = last_t ; t_nextmesh ; t_horizon ; needs_reset } as params ) -> ( try if needs_reset then ( SSolver . reinitialize ss last_t cstates_nv ; ZSolver . reinitialize zs last_t cstates ) ; let t_limit = min ( last_t . + ! max_c_step ) t_horizon in let t_nextmesh = if needs_reset || t_limit > t_nextmesh then SSolver . step ss ( add_margin t_limit ) cstates_nv else t_nextmesh in then ( SSolver . get_dky ss cstates_nv t_limit 0 ; t_limit ) else t_nextmesh in ZSolver . step zs t cstates ; let has_roots = ZSolver . has_roots zs in let t = if has_roots then ZSolver . find zs ( SSolver . get_dky ss cstates_nv , cstates ) roots else t in let event = has_roots || t >= t_horizon in let delta = if ! speedup > 0 . 0 then ( t . - last_t ) . / ! speedup else 0 . 0 in print_states ( if event then " C ' : " else " C : " ) t cstates ; let at_stop_time = match ! max_sim_time with Some tmax -> t >= tmax | _ -> false in simstate := if at_stop_time then ( print_terminated t ; SimF ) else if event then begin if has_roots then print_roots zs t roots ; setup_discrete_step t ( if has_roots then roots else no_roots_in ) ; SimD { params with t_sim = t ; t_nextmesh = t_nextmesh ; after_c = true ; roots_valid = has_roots ; needs_reset = false ; } end else SimC { params with needs_reset = false ; after_c = true ; t_sim = t ; t_nextmesh = t_nextmesh } ; None , false , delta with err -> begin flush stdout ; set_err_color boldred ; eprintf " fatal error : % s \ n " ( Printexc . to_string err ) ; if ! log then if Printexc . backtrace_status ( ) then Printexc . print_backtrace stderr else prerr_string " ( compile with - g and run with OCAMLRUNPARAM = b for a backtrace ) \ n " ; Printexc . print_backtrace stderr ; set_err_color black ; flush stderr ; simstate := SimF ; None , false , 0 . 0 end ) | SimD ( { ssolver = ss ; zsolver = zs ; t_sim ; after_c ; needs_reset ; roots_valid } as params ) -> begin let step_out , step_status = d_main t_sim no_roots_in in simstate := ( match step_status with | Continue ( reset , t_horizon ) -> begin print_states " D : " t_sim cstates ; let needs_reinit = needs_reset || reset && exists_state_reset ( ) in print_horizon t_sim t_horizon needs_reinit ; SimC { params with after_c = false ; t_horizon = t_horizon ; needs_reset = needs_reinit } end | Goagain reset -> begin print_states " D . : " t_sim cstates ; SimD { params with after_c = false ; needs_reset = needs_reset || reset } end | EndSimulation -> begin print_states " D $: " t_sim cstates ; print_terminated t_sim ; SimF end ) ; Some step_out , false , 0 . 0 end | SimF -> None , true , 0 . 0 in step
module Make ( SSolver : Zls . STATE_SOLVER ) = struct
module Solver = Zlsolve . Make ( SSolver ) ( Illinois )
let wait_next_instant = let delay = ref 0 . 0 in let rec wait_next_instant starting ending delta = let diff = ( delta . - ( ending . - starting ) ) . - ! delay in if diff > 0 . 0 then begin try delay := 0 . 0 ; ignore ( Unix . select [ ] [ ] [ ] diff ) ; false with Unix . Unix_error ( Unix . EINTR , _ , _ ) -> wait_next_instant starting ( Unix . gettimeofday ( ) ) delta end else begin delay := min ( . - diff ) delta ; true end in wait_next_instant
let go ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) = let stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let starting = ref ( Unix . gettimeofday ( ) ) in let rec step ( ) = let _ , is_done , delta = stepfn ( ) in if is_done then ( ) else if delta = 0 . 0 then step ( ) else let ending = Unix . gettimeofday ( ) in ignore ( wait_next_instant ! starting ending delta ) ; starting := Unix . gettimeofday ( ) ; step ( ) in step ( )
let check ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) limit = let stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let rec step n = if n == limit then ( ) else let result , is_done , delta = stepfn ( ) in match result with | Some false -> exit 1 | _ -> if is_done then ( ) else step ( n + 1 ) in ( step 0 ; exit 0 ) end
module Make ( SSolver : Zls . STATE_SOLVER ) =
module Solver = Zlsolve . Make ( SSolver ) ( Illinois )
let _ = GMain . init ( )
let start_playing = ref true
let destroy ( ) = GMain . Main . quit ( )
let low_prio = Glib . int_of_priority ` LOW -> Glib . Timeout . id = " ml_g_timeout_add " main_ders main_step main_zero main_reset = val stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset val mutable last_wall_clk = Unix . gettimeofday ( ) val mutable timer_id = None val mutable step_count = 0 method private inc_step_count ( ) = step_count <- step_count + 1 method private reset_step_count ( ) = step_count <- 0 method private too_many_steps = step_count > 1000 method private clear_timer ( ) = match timer_id with None -> ( ) | Some id -> ( Glib . Timeout . remove id ; timer_id <- None ) method single_step ( ) = let _ , is_done , _ = stepfn ( ) in is_done method trigger_step ( ) = self # clear_timer ( ) ; self # inc_step_count ( ) ; let _ , is_done , delta = stepfn ( ) in let wall_clk = Unix . gettimeofday ( ) in let delta ' = delta . - ( wall_clk . - last_wall_clk ) in last_wall_clk <- wall_clk ; if is_done then true else if delta <= 0 . 0 && not self # too_many_steps then self # trigger_step ( ) else if self # too_many_steps then begin prerr_string " Zlsrungtk : too fast !\ n " ; flush stderr ; self # reset_step_count ( ) ; timer_id <- Some ( timeout_add ~ prio : low_prio ~ ms : 10 ~ callback : self # trigger_step ) ; true end else if delta ' <= 0 . 0 then self # trigger_step ( ) else ( self # reset_step_count ( ) ; timer_id <- Some ( timeout_add ~ prio : low_prio ~ ms ( : int_of_float ( delta ' . * 1000 . 0 ) ) ~ callback : self # trigger_step ) ; true ) method start ( ) = last_wall_clk <- Unix . gettimeofday ( ) ; ignore ( self # trigger_step ( ) ) method stop ( ) = self # clear_timer ( ) end
let go ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) = let w = GWindow . window ~ title " : Simulator " ~ width : 250 ~ height : 70 ~ resizable : false ( ) in let outer_box = GPack . vbox ~ packing : w # add ( ) in let top_box = GPack . button_box ` HORIZONTAL ~ packing : outer_box # pack ~ child_width : 48 ~ child_height : 48 ~ layout ` : SPREAD ( ) in let b_play = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PLAY ( ) in let b_pause = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PAUSE ( ) in let b_single = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_NEXT ( ) in b_pause # misc # set_sensitive false ; let stask = new step_task main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let s_speed_adj = GData . adjustment ~ lower : 1 . 0 ~ upper : 20 . 0 ~ value : 3 . 0 ~ step_incr : 0 . 2 ( ) in let original_speedup = ! Solver . speedup in let change_speedup x = let v = s_speed_adj # value in Solver . speedup := original_speedup . * ( if v <= 3 . 0 then v . / 3 . 0 else ( v . - 3 . 0 ) . * 4 . 0 ) ; ignore ( stask # trigger_step ( ) ) in ignore ( s_speed_adj # connect # value_changed change_speedup ) ; let s_speed = GRange . scale ` HORIZONTAL ~ adjustment : s_speed_adj ~ draw_value : false ~ packing : outer_box # pack ( ) in ignore ( s_speed ) ; let step_react_fun ( ) = try if Printexc . print stask # single_step ( ) then begin b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive false ; ( ) end with _ -> ( destroy ( ) ) in let play_pushed ( ) = b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive true ; stask # start ( ) in let pause_pushed ( ) = b_single # misc # set_sensitive true ; b_play # misc # set_sensitive true ; b_pause # misc # set_sensitive false ; stask # stop ( ) in ignore ( b_play # connect # clicked ~ callback : play_pushed ) ; ignore ( b_pause # connect # clicked ~ callback : pause_pushed ) ; ignore ( b_single # connect # clicked ~ callback : step_react_fun ) ; if ! start_playing then play_pushed ( ) ; ignore ( w # connect # destroy ~ callback : destroy ) ; w # show ( ) ; GMain . Main . main ( )
let check _ _ = assert false
let _ = GMain . init ( )
let start_playing = ref false
let destroy ( ) = GMain . Main . quit ( )
let low_prio = Glib . int_of_priority ` LOW -> Glib . Timeout . id = " ml_g_timeout_add " val mutable period = 1 . 0 . / freq val mutable last_wall_clk = Unix . gettimeofday ( ) val mutable timer_id = None val mutable step_count = 0 method set_period v = period <- v method private clear_timer ( ) = match timer_id with None -> ( ) | Some id -> ( Glib . Timeout . remove id ; timer_id <- None ) method single_step ( ) = main_step ( ) method trigger_step ( ) = self # clear_timer ( ) ; let is_done = main_step ( ) in let delta = 1 . 0 in let wall_clk = Unix . gettimeofday ( ) in let delta ' = delta . - ( wall_clk . - last_wall_clk ) in last_wall_clk <- wall_clk ; if is_done then true else if delta ' <= 0 . 0 then main_step ( ) else ( timer_id <- Some ( timeout_add ~ prio : low_prio ~ ms ( : int_of_float ( delta ' . * period ) ) ~ callback : self # trigger_step ) ; true ) method start ( ) = last_wall_clk <- Unix . gettimeofday ( ) ; ignore ( self # trigger_step ( ) ) method stop ( ) = self # clear_timer ( ) end
let go freq main_step = let w = GWindow . window ~ title " : Simulator " ~ width : 250 ~ height : 70 ~ resizable : false ( ) in let outer_box = GPack . vbox ~ packing : w # add ( ) in let top_box = GPack . button_box ` HORIZONTAL ~ packing : outer_box # pack ~ child_width : 48 ~ child_height : 48 ~ layout ` : SPREAD ( ) in let b_play = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PLAY ( ) in let b_pause = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PAUSE ( ) in let b_single = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_NEXT ( ) in b_pause # misc # set_sensitive false ; let stask = new step_task freq ( fun ( ) -> main_step ( ) ; false ) in let s_speed_adj = GData . adjustment ~ lower : 1 . 0 ~ upper : 100 . 0 ~ value : 10 . 0 ~ step_incr : 1 . 0 ( ) in let change_period x = stask # set_period ( 10 . . / s_speed_adj # value ) in ignore ( s_speed_adj # connect # value_changed change_period ) ; let s_speed = GRange . scale ` HORIZONTAL ~ adjustment : s_speed_adj ~ draw_value : false ~ packing : outer_box # pack ( ) in ignore ( s_speed ) ; let step_react_fun ( ) = try if Printexc . print stask # single_step ( ) then begin b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive false ; ( ) end with _ -> ( destroy ( ) ) in let play_pushed ( ) = b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive true ; stask # start ( ) in let pause_pushed ( ) = b_single # misc # set_sensitive true ; b_play # misc # set_sensitive true ; b_pause # misc # set_sensitive false ; stask # stop ( ) in ignore ( b_play # connect # clicked ~ callback : play_pushed ) ; ignore ( b_pause # connect # clicked ~ callback : pause_pushed ) ; ignore ( b_single # connect # clicked ~ callback : step_react_fun ) ; if ! start_playing then play_pushed ( ) else step_react_fun ( ) ; ignore ( w # connect # destroy ~ callback : destroy ) ; w # show ( ) ; GMain . Main . main ( )
type error = | Etype | Ehybrid_operator | Earray_operator | Eapplication
let error loc kind = raise ( Error ( loc , kind ) )
let message loc kind = begin match kind with | Etype -> eprintf " [ @% aTranslation to L --: This type cannot be translated . . ] " @@ output_location loc | Ehybrid_operator -> eprintf " [ @% aTranslation to L --: Hybrid operators are not treated . . ] " @@ output_location loc | Earray_operator -> eprintf " [ @% aTranslation to L --: Array operators are not treated . . ] " @@ output_location loc | Eapplication -> eprintf " [ @% aTranslation to L --: \ Application must be of the form f ( e1 , . . . , en ) . . ] " @@ output_location loc end
type return = { eqs : eq State . t ; env : tentry Env . t State . t ; assertion : exp State . t }
let empty = { eqs = State . empty ; env = State . empty ; assertion = State . empty }
let with_env ( { env = env0 } as return ) env = { return with env = State . cons env env0 }
let with_eq ( { eqs = eqs } as return ) eq = { return with eqs = State . cons eq eqs }
let par { eqs = eqs1 ; env = env1 ; assertion = as1 } { eqs = eqs2 ; env = env2 ; assertion = as2 } = { eqs = State . par eqs1 eqs2 ; env = State . par env1 env2 ; assertion = State . par as1 as2 }
let eq_make k x e ck = { eq_kind = k ; eq_ident = x ; eq_exp = e ; eq_clock = ck }
let on ck ln c = Ck_on ( ck , ln , c )
let relse res c = Res_else ( res , c )
let immediate = function | Eint ( i ) -> Lint ( i ) | Efloat ( f ) -> Lfloat ( f ) | Ebool ( b ) -> Lbool ( b ) | Echar ( c ) -> Lchar ( c ) | Estring ( s ) -> Lstring ( s ) | Evoid -> Lvoid
let constr0pat { p_desc = p_desc } = match p_desc with | Econstpat ( Ebool ( b ) ) -> Lboolpat ( b ) | Econstr0pat ( c ) -> Lconstr0pat ( c ) | _ -> assert false
let rec type_of loc { t_desc = ty } = match ty with | Deftypes . Tconstr ( q , [ ] , _ ) -> if q = Initial . int_ident then Tint else if q = Initial . int32_ident then Tint else if q = Initial . int64_ident then Tint else if q = Initial . bool_ident then Tbool else if q = Initial . zero_ident then Tbool else if q = Initial . float_ident then Tfloat else if q = Initial . char_ident then Tchar else if q = Initial . string_ident then Tstring else if q = Initial . unit_ident then Tunit else Lmm . Tconstr ( q ) | Tconstr _ -> error loc Etype | Tproduct ( ty_list ) -> Lmm . Tproduct ( List . map ( type_of loc ) ty_list ) | Tvar | Tvec _ | Tfun _ -> error loc Etype | Tlink ( ty ) -> type_of loc ty
let type_expression loc ty_e = let { typ_body = ty } = Interface . scheme_of_type ty_e in type_of loc ty
let env_of_env loc env = Env . map ( fun { Deftypes . t_typ = ty } -> { t_typ = type_of loc ty } ) env
let operator loc op e_list = match op with | Eifthenelse -> Lapp ( Lifthenelse , e_list ) | Eunarypre -> Lapp ( Lunarypre , e_list ) | Eminusgreater -> Lapp ( Lminusgreater , e_list ) | Efby -> Lapp ( Lfby , e_list ) | Eup | Einitial | Edisc | Ehorizon -> error loc Ehybrid_operator | Eaccess | Eupdate | Econcat | Eslice _ -> error loc Earray_operator | Etest | Eatomic -> assert false
let shared_variables { dv = dv } = dv
let get x name_to_exp = try Env . find x name_to_exp with | Not_found -> Llast ( x )
let rec expression ck { e_desc = desc ; e_loc = loc } = match desc with | Elocal ( id ) -> Llocal ( id ) | Eglobal { lname = lid } -> Lglobal ( lid ) | Econst ( im ) -> Lconst ( immediate im ) | Econstr0 ( lid ) -> Lconstr0 ( lid ) | Econstr1 _ -> assert false | Elast ( x ) -> Llast ( x ) | Eapp ( _ , { e_desc = Eglobal { lname = lid } } , e_list ) -> Lapp ( Lop ( lid ) , List . map ( expression ck ) e_list ) | Eapp _ -> error loc Eapplication | Eop ( op , e_list ) -> operator loc op ( map ( expression ck ) e_list ) | Erecord_access ( e , lid ) -> Lrecord_access ( expression ck e , lid ) | Erecord ( l_e_list ) -> Lrecord ( map ( fun ( l , e ) -> ( l , expression ck e ) ) l_e_list ) | Etypeconstraint ( e , _ ) -> expression ck e | Etuple ( e_list ) -> Ltuple ( List . map ( expression ck ) e_list ) | Ematch _ | Eseq _ | Elet _ | Eperiod _ | Eblock _ | Epresent _ -> assert false
let split s_set ( { eqs = eqs } as return ) = let eq_name_exp , eqs = State . partition ( fun { eq_ident = id } -> S . mem id s_set ) eqs in let name_to_exp = State . fold ( fun { eq_ident = id ; eq_exp = e } acc -> Env . add id e acc ) eq_name_exp Env . empty in name_to_exp , { return with eqs = eqs }
let rec equation ck res { eq_desc = desc ; eq_write = defnames } = match desc with | EQeq ( { p_desc = Evarpat ( x ) } , e ) -> with_eq empty ( eq_make Def x ( expression ck e ) ck ) | EQinit ( x , e ) -> let e = expression ck e in with_eq empty ( eq_make ( Init ( res ) ) x e ck ) | EQreset ( eq_list , e ) -> let e = expression ck e in equation_list ck ( relse res e ) eq_list | EQmatch ( total , e , p_h_list ) -> let e = expression ck e in let s_set = shared_variables defnames in let equations_from_handler e p b = let co = constr0pat p in let return = block ( on ck co e ) res b in let name_to_exp , return = split s_set return in co , name_to_exp , return in let constrpat_to_exp_list , return = Zmisc . map_fold ( fun return { m_pat = p ; m_body = b } -> let co , name_to_exp , return_name_to_exp = equations_from_handler e p b in let merge e x constrpat_name_to_exp_list = let p_e_list = List . map ( fun ( co , name_to_exp ) -> co , get x name_to_exp ) constrpat_name_to_exp_list in Lmerge ( e , p_e_list ) in let eq_list = S . fold ( eq_make Def x ( merge e x constrpat_to_exp_list ) ck ) :: eq_list ) s_set [ ] in List . fold_left with_eq empty eq_list | EQeq _ | EQnext _ | EQblock _ | EQemit _ | EQautomaton _ | EQpresent _ | EQder _ | EQpluseq _ | EQand _ | EQbefore _ | EQforall _ -> assert false fold_left ( fun acc eq -> par acc ( equation ck res eq ) ) empty eq_list let return = equation_list ck res body_eq_list in with_env return ( env_of_env loc n_env )
let local ck res { l_eq = eq_list ; l_env = l_env ; l_loc = loc } = let return = equation_list ck res eq_list in with_env return ( env_of_env loc l_env )
let let_expression ck res n_output ( { e_desc = desc } as e ) = match desc with | Elet ( l , e ) -> let return = local ck res l in let e = expression ck e in with_eq return ( eq_make Def n_output e ck ) | _ -> let e = expression ck e in with_eq empty ( eq_make Def n_output e ck )
let kind = function | S | AS | A | AD -> A | D -> D | C -> assert false
let typedecl loc n params td = let decl { desc = desc } = match desc with | Eabstract_type -> Labstract_type | Evariant_type _ -> assert false | Erecord_type ( n_ty_list ) -> Lrecord_type | Eabbrev _ -> assert false in match params with | [ ] -> Ltypedecl ( n , decl td ) | _ -> assert false
let implementation lmm_nodes lmm_list impl = match impl . desc with | Eopen _ -> lmm_list | Etypedecl ( n , params , td ) -> typedecl impl . loc n params td :: lmm_list | Econstdecl ( n , _ , e ) -> if Zmisc . S . mem n lmm_nodes then Lconstdecl ( n , expression Ck_base e ) :: lmm_list else lmm_list | Efundecl ( n , { f_kind = k ; f_args = p_list ; f_env = f_env ; f_body = e } ) -> if Zmisc . S . mem n lmm_nodes then let iset = List . fold_left ( Vars . fv_pat S . empty ) S . empty p_list in let i_list = S . elements iset in let n_output = Zident . fresh " out " in let { eqs = eqs ; env = env ; assertion = assertion } = let env = ( fun env acc -> Env . append env acc ) env ( env_of_env impl . loc f_env ) in let eq_list = State . list [ ] eqs in let assertion = Lfundecl ( n , { f_inputs = i_list ; else lmm_list
let implementation_list lmm_nodes impl_list = rev ( fold_left ( implementation lmm_nodes ) [ ] impl_list )
let rec repeat n a = match n with | 0 -> [ ] | n -> a :: ( repeat ( n - 1 ) a )
let rec keep l n = match ( l , n ) with | ( _ , 0 ) -> invalid_arg " keep " | ( h :: _ , 1 ) -> h | ( _ :: t , n ) -> keep t ( n - 1 ) | _ -> invalid_arg " keep "
let rec drop l n = match ( l , n ) with | ( _ , 0 ) -> invalid_arg " drop " | ( _ :: t , 1 ) -> t | ( h :: t , n ) -> h :: ( drop t ( n - 1 ) ) | _ -> invalid_arg " drop "
let rec range n m = if n > m then [ ] else n :: ( range ( n + 1 ) m )
let separate n l = let rec f acc n l = match ( n , l ) with | ( 0 , _ ) -> ( acc , l ) | ( n , h :: t ) -> f ( h :: acc ) ( n - 1 ) t | _ -> assert false in if n > List . length l then invalid_arg " separate " else let ( p , l ) = f [ ] n l in ( List . rev p , l )