text
stringlengths
12
786k
let list = { space_after_opening = true ; space_after_separator = true ; space_before_separator = false ; separators_stick_left = true ; space_before_closing = true ; stick_to_label = true ; align_closing = true ; wrap_body = ` Wrap_atoms ; indent_body = 2 ; list_style = None ; opening_style = None ; body_style = None ; separator_style = None ; closing_style = None ; }
type label_param = { label_break : label_break ; space_after_label : bool ; indent_after_label : int ; label_style : style_name option ; }
let label = { label_break = ` Auto ; space_after_label = true ; indent_after_label = 2 ; label_style = None ; }
type t = Atom of string * atom_param | List of ( string * string * string * list_param ) * t list | Label of ( t * label_param ) * t | Custom of ( formatter -> unit )
type escape = [ ` None | ` Escape of ( ( string -> int -> int -> unit ) -> string -> int -> int -> unit ) | ` Escape_string of ( string -> string ) ]
type styles = ( style_name * style ) list
let propagate_from_leaf_to_root ~ init_acc ~ merge_acc ~ map_node x = let rec aux x = match x with | Atom _ -> let acc = init_acc x in map_node x acc | List ( param , children ) -> let new_children , accs = List . rev_split ( List . rev_map aux children ) in let acc = List . fold_left merge_acc ( init_acc x ) accs in map_node ( List ( param , new_children ) ) acc | Label ( ( x1 , param ) , x2 ) -> let acc0 = init_acc x in let new_x1 , acc1 = aux x1 in let new_x2 , acc2 = aux x2 in let acc = merge_acc ( merge_acc acc0 acc1 ) acc2 in map_node ( Label ( ( new_x1 , param ) , new_x2 ) ) acc | Custom _ -> let acc = init_acc x in map_node x acc in aux x
let propagate_forced_breaks x = let init_acc = function | List ( ( _ , _ , _ , { wrap_body = ` Force_breaks_rec } ) , _ ) | Label ( ( _ , { label_break = ` Always_rec } ) , _ ) -> true | Atom _ | Label _ | Custom _ | List _ -> false in let merge_acc force_breaks1 force_breaks2 = force_breaks1 || force_breaks2 in let map_node x force_breaks = match x with | List ( ( _ , _ , _ , { wrap_body = ` Force_breaks_rec } ) , _ ) -> x , true | List ( ( _ , _ , _ , { wrap_body = ` Force_breaks } ) , _ ) -> x , force_breaks | List ( ( op , sep , cl , ( { wrap_body = ( ` Wrap_atoms | ` Never_wrap | ` Always_wrap ) } as p ) ) , children ) -> if force_breaks then let p = { p with wrap_body = ` Force_breaks } in List ( ( op , sep , cl , p ) , children ) , true else x , false | Label ( ( a , ( { label_break = ` Auto } as lp ) ) , b ) -> if force_breaks then let lp = { lp with label_break = ` Always } in Label ( ( a , lp ) , b ) , true else x , false | List ( ( _ , _ , _ , { wrap_body = ` No_breaks } ) , _ ) | Label ( ( _ , { label_break = ( ` Always | ` Always_rec | ` Never ) } ) , _ ) | Atom _ | Custom _ -> x , force_breaks in let new_x , forced_breaks = propagate_from_leaf_to_root ~ init_acc ~ merge_acc ~ map_node x in new_x
module Pretty = struct let rewrite x = propagate_forced_breaks x let set_escape fmt escape = let print0 , flush0 = pp_get_formatter_output_functions fmt ( ) in let tagf0 = ( pp_get_formatter_tag_functions [ @ warning " - 3 " ] ) fmt ( ) in let is_tag = ref false in let mot tag = is_tag := true ; tagf0 . mark_open_tag tag in let mct tag = is_tag := true ; tagf0 . mark_close_tag tag in let print s p n = if ! is_tag then ( print0 s p n ; is_tag := false ) else escape print0 s p n in let tagf = { tagf0 with mark_open_tag = mot ; mark_close_tag = mct } in pp_set_formatter_output_functions fmt print flush0 ; ( pp_set_formatter_tag_functions [ @ warning " - 3 " ] ) fmt tagf let set_escape_string fmt esc = let escape print s p n = let s0 = String . sub s p n in let s1 = esc s0 in print s1 0 ( String . length s1 ) in set_escape fmt escape let define_styles fmt escape l = if l <> [ ] then ( pp_set_tags fmt true ; let tbl1 = Hashtbl . create ( 2 * List . length l ) in let tbl2 = Hashtbl . create ( 2 * List . length l ) in List . iter ( fun ( style_name , style ) -> Hashtbl . add tbl1 style_name style . tag_open ; Hashtbl . add tbl2 style_name style . tag_close ) l ; let mark_open_tag style_name = try Hashtbl . find tbl1 style_name with Not_found -> " " in let mark_close_tag style_name = try Hashtbl . find tbl2 style_name with Not_found -> " " in let tagf = { ( ( pp_get_formatter_tag_functions [ @ warning " - 3 " ] ) fmt ( ) ) with mark_open_tag = mark_open_tag ; mark_close_tag = mark_close_tag } in ( pp_set_formatter_tag_functions [ @ warning " - 3 " ] ) fmt tagf ) ; ( match escape with ` None -> ( ) | ` Escape esc -> set_escape fmt esc | ` Escape_string esc -> set_escape_string fmt esc ) let pp_open_xbox fmt p indent = match p . wrap_body with ` Always_wrap | ` Never_wrap | ` Wrap_atoms -> pp_open_hvbox fmt indent | ` Force_breaks | ` Force_breaks_rec -> pp_open_vbox fmt indent | ` No_breaks -> pp_open_hbox fmt ( ) let extra_box p l = let wrap = match p . wrap_body with ` Always_wrap -> true | ` Never_wrap | ` Force_breaks | ` Force_breaks_rec | ` No_breaks -> false | ` Wrap_atoms -> List . for_all ( function Atom _ -> true | _ -> false ) l in if wrap then ( ( fun fmt -> pp_open_hovbox fmt 0 ) , ( fun fmt -> pp_close_box fmt ( ) ) ) else ( ( fun fmt -> ( ) ) , ( fun fmt -> ( ) ) ) let pp_open_nonaligned_box fmt p indent l = match p . wrap_body with ` Always_wrap -> pp_open_hovbox fmt indent | ` Never_wrap -> pp_open_hvbox fmt indent | ` Wrap_atoms -> if List . for_all ( function Atom _ -> true | _ -> false ) l then pp_open_hovbox fmt indent else pp_open_hvbox fmt indent | ` Force_breaks | ` Force_breaks_rec -> pp_open_vbox fmt indent | ` No_breaks -> pp_open_hbox fmt ( ) let open_tag fmt = function None -> ( ) | Some s -> ( pp_open_tag [ @ warning " - 3 " ] ) fmt s let close_tag fmt = function None -> ( ) | Some _ -> ( pp_close_tag [ @ warning " - 3 " ] ) fmt ( ) let tag_string fmt o s = match o with None -> pp_print_string fmt s | Some tag -> ( pp_open_tag [ @ warning " - 3 " ] ) fmt tag ; pp_print_string fmt s ; ( pp_close_tag [ @ warning " - 3 " ] ) fmt ( ) let rec fprint_t fmt = function Atom ( s , p ) -> tag_string fmt p . atom_style s ; | List ( ( _ , _ , _ , p ) as param , l ) -> open_tag fmt p . list_style ; if p . align_closing then fprint_list fmt None param l else fprint_list2 fmt param l ; close_tag fmt p . list_style | Label ( label , x ) -> fprint_pair fmt label x | Custom f -> f fmt and fprint_list_body_stick_left fmt p sep hd tl = open_tag fmt p . body_style ; fprint_t fmt hd ; List . iter ( fun x -> if p . space_before_separator then pp_print_string fmt " " ; tag_string fmt p . separator_style sep ; if p . space_after_separator then pp_print_space fmt ( ) else pp_print_cut fmt ( ) ; fprint_t fmt x ) tl ; close_tag fmt p . body_style and fprint_list_body_stick_right fmt p sep hd tl = open_tag fmt p . body_style ; fprint_t fmt hd ; List . iter ( fun x -> if p . space_before_separator then pp_print_space fmt ( ) else pp_print_cut fmt ( ) ; tag_string fmt p . separator_style sep ; if p . space_after_separator then pp_print_string fmt " " ; fprint_t fmt x ) tl ; close_tag fmt p . body_style and fprint_opt_label fmt = function None -> ( ) | Some ( lab , lp ) -> open_tag fmt lp . label_style ; fprint_t fmt lab ; close_tag fmt lp . label_style ; if lp . space_after_label then pp_print_string fmt " " and fprint_list fmt label ( ( op , sep , cl , p ) as param ) = function [ ] -> fprint_opt_label fmt label ; tag_string fmt p . opening_style op ; if p . space_after_opening || p . space_before_closing then pp_print_string fmt " " ; tag_string fmt p . closing_style cl | hd :: tl as l -> if tl = [ ] || p . separators_stick_left then fprint_list_stick_left fmt label param hd tl l else fprint_list_stick_right fmt label param hd tl l and fprint_list_stick_left fmt label ( op , sep , cl , p ) hd tl l = let indent = p . indent_body in pp_open_xbox fmt p indent ; fprint_opt_label fmt label ; tag_string fmt p . opening_style op ; if p . space_after_opening then pp_print_space fmt ( ) else pp_print_cut fmt ( ) ; let open_extra , close_extra = extra_box p l in open_extra fmt ; fprint_list_body_stick_left fmt p sep hd tl ; close_extra fmt ; if p . space_before_closing then pp_print_break fmt 1 ( - indent ) else pp_print_break fmt 0 ( - indent ) ; tag_string fmt p . closing_style cl ; pp_close_box fmt ( ) and fprint_list_stick_right fmt label ( op , sep , cl , p ) hd tl l = let base_indent = p . indent_body in let sep_indent = String . length sep + ( if p . space_after_separator then 1 else 0 ) in let indent = base_indent + sep_indent in pp_open_xbox fmt p indent ; fprint_opt_label fmt label ; tag_string fmt p . opening_style op ; if p . space_after_opening then pp_print_space fmt ( ) else pp_print_cut fmt ( ) ; let open_extra , close_extra = extra_box p l in open_extra fmt ; fprint_t fmt hd ; List . iter ( fun x -> if p . space_before_separator then pp_print_break fmt 1 ( - sep_indent ) else pp_print_break fmt 0 ( - sep_indent ) ; tag_string fmt p . separator_style sep ; if p . space_after_separator then pp_print_string fmt " " ; fprint_t fmt x ) tl ; close_extra fmt ; if p . space_before_closing then pp_print_break fmt 1 ( - indent ) else pp_print_break fmt 0 ( - indent ) ; tag_string fmt p . closing_style cl ; pp_close_box fmt ( ) and fprint_list2 fmt ( op , sep , cl , p ) = function [ ] -> tag_string fmt p . opening_style op ; if p . space_after_opening || p . space_before_closing then pp_print_string fmt " " ; tag_string fmt p . closing_style cl | hd :: tl as l -> tag_string fmt p . opening_style op ; if p . space_after_opening then pp_print_string fmt " " ; pp_open_nonaligned_box fmt p 0 l ; if p . separators_stick_left then fprint_list_body_stick_left fmt p sep hd tl else fprint_list_body_stick_right fmt p sep hd tl ; pp_close_box fmt ( ) ; if p . space_before_closing then pp_print_string fmt " " ; tag_string fmt p . closing_style cl and fprint_pair fmt ( ( lab , lp ) as label ) x = match x with List ( ( op , sep , cl , p ) , l ) when p . stick_to_label && p . align_closing -> fprint_list fmt ( Some label ) ( op , sep , cl , p ) l | _ -> let indent = lp . indent_after_label in pp_open_hvbox fmt 0 ; open_tag fmt lp . label_style ; fprint_t fmt lab ; close_tag fmt lp . label_style ; ( match lp . label_break with | ` Auto -> if lp . space_after_label then pp_print_break fmt 1 indent else pp_print_break fmt 0 indent | ` Always | ` Always_rec -> pp_force_newline fmt ( ) ; pp_print_string fmt ( String . make indent ' ' ) | ` Never -> if lp . space_after_label then pp_print_char fmt ' ' else ( ) ) ; fprint_t fmt x ; pp_close_box fmt ( ) let to_formatter fmt x = let x = rewrite x in fprint_t fmt x ; pp_print_flush fmt ( ) let to_buffer ( ? escape = ` None ) ( ? styles = [ ] ) buf x = let fmt = Format . formatter_of_buffer buf in define_styles fmt escape styles ; to_formatter fmt x let to_string ? escape ? styles x = let buf = Buffer . create 500 in to_buffer ? escape ? styles buf x ; Buffer . contents buf let to_channel ( ? escape = ` None ) ( ? styles = [ ] ) oc x = let fmt = formatter_of_out_channel oc in define_styles fmt escape styles ; to_formatter fmt x let to_stdout ? escape ? styles x = to_channel ? escape ? styles stdout x let to_stderr ? escape ? styles x = to_channel ? escape ? styles stderr x end
module Compact = struct open Printf let rec fprint_t buf = function Atom ( s , _ ) -> Buffer . add_string buf s | List ( param , l ) -> fprint_list buf param l | Label ( label , x ) -> fprint_pair buf label x | Custom f -> let fmt = formatter_of_buffer buf in f fmt ; pp_print_flush fmt ( ) and fprint_list buf ( op , sep , cl , _ ) = function [ ] -> bprintf buf " % s % s " op cl | x :: tl -> Buffer . add_string buf op ; fprint_t buf x ; List . iter ( fun x -> Buffer . add_string buf sep ; fprint_t buf x ) tl ; Buffer . add_string buf cl and fprint_pair buf ( label , _ ) x = fprint_t buf label ; fprint_t buf x let to_buffer buf x = fprint_t buf x let to_string x = let buf = Buffer . create 500 in to_buffer buf x ; Buffer . contents buf let to_formatter fmt x = let s = to_string x in Format . fprintf fmt " % s " s ; pp_print_flush fmt ( ) let to_channel oc x = let buf = Buffer . create 500 in to_buffer buf x ; Buffer . output_buffer oc buf let to_stdout x = to_channel stdout x let to_stderr x = to_channel stderr x end
module Param = struct let list_true = { space_after_opening = true ; space_after_separator = true ; space_before_separator = true ; separators_stick_left = true ; space_before_closing = true ; stick_to_label = true ; align_closing = true ; wrap_body = ` Wrap_atoms ; indent_body = 2 ; list_style = None ; opening_style = None ; body_style = None ; separator_style = None ; closing_style = None ; } let list_false = { space_after_opening = false ; space_after_separator = false ; space_before_separator = false ; separators_stick_left = false ; space_before_closing = false ; stick_to_label = false ; align_closing = false ; wrap_body = ` Wrap_atoms ; indent_body = 2 ; list_style = None ; opening_style = None ; body_style = None ; separator_style = None ; closing_style = None ; } let label_true = { label_break = ` Auto ; space_after_label = true ; indent_after_label = 2 ; label_style = None ; } let label_false = { label_break = ` Auto ; space_after_label = false ; indent_after_label = 2 ; label_style = None ; } end
module Prop = struct module Boolean = Boolean include Option include Set end
let f t = [ 1 ] @ t
let f t = 1 :: [ ] @ t
let f ( t : int * int ) = fst t + snd t
let dounit ( ) = ( )
let f ( ) = if x then ( if x then x else y ) else y
let f ( ) = if x then ( if x then x else let z = 3 in dounit ( ) ; ( if z = 2 then x else y ) ) else y
let f ( ) = let l = [ ] in begin match l with | [ ] -> begin match l with | [ ] -> let z = [ ] in begin match z with | _ -> true end | _ -> false end | _ -> true end
let z = if x then 1 else if y then 2 else if x & y then 3 else 4
let z = if x then 1 else if y then 2 else if x & y then 3 else if z = 4 then 3 else 9
let z = ( x = TConstr 3 || x = TConstr 4 )
let z = ( x = [ 12 ] || x = [ 50 ] )
let z = ( x = 5 || x = 6 )
let z = ( x = TConstr 3 && x = TConstr 4 )
let z = ( x = [ 12 ] && x = [ 50 ] )
let z = ( x = 5 && x = 6 )
let z = ( x = TConstr 3 || not ( x = TConstr 3 ) )
let z = ( x = [ ] || x = [ ] )
let z = ( x = None || x = None )
let z = ( x = 5 || x = 5 )
let z = ( x = TConstr 3 || x = TConstr 3 )
let z = ( x = TConstr 3 || x = TConstr 3 || x = TConstr 4 )
let z = ( x = TConstr 3 || x = TConstr 4 || x = TConstr 3 )
let z = ( x = [ ] && x = [ ] )
let z = ( x = None && x = None )
let z = ( x = 5 && x = 5 )
let z = ( x = TConstr 3 && x = TConstr 3 )
let z = ( x = TConstr 3 && x = TConstr 3 && x = TConstr 4 )
let z = ( x = TConstr 3 && x = TConstr 4 && x = TConstr 3 )
let ( ) = Alcotest . run ~ verbose : true __FILE__ [ ( " alpha " , [ Alcotest . test_case " 0 newlines " ` Quick ( fun ( ) -> Format . printf " Print inside alpha " ) ; ] ) ; ( " beta " , [ Alcotest . test_case " 1 newline " ` Quick ( fun ( ) -> Format . printf " Print inside beta \ n " ) ; ] ) ; ( " gamma " , [ Alcotest . test_case " 1 newline + long line " ` Quick ( fun ( ) -> Format . printf " Print inside gamma \ n \ Lorem ipsum dolor sit amet , consectetur adipiscing elit , \ nullam malesuada dictum tortor in venenatis . " ) ; ] ) ; ( " delta " , [ Alcotest . test_case " 1 newline + long check " ` Quick ( fun ( ) -> Format . printf " Print inside delta \ n " ; Alcotest . ( check unit ) " Lorem ipsum dolor sit amet , consectetur adipiscing elit , \ nullam malesuada dictum tortor in venenatis . " ( ) ( ) ) ; ] ) ; ]
val mutable x : int = x method x = x val mutable y : int = y method y = y val mutable width = w method width = width method draw = fill_rect x y width width method private contains x ' y ' = x <= x ' && x ' <= x + width && y <= y ' && y ' <= y + width method on_click ? start ? stop f = on_click ? start ? stop ( fun ev -> if self # contains ev . mouse_x ev . mouse_y then f ev . mouse_x ev . mouse_y ) end val mutable x : int = x method x = x val mutable y : int = y method y = y val mutable radius = r method radius = radius method draw = fill_circle x y radius method private contains x ' y ' = let dx = abs ( x ' - x ) in let dy = abs ( y ' - y ) in let dist = sqrt ( Float . of_int ( ( dx * dx ) + ( dy * dy ) ) ) in dist <= ( Float . of_int radius ) method on_click ? start ? stop f = on_click ? start ? stop ( fun ev -> if self # contains ev . mouse_x ev . mouse_y then f ev . mouse_x ev . mouse_y ) end
module Verifier_index_json = struct module Lookup = struct type lookups_used = Kimchi_types . VerifierIndex . Lookup . lookups_used = | Single | Joint [ @@ deriving yojson ] yojson type ' polyComm t = ' polyComm Kimchi_types . VerifierIndex . Lookup . t = { lookup_used : lookups_used ; lookup_table : ' polyComm array ; lookup_selectors : ' polyComm array ; table_ids : ' polyComm option ; max_joint_size : int } [ @@ deriving yojson ] yojson end type ' fr domain = ' fr Kimchi_types . VerifierIndex . domain = { log_size_of_group : int ; group_gen : ' fr } [ @@ deriving yojson ] yojson type ' polyComm verification_evals = ' polyComm Kimchi_types . VerifierIndex . verification_evals = { sigma_comm : ' polyComm array ; coefficients_comm : ' polyComm array ; generic_comm : ' polyComm ; psm_comm : ' polyComm ; complete_add_comm : ' polyComm ; mul_comm : ' polyComm ; emul_comm : ' polyComm ; endomul_scalar_comm : ' polyComm ; chacha_comm : ' polyComm array option } [ @@ deriving yojson ] yojson type ( ' fr , ' sRS , ' polyComm ) ' polyComm verifier_index = ( ' fr , ' sRS , ' polyComm ) ' polyComm Kimchi_types . VerifierIndex . verifier_index = { domain : ' fr domain ; max_poly_size : int ; max_quot_size : int ; srs : ' sRS ; evals : ' polyComm verification_evals ; shifts : ' fr array ; lookup_index : ' polyComm Lookup . t option } [ @@ deriving yojson ] yojson type ' f or_infinity = ' f Kimchi_types . or_infinity = | Infinity | Finite of ( ' f * ' f ) ' f [ @@ deriving yojson ] yojson type ' g polycomm = ' g Kimchi_types . poly_comm = { unshifted : ' g array ; shifted : ' g option } [ @@ deriving yojson ] yojson let to_yojson fp fq = verifier_index_to_yojson fp ( fun _ -> ` Null ) Null ( polycomm_to_yojson ( or_infinity_to_yojson fq ) fq ) fq end
module Data = struct [ %% versioned module Stable = struct module V1 = struct type t = { constraints : int } [ @@ deriving yojson ] yojson let to_latest = Fn . id end end ] end end
module Repr = struct [ %% versioned module Stable = struct module V2 = struct type t = { commitments : Backend . Tock . Curve . Affine . Stable . V1 . t Plonk_verification_key_evals . Stable . V2 . t ; step_domains : Domains . Stable . V2 . t array ; data : Data . Stable . V1 . t } [ @@ deriving to_yojson ] to_yojson let to_latest = Fn . id end end ] end end [ %% versioned_binable
module Stable = struct module V2 = struct type t = { commitments : Backend . Tock . Curve . Affine . t Plonk_verification_key_evals . t ; step_domains : Domains . t array ; index : ( Impls . Wrap . Verification_key . t [ @ to_yojson Verifier_index_json . to_yojson Backend . Tock . Field . to_yojson Backend . Tick . Field . to_yojson ] to_yojson ) ; data : Data . t } [ @@ deriving fields , to_yojson ] to_yojson let to_latest = Fn . id let of_repr srs { Repr . commitments = c ; step_domains ; data = d } = let t : Impls . Wrap . Verification_key . t = let log2_size = Int . ceil_log2 d . constraints in let d = Domain . Pow_2_roots_of_unity log2_size in let max_quot_size = Common . max_quot_size_int ( Domain . size d ) d in { domain = { log_size_of_group = log2_size ; group_gen = Backend . Tock . Field . domain_generator log2_size } ; max_poly_size = 1 lsl Nat . to_int Rounds . Wrap . n ; max_quot_size ; srs ; evals = ( let g ( x , y ) y = { Kimchi_types . unshifted = [ | Kimchi_types . Finite ( x , y ) y ] | ; shifted = None } in { sigma_comm = Array . map ~ f : g ( Vector . to_array c . sigma_comm ) sigma_comm ; coefficients_comm = Array . map ~ f : g ( Vector . to_array c . coefficients_comm ) coefficients_comm ; generic_comm = g c . generic_comm ; mul_comm = g c . mul_comm ; psm_comm = g c . psm_comm ; emul_comm = g c . emul_comm ; complete_add_comm = g c . complete_add_comm ; endomul_scalar_comm = g c . endomul_scalar_comm ; chacha_comm = None } ) ; shifts = Common . tock_shifts ~ log2_size ; lookup_index = None } in { commitments = c ; step_domains ; data = d ; index = t } include Binable . Of_binable ( Repr . Stable . V2 ) V2 ( struct type nonrec t = t let to_binable { commitments ; step_domains ; data ; index = _ } = { Repr . commitments ; data ; step_domains } let of_binable r = of_repr ( Backend . Tock . Keypair . load_urs ( ) ) r end ) end end end ] end
let dummy_commitments g = let open Plonk_types in { Plonk_verification_key_evals . sigma_comm = Vector . init Permuts . n ~ f ( : fun _ -> g ) g ; coefficients_comm = Vector . init Columns . n ~ f ( : fun _ -> g ) g ; generic_comm = g ; psm_comm = g ; complete_add_comm = g ; mul_comm = g ; emul_comm = g ; endomul_scalar_comm = g }
let dummy = lazy ( let rows = Domain . size ( Common . wrap_domains ~ proofs_verified : 2 ) 2 . h in let g = Backend . Tock . Curve ( . to_affine_exn one ) one in { Repr . commitments = dummy_commitments g ; step_domains = [ ] || ; data = { constraints = rows } } |> Stable . Latest . of_repr ( Kimchi_bindings . Protocol . SRS . Fq . create 1 ) 1 )
module Base = struct module type S = sig type t type ledger_proof type invalid = [ ` Invalid_keys of Signature_lib . Public_key . Compressed . t list | ` Invalid_signature of Signature_lib . Public_key . Compressed . t list | ` Invalid_proof | ` Missing_verification_key of Signature_lib . Public_key . Compressed . t list ] [ @@ deriving bin_io , to_yojson ] to_yojson val invalid_to_string : invalid -> string val verify_commands : t -> Mina_base . User_command . Verifiable . t list -> [ ` Valid of Mina_base . User_command . Valid . t | ` Valid_assuming of ( Pickles . Side_loaded . Verification_key . t * Mina_base . Zkapp_statement . t * Pickles . Side_loaded . Proof . t ) list | invalid ] list Deferred . Or_error . t val verify_blockchain_snarks : t -> Blockchain_snark . Blockchain . t list -> bool Or_error . t Deferred . t val verify_transaction_snarks : t -> ( ledger_proof * Mina_base . Sok_message . t ) t list -> bool Or_error . t Deferred . t val get_blockchain_verification_key : t -> Pickles . Verification_key . t Or_error . t Deferred . t end end
module type S = sig include Base . S val create : logger : Logger . t -> proof_level : Genesis_constants . Proof_level . t -> constraint_constants : Genesis_constants . Constraint_constants . t -> pids : Child_processes . Termination . t -> conf_dir : string option -> t Deferred . t end
let extract_sources sources = let erl = List . hd sources in let ml = List . hd ( List . tl sources ) in ( erl , ml )
let compare_parsetree a b = if a = b then Ok ( ) else Error ` not_equal
let remove_locations parsetree = let open Ast_mapper in let open Parsetree in let map_structure_item sub { pstr_loc = loc ; pstr_desc = desc } = let open Ast_helper . Str in let loc = sub . location sub loc in match desc with | Pstr_value ( _r , vbs ) -> value ~ loc Recursive ( List . map ( sub . value_binding sub ) vbs ) | Pstr_eval ( x , attrs ) -> let attrs = sub . attributes sub attrs in eval ~ loc ~ attrs ( sub . expr sub x ) | Pstr_primitive vd -> primitive ~ loc ( sub . value_description sub vd ) | Pstr_type ( rf , l ) -> type_ ~ loc rf ( List . map ( sub . type_declaration sub ) l ) | Pstr_typext te -> type_extension ~ loc ( sub . type_extension sub te ) | Pstr_exception ed -> exception_ ~ loc ( sub . type_exception sub ed ) | Pstr_module x -> module_ ~ loc ( sub . module_binding sub x ) | Pstr_recmodule l -> rec_module ~ loc ( List . map ( sub . module_binding sub ) l ) | Pstr_modtype x -> modtype ~ loc ( sub . module_type_declaration sub x ) | Pstr_open x -> open_ ~ loc ( sub . open_declaration sub x ) | Pstr_class l -> class_ ~ loc ( List . map ( sub . class_declaration sub ) l ) | Pstr_class_type l -> class_type ~ loc ( List . map ( sub . class_type_declaration sub ) l ) | Pstr_include x -> include_ ~ loc ( sub . include_declaration sub x ) | Pstr_extension ( x , attrs ) -> let attrs = sub . attributes sub attrs in extension ~ loc ~ attrs ( sub . extension sub x ) | Pstr_attribute x -> attribute ~ loc ( sub . attribute sub x ) in let mapper = { Ast_mapper . default_mapper with location = ( fun _this _l -> Location . none ) ; structure_item = map_structure_item ; } in mapper . structure mapper parsetree
let verify sources = let erl , ml = extract_sources sources in let ml_parsetree = Ocaml . parse_implementation ~ dump_ast : false ~ source_file : ml |> remove_locations in Printast . structure 0 Format . std_formatter ml_parsetree ; Format . fprintf Format . std_formatter " \ n \ n " ; %! let erl_parsetree = Erlang_as_ocaml . parse ~ source_file : erl ~ dump_ast : true in compare_parsetree erl_parsetree ml_parsetree
let ( . <> ) f g x = f ( g x )
module Scheduler = Carton . Make ( Fiber )
module SHA1 = struct include Digestif . SHA1 let feed ctx ? off ? len bs = feed_bigstring ctx ? off ? len bs let null = digest_string " " let length = digest_size let compare a b = String . compare ( to_raw_string a ) ( to_raw_string b ) end
module Verify = Carton . Dec . Verify ( SHA1 ) ( Scheduler ) ( Fiber )
module First_pass = Carton . Dec . Fp ( SHA1 )
let sched = let open Scheduler in { Carton . bind = ( fun x f -> inj ( bind ( prj x ) ( fun x -> prj ( f x ) ) ) ) ; return = ( fun x -> inj ( return x ) ) ; }
let z = De . bigstring_create De . io_buffer_size
let allocate bits = De . make_window ~ bits
let replace hashtbl k v = try let v ' = Hashtbl . find hashtbl k in if v < v ' then Hashtbl . replace hashtbl k v ' with _ -> Hashtbl . add hashtbl k v
let never _ = assert false
let digest ~ kind ( ? off = 0 ) ? len buf = let len = match len with Some len -> len | None -> Bigstringaf . length buf - off in let ctx = SHA1 . empty in let ctx = match kind with | ` A -> SHA1 . feed_string ctx ( Fmt . str " commit % d \ 000 " len ) | ` B -> SHA1 . feed_string ctx ( Fmt . str " tree % d \ 000 " len ) | ` C -> SHA1 . feed_string ctx ( Fmt . str " blob % d \ 000 " len ) | ` D -> SHA1 . feed_string ctx ( Fmt . str " tag % d \ 000 " len ) in let ctx = SHA1 . feed_bigstring ctx ~ off ~ len buf in SHA1 . get ctx
let ( >>= ) = sched . bind
let read fd buf ~ off ~ len = let len = input fd buf off len in return len
let first_pass fpath = let ic = open_in ( Fpath . to_string fpath ) in let zw = De . make_window ~ bits : 15 in let allocate _ = zw in First_pass . check_header sched read ic >>= fun ( max , _ , _ ) -> seek_in ic 0 ; let decoder = First_pass . decoder ~ o : z ~ allocate ( ` Channel ic ) in let children = Hashtbl . create 0x100 in let where = Hashtbl . create 0x100 in let weight = Hashtbl . create 0x100 in let length = Hashtbl . create 0x100 in let carbon = Hashtbl . create 0x100 in let matrix = Array . make max Verify . unresolved_node in let rec go decoder = match First_pass . decode decoder with | ` Await _ | ` Peek _ -> assert false | ` Entry ( { First_pass . kind = Base _ ; offset ; size ; consumed ; _ } , decoder ) -> let n = First_pass . count decoder - 1 in Hashtbl . add weight offset size ; Hashtbl . add length offset size ; Hashtbl . add carbon offset consumed ; Hashtbl . add where offset n ; matrix . ( n ) <- Verify . unresolved_base ~ cursor : offset ; go decoder | ` Entry ( { First_pass . kind = Ofs { sub = s ; source ; target } ; offset ; size ; consumed ; _ ; } , decoder ) -> let n = First_pass . count decoder - 1 in replace weight Int64 . ( sub offset ( Int64 . of_int s ) ) source ; replace weight offset target ; Hashtbl . add length offset size ; Hashtbl . add carbon offset consumed ; Hashtbl . add where offset n ; ( try let vs = Hashtbl . find children ( ` Ofs Int64 . ( sub offset ( of_int s ) ) ) in Hashtbl . replace children ( ` Ofs Int64 . ( sub offset ( of_int s ) ) ) ( offset :: vs ) with _ -> Hashtbl . add children ( ` Ofs Int64 . ( sub offset ( of_int s ) ) ) [ offset ] ) ; go decoder | ` Entry ( { First_pass . kind = Ref { ptr ; target ; source } ; offset ; size ; consumed ; _ ; } , decoder ) -> let n = First_pass . count decoder - 1 in replace weight offset ( Stdlib . max target source ) ; Hashtbl . add length offset size ; Hashtbl . add carbon offset consumed ; Hashtbl . add where offset n ; ( try let vs = Hashtbl . find children ( ` Ref ptr ) in Hashtbl . replace children ( ` Ref ptr ) ( offset :: vs ) with _ -> Hashtbl . add children ( ` Ref ptr ) [ offset ] ) ; go decoder | ` End hash -> close_in ic ; return ( Ok hash ) | ` Malformed err -> return ( Error ( ` Msg err ) ) in go decoder >>= function | Error _ as err -> return err | Ok hash -> let where ~ cursor = Hashtbl . find where cursor in let children ~ cursor ~ uid = match ( Hashtbl . find_opt children ( ` Ofs cursor ) , Hashtbl . find_opt children ( ` Ref uid ) ) with | Some a , Some b -> List . sort_uniq compare ( a @ b ) | Some x , None | None , Some x -> x | None , None -> [ ] in let weight ~ cursor = Hashtbl . find weight cursor in let oracle = { Carton . Dec . where ; children ; digest ; weight } in return ( Ok ( hash , oracle , matrix , length , carbon ) )
let map ~ max fd ~ pos len = let len = Stdlib . min len ( Int64 . to_int ( Int64 . sub max pos ) ) in let res = Unix . map_file fd ~ pos Bigarray . char Bigarray . c_layout false [ | len ] | in Bigarray . array1_of_genarray res
let second_pass fpath ( hash , oracle , matrix ) = let open Fiber in let fd = Unix . openfile ( Fpath . to_string fpath ) Unix . [ O_RDONLY ] 0o644 in let max = ( Unix . LargeFile . fstat fd ) . Unix . LargeFile . st_size in let map fd ~ pos len = map ~ max fd ~ pos len in let pack = Carton . Dec . make fd ~ allocate ~ z ~ uid_ln : SHA1 . length ~ uid_rw : SHA1 . of_raw_string never in Verify . verify ~ threads ( : Fiber . get_concurrency ( ) ) pack ~ map ~ oracle ~ verbose : ignore ~ matrix >>= fun ( ) -> match Array . for_all Verify . is_resolved matrix with | false -> return ( R . error_msgf " Thin PACK file " ) | true -> return ( Ok ( hash , matrix ) )
let pp_kind ppf = function | ` A -> Fmt . string ppf " commit " | ` B -> Fmt . string ppf " tree " | ` C -> Fmt . string ppf " blob " | ` D -> Fmt . string ppf " tag "
let pp_delta ppf status = match Verify . source_of_status status with | Some uid -> Fmt . pf ppf " % d % a " ( Verify . depth_of_status status ) SHA1 . pp uid | None -> ( )
let verify_hash ~ memory hash = let max = Bigstringaf . length memory in let hash ' = SHA1 . of_raw_string ( Bigstringaf . substring memory ~ off ( : max - ( 2 * SHA1 . length ) ) ~ len : SHA1 . length ) in SHA1 . equal hash hash '
let verify ~ verbose fpath hash length carbon matrix = let fd = Unix . openfile ( Fpath . to_string fpath ) Unix . [ O_RDONLY ] 0o644 in let len = ( Unix . fstat fd ) . Unix . st_size in let memory = Unix . map_file fd ~ pos : 0L Bigarray . char Bigarray . c_layout false [ | len ] | in let memory = Bigarray . array1_of_genarray memory in Unix . close fd ; let idx = Carton . Dec . Idx . make memory ~ uid_ln : SHA1 . length ~ uid_rw : SHA1 . to_raw_string ~ uid_wr : SHA1 . of_raw_string in if not ( verify_hash ~ memory hash ) then return ( R . error_msgf " Invalid PACK hash " ) else match verbose with | false -> if Array . for_all ( Carton . Dec . Idx . exists idx . <> Verify . uid_of_status ) matrix then return ( Ok ( ) ) else return ( R . error_msgf " Invalid PACK file " ) | true -> ( let chains = Hashtbl . create 0x10 in let f status = let uid = Verify . uid_of_status status in let kind = Verify . kind_of_status status in let offset = Verify . offset_of_status status in let ( size : Carton . Dec . weight ) = Hashtbl . find length offset in let size_in_pack = Hashtbl . find carbon offset in let depth = Verify . depth_of_status status in ( match Hashtbl . find chains depth with | v -> Hashtbl . replace chains depth ( succ v ) | exception _ -> Hashtbl . replace chains depth 1 ) ; match Carton . Dec . Idx . find idx uid with | Some ( _crc , offset ' ) when offset = offset ' -> Fmt . pr " % a % a % d % d % Ld % a \ n " %! SHA1 . pp uid pp_kind kind ( size :> int ) size_in_pack offset pp_delta status | _ -> Fmt . failwith " Invalid PACK file " in let pp_chain ppf ( depth , n ) = match depth with | 0 -> Fmt . pf ppf " non delta : % d objects \ n " %! n | _ -> Fmt . pf ppf " chain length = % d : % d objects \ n " %! depth n in try Array . iter f matrix ; let chains = List . sort_uniq ( fun ( a , _ ) ( b , _ ) -> compare a b ) ( ( List . of_seq . <> Hashtbl . to_seq ) chains ) in Fmt . pr " % a " %! ( Fmt . list ~ sep : Fmt . nop pp_chain ) chains ; Fmt . pr " % a : ok \ n " %! Fpath . pp Fpath . ( set_ext " pack " ( base fpath ) ) ; return ( Ok ( ) ) with _exn -> return ( R . error_msgf " Invalid PACK file " ) )
let ( >>? ) x f = let open Fiber in x >>= function Ok x -> f x | Error err -> return ( Error err )
let run ~ verbose fpath = let pack = Fpath . set_ext " pack " fpath in Bos . OS . File . must_exist pack |> Fiber . return >>? fun pack -> first_pass pack |> Scheduler . prj >>? fun ( hash , oracle , matrix , length , carbon ) -> second_pass pack ( hash , oracle , matrix ) >>? fun ( hash , matrix ) -> verify ~ verbose fpath hash length carbon matrix |> Scheduler . prj
let run verbose fpath = match Fiber . run ( run ~ verbose fpath ) with | Ok ( ) -> Ok ( ) | Error ( ` Msg err ) -> Error ( Fmt . str " % s . " err )
let verbose = let doc = " After verifying the pack , show list of objects contained in the pack and \ histogram of delta chain length . " in Arg . ( value & flag & info [ " v " ; " verbose " ] ~ doc )
let fpath = let parser x = match Fpath . of_string x with | Ok v when Sys . file_exists x -> Ok v | Ok v -> R . error_msgf " % a not found " Fpath . pp v | Error _ as err -> err in Arg . conv ( parser , Fpath . pp )
let fpath = let doc = " The idx files to verify . " in Arg . ( required & pos ~ rev : true 0 ( some fpath ) None & info [ ] ~ doc )
let cmd = let doc = " Validate packed Git archive files " in let man = [ ` S Manpage . s_description ; ` P " Reads given idx file for packed Git archive created with the ( $ i , git ) \ ( $ i , pack - objets ) command and verifies idx file and the corresponding \ pack file . " ; ] in let info = Cmd . info " verify - pack " ~ doc ~ man in Cmd . v info Term . ( const run $ verbose $ fpath )
let ( ) = exit @@ Cmd . eval_result cmd
let parse s = Pb_parsing_parser . proto_ Pb_parsing_lexer . lexer ( Lexing . from_string s ) s
let ( ) = let proto = parse " message M { string no_label = 1 ; } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto2 " ; \ \ message M { \ string no_label = 1 ; \ } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ message M { \ string no_label = 1 ; \ repeated string r = 2 ; \ message S { \ string s_no_label = 3 ; \ repeated string s_r = 4 ; \ } \ } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> ( ) | exception E . Compilation_error _ -> assert ( assertfalse ) assertfalse
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ message M { \ required string no_label = 1 ; \ } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ message M { message S { \ required string no_label = 1 ; \ } } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ enum E { EN1 = 1 ; EN2 = 2 ; } \ message M { } \ " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ message M { \ enum E { EN1 = 1 ; EN2 = 2 ; } \ } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> assert ( assertfalse ) assertfalse | exception E . Compilation_error _ -> ( )
let ( ) = let proto = parse " \ syntax = " \ proto3 " ; \ \ message M { \ enum E { EN0 = 0 ; EN2 = 2 ; } \ } " in match Pb_parsing_util . finalize_proto_value proto with | _ -> ( ) | exception E . Compilation_error _ -> assert ( assertfalse ) assertfalse
let ( ) = print_endline " Verify syntax invariants . . . Ok "
let failwith str = raise ( Failure str )
let ( ) @ a b = let a = List . rev a in let rec f a b = match b with | [ ] -> a | h :: t -> f ( h :: a ) t in List . rev ( f a b )
let reserved = [ " and " ; " always " ; " assign " ; " attribute " ; " begin " ; " buf " ; " bufif0 " ; " bufif1 " ; " case " ; " cmos " ; " deassign " ; " default " ; " defparam " ; " disable " ; " else " ; " endattribute " ; " end " ; " endcase " ; " endfunction " ; " endprimitive " ; " endmodule " ; " endtable " ; " endtask " ; " event " ; " for " ; " force " ; " forever " ; " fork " ; " function " ; " highhz0 " ; " highhz1 " ; " if " ; " initial " ; " inout " ; " input " ; " integer " ; " join " ; " large " ; " medium " ; " module " ; " nand " ; " negedge " ; " nor " ; " not " ; " notif0 " ; " notif1 " ; " nmos " ; " or " ; " output " ; " parameter " ; " pmos " ; " posedge " ; " primitive " ; " pulldown " ; " pullup " ; " pull0 " ; " pull1 " ; " rcmos " ; " reg " ; " release " ; " repeat " ; " rnmos " ; " rpmos " ; " rtran " ; " rtranif0 " ; " rtranif1 " ; " scalared " ; " small " ; " specify " ; " specparam " ; " strong0 " ; " strong1 " ; " supply0 " ; " supply1 " ; " table " ; " task " ; " tran " ; " tranif0 " ; " tranif1 " ; " time " ; " tri " ; " triand " ; " trior " ; " trireg " ; " tri0 " ; " tri1 " ; " vectored " ; " wait " ; " wand " ; " weak0 " ; " weak1 " ; " while " ; " wire " ; " wor " ]
let iteri f l = let rec iteri n l = match l with | [ ] -> ( ) | h :: t -> f n h ; iteri ( n + 1 ) t in iteri 0 l
let folds c s = List . fold_left ( fun s n -> if s = " " then n else n ^ c ^ s ) " " s
let write circuit = let inputs = Circuit . inputs circuit in let outputs = Circuit . outputs circuit in let buf = Buffer . create ( 10 * 1024 ) in let name = Circuit . mangle_names reserved prefix circuit in let write_signal_decl typ signal = let write typ name ass = if width signal = 1 then bprintf buf " % s % s % s ; \ n " typ name ass else bprintf buf " % s [ % d : 0 ] % s % s ; \ n " typ ( width signal - 1 ) name ass in let names = names signal in let name = name ( uid signal ) in let name0 = name 0 in write typ name0 " " ; if List . length names > 1 then iteri ( fun i _ -> write " wire " ( name ( i + 1 ) ) ( " = " ^ name0 ) ) ( List . tl names ) in let write_mem_decl s = match s with | Signal_mem ( id , mid , r , sp ) -> bprintf buf " reg [ % d : 0 ] % s [ 0 :% d ] ; \ n " ( width s - 1 ) ( name mid 0 ) ( sp . mem_size - 1 ) | _ -> failwith " can only write memories here " in bprintf buf " module % s ( " ( Circuit . name circuit ) ; bprintf buf " % s " ( folds " , " ( List . map ( fun s -> List . hd ( names s ) ) ( inputs @ outputs ) ) ) ; bprintf buf " ) ; \ n " ; List . iter ( write_signal_decl " input " ) inputs ; List . iter ( write_signal_decl " output " ) outputs ; let is_internal_signal s = not ( Circuit . is_input circuit s ) && not ( Circuit . is_output circuit s ) && not ( s = empty ) in let internal_signals = Circuit . filter is_internal_signal outputs in List . iter ( fun s -> if is_mem s then write_mem_decl s ; write_signal_decl ( if is_op Signal_mux s || is_reg s then " reg " else " wire " ) s ) internal_signals ; let write_logic s = let dep = List . nth ( deps s ) in let nameuid u = name u 0 in let name s = name ( uid s ) 0 in let edge s = if s = vdd then " posedge " else " negedge " in let cat s = fst ( List . fold_left ( fun ( s , i ) d -> if i = 0 then name d , i + 1 else s ^ " , " ^ name d , i + 1 ) ( " " , 0 ) ( deps s ) ) in let mux s = let deps = deps s in let sel = List . hd deps in let vals = List . tl deps in let nvals = List . length vals in let name_s = name s in bprintf buf " always @*\ n case ( % s ) \ n " ( name sel ) ; iteri ( fun i d -> if ( i + 1 ) <> nvals then ( bprintf buf " % i ' d % i : % s <= % s ; \ n " ( width sel ) i name_s ( name d ) ) else ( bprintf buf " default : % s <= % s ; \ n " name_s ( name d ) ) ) vals ; bprintf buf " endcase \ n " in let reg s = let d = List . hd ( deps s ) in match s with | Signal_reg ( _ , r ) -> begin if r . reg_reset = empty then bprintf buf " always ( @% s % s ) \ n " ( edge r . reg_clock_level ) ( name r . reg_clock ) else begin bprintf buf " always ( @% s % s , % s % s ) \ n " ( edge r . reg_clock_level ) ( name r . reg_clock ) ( edge r . reg_reset_level ) ( name r . reg_reset ) ; bprintf buf " if ( % s == % i ) " ( name r . reg_reset ) ( if r . reg_reset_level = vdd then 1 else 0 ) ; bprintf buf " % s <= % s ; else \ n " ( name s ) ( name r . reg_reset_value ) end ; if r . reg_clear <> empty then begin bprintf buf " if ( % s == % i ) " ( name r . reg_clear ) ( if r . reg_clear_level = vdd then 1 else 0 ) ; bprintf buf " % s <= % s ; else \ n " ( name s ) ( name r . reg_clear_value ) end ; if r . reg_enable = vdd then bprintf buf " % s <= % s ; \ n " ( name s ) ( name d ) else bprintf buf " if ( % s ) % s <= % s ; \ n " ( name r . reg_enable ) ( name s ) ( name d ) end | _ -> failwith " Cannot write non - register value here " in let mem s = match s with | Signal_mem ( id , muid , r , m ) -> begin let d = dep 0 in if r . reg_reset = empty then bprintf buf " always ( @% s % s ) \ n " ( edge r . reg_clock_level ) ( name r . reg_clock ) else begin bprintf buf " always ( @% s % s , % s % s ) \ n " ( edge r . reg_clock_level ) ( name r . reg_clock ) ( edge r . reg_reset_level ) ( name r . reg_reset ) ; bprintf buf " if ( % s == % i ) \ n " ( name r . reg_reset ) ( if r . reg_reset_level = vdd then 1 else 0 ) ; bprintf buf " begin \ n " ; for i = 0 to m . mem_size - 1 do bprintf buf " % s [ % i ] <= % s ; \ n " ( nameuid muid ) i ( name r . reg_reset_value ) done ; bprintf buf " end \ n " ; bprintf buf " else \ n " ; end ; if r . reg_clear <> empty then begin bprintf buf " if ( % s == % i ) \ n " ( name r . reg_clear ) ( if r . reg_clear_level = vdd then 1 else 0 ) ; bprintf buf " begin \ n " ; for i = 0 to m . mem_size - 1 do bprintf buf " % s [ % i ] <= % s ; \ n " ( nameuid muid ) i ( name r . reg_clear_value ) done ; bprintf buf " end \ n " ; bprintf buf " else \ n " ; end ; if r . reg_enable = vdd then bprintf buf " % s [ % s ] <= % s ; \ n " ( nameuid muid ) ( name m . mem_write_address ) ( name d ) else bprintf buf " if ( % s ) % s [ % s ] <= % s ; \ n " ( name r . reg_enable ) ( nameuid muid ) ( name m . mem_write_address ) ( name d ) ; bprintf buf " assign % s = % s [ % s ] ; \ n " ( name s ) ( nameuid muid ) ( name m . mem_read_address ) end | _ -> failwith " Cannot write non - memory value here " in let inst s = match s with | Signal_inst ( id , iuid , i ) -> begin let rec folds = function | [ ] -> " " | s :: [ ] -> s | h :: t -> h ^ " , " ^ ( folds t ) in let generic ( n , g ) = " . " ^ n ^ " ( " ^ ( match g with | ParamString ( s ) -> " " " \ ^ s ^ " " " \ | ParamInt ( i ) -> string_of_int i | ParamBool ( b ) -> if b then " 1 " else " 0 " | ParamFloat ( f ) -> string_of_float f ) ^ " ) " in let inport ( n , s ) = " . " ^ n ^ " ( " ^ ( name s ) ^ " ) " in let outport ( n , ( w , l ) ) = if width s = 1 then " . " ^ n ^ " ( " ^ ( name s ) ^ " ) " else " . " ^ n ^ " ( " ^ ( name s ) ^ " [ " ^ string_of_int ( w + l - 1 ) ^ " " : ^ string_of_int l ^ " ] ) " in let generics = List . map generic i . inst_generics in let inports = List . map inport i . inst_inputs in let outports = List . map outport i . inst_outputs in bprintf buf " % s \ n " i . inst_name ; if i . inst_generics <> [ ] then bprintf buf " ( # % s ) \ n " ( folds generics ) ; bprintf buf " % s \ n " ( nameuid iuid ) ; bprintf buf " ( % s ) ; \ n " ( folds ( inports @ outports ) ) ; end | _ -> failwith " expecting an instantiation " in match s with | Signal_empty -> failwith " Can ' t write empty signal " | Signal_const ( _ , v ) -> bprintf buf " assign % s = % i ' b % s ; \ n " ( name s ) ( width s ) v | Signal_wire ( _ , d ) -> bprintf buf " assign % s = % s ; \ n " ( name s ) ( name ! d ) | Signal_select ( _ , h , l ) -> bprintf buf " assign % s = % s [ % d :% d ] ; \ n " ( name s ) ( name ( dep 0 ) ) h l | Signal_op ( _ , op ) -> begin let op2 op = bprintf buf " assign % s = % s % s % s ; \ n " ( name s ) ( name ( dep 0 ) ) op ( name ( dep 1 ) ) in match op with | Signal_add -> op2 " " + | Signal_sub -> op2 " " - | Signal_mulu -> op2 " " * | Signal_muls -> bprintf buf " assign % s = $ signed ( % s ) * $ signed ( % s ) ; \ n " ( name s ) ( name ( dep 0 ) ) ( name ( dep 1 ) ) | Signal_and -> op2 " " & | Signal_or -> op2 " " | | Signal_xor -> op2 " " ^ | Signal_eq -> op2 " " == | Signal_not -> bprintf buf " assign % s = ~ % s ; \ n " ( name s ) ( name ( dep 0 ) ) | Signal_lt -> op2 " " < | Signal_cat -> bprintf buf " assign % s = { % s } ; \ n " ( name s ) ( cat s ) | Signal_mux -> mux s end | Signal_reg ( _ , _ ) -> reg s | Signal_mem ( _ , _ , _ , _ ) -> mem s | Signal_inst ( _ ) -> inst s in List . iter write_logic ( internal_signals @ outputs ) ; bprintf buf " endmodule \ n " ; buf
module Testbench = struct let write clocks resets circuit = let buf = Buffer . create ( 10 * 1024 ) in let inputs = Circuit . inputs circuit in let outputs = Circuit . outputs circuit in let name s = List . hd ( names s ) in let write_signal_decl t s = if width s = 1 then bprintf buf " % s % s ; \ n " t ( name s ) else bprintf buf " % s [ % i : 0 ] % s ; \ n " t ( width s ) ( name s ) in let write_reg = write_signal_decl " reg " in let write_wire = write_signal_decl " wire " in bprintf buf " module % s_tb ; \ n " ( Circuit . name circuit ) ; List . iter write_reg inputs ; List . iter write_wire outputs ; let write_assoc s = folds " , " ( List . map ( fun s -> " . " ^ ( name s ) ^ " ( " ^ ( name s ) ^ " ) " ) s ) in bprintf buf " /* design under test */\ n " ; bprintf buf " % s the_dut ( \ n " ( Circuit . name circuit ) ; bprintf buf " % s \ n " ( write_assoc ( inputs @ outputs ) ) ; bprintf buf " ) ; \ n " ; let clocks , inputs = List . partition ( fun s -> List . mem ( name s ) clocks ) inputs in let resets , inputs = List . partition ( fun s -> List . mem ( name s ) resets ) inputs in bprintf buf " /* stimulus */\ n " ; bprintf buf " initial begin \ n " ; bprintf buf " /* async reset */\ n " ; List . iter ( fun s -> bprintf buf " % s <= 0 ; \ n " ( name s ) ; ) clocks ; List . iter ( fun s -> bprintf buf " % s <= 1 ; \ n " ( name s ) ; ) resets ; bprintf buf " # 10 ; \ n " ; List . iter ( fun s -> bprintf buf " % s <= 0 ; \ n " ( name s ) ; ) resets ; bprintf buf " # 10 ; \ n " ; bprintf buf " /* clocking */\ n " ; bprintf buf " while ( 1 ) begin \ n " ; List . iter ( fun s -> bprintf buf " % s <= 1 ; \ n " ( name s ) ; ) clocks ; List . iter ( fun s -> bprintf buf " $ scanf ( " \%% b " , \ % s ) ; \ n " ( name s ) ; ) inputs ; bprintf buf " # 10 ; \ n " ; List . iter ( fun s -> bprintf buf " % s <= 0 ; \ n " ( name s ) ; ) clocks ; bprintf buf " # 10 ; \ n " ; bprintf buf " end \ n " ; bprintf buf " end \ n " ; bprintf buf " endmodule \ n " ; buf end
let write chan circ = let b = Verilog . write circ in output_string chan ( Buffer . contents b )