text
stringlengths
0
601k
let quote s = str " ` % s ' " s
let alts_str ( ? quoted = true ) alts = let quote = if quoted then quote else ( fun s -> s ) in match alts with | [ ] -> invalid_arg err_empty_list | [ a ] -> ( quote a ) | [ a ; b ] -> str " either % s or % s " ( quote a ) ( quote b ) | alts -> let rev_alts = List . rev alts in str " one of % s or % s " ( String . concat " , " ( List . rev_map quote ( List . tl rev_alts ) ) ) ( quote ( List . hd rev_alts ) )
let pr_white_str spaces ppf s = let left = ref 0 and right = ref 0 and len = String . length s in let flush ( ) = Format . pp_print_string ppf ( String . sub s ! left ( ! right - ! left ) ) ; incr right ; left := ! right ; in while ( ! right <> len ) do if s . [ ! right ] = ' \ n ' then ( flush ( ) ; Format . pp_force_newline ppf ( ) ) else if spaces && s . [ ! right ] = ' ' then ( flush ( ) ; Format . pp_print_space ppf ( ) ) else incr right ; done ; if ! left <> len then flush ( )
let pr_text = pr_white_str true
let pr_lines = pr_white_str false
let pr_to_temp_file pr v = try let exec = Filename . basename Sys . argv . ( 0 ) in let file , oc = Filename . open_temp_file exec " out " in let ppf = Format . formatter_of_out_channel oc in pr ppf v ; Format . pp_print_flush ppf ( ) ; close_out oc ; at_exit ( fun ( ) -> try Sys . remove file with Sys_error e -> ( ) ) ; Some file
let levenshtein_distance s t = let minimum a b c = min a ( min b c ) in let m = String . length s in let n = String . length t in let d = Array . make_matrix ( m + 1 ) ( n + 1 ) 0 in for i = 0 to m do d . ( i ) . ( 0 ) <- i done ; for j = 0 to n do d . ( 0 ) . ( j ) <- j done ; for j = 1 to n do for i = 1 to m do if s . [ i - 1 ] = t . [ j - 1 ] then d . ( i ) . ( j ) <- d . ( i - 1 ) . ( j - 1 ) else d . ( i ) . ( j ) <- minimum ( d . ( i - 1 ) . ( j ) + 1 ) ( d . ( i ) . ( j - 1 ) + 1 ) ( d . ( i - 1 ) . ( j - 1 ) + 1 ) done ; done ; d . ( m ) . ( n )
let suggest s candidates = let add ( min , acc ) name = let d = levenshtein_distance s name in if d = min then min , ( name :: acc ) else if d < min then d , [ name ] else min , acc in let dist , suggs = List . fold_left add ( max_int , [ ] ) candidates in if dist < 3 then suggs else [ ]
module Trie : sig type ' a t val empty : ' a t val is_empty : ' a t -> bool val add : ' a t -> string -> ' a -> ' a t val find : ' a t -> string -> [ ` Ok of ' a | ` Ambiguous | ` Not_found ] val ambiguities : ' a t -> string -> string list val of_list : ( string * ' a ) list -> ' a t module Cmap = Map . Make ( Char ) type ' a value = | Pre of ' a | Key of ' a | Amb | Nil type ' a t = { v : ' a value ; succs : ' a t Cmap . t } let empty = { v = Nil ; succs = Cmap . empty } let is_empty t = t = empty let add t k d = let rec aux t k len i d pre_d = if i = len then { v = Key d ; succs = t . succs } else let v = match t . v with | Amb | Pre _ -> Amb | Key _ as v -> v | Nil -> pre_d in let succs = let t ' = try Cmap . find k . [ i ] t . succs with Not_found -> empty in Cmap . add k . [ i ] ( aux t ' k len ( i + 1 ) d pre_d ) t . succs in { v ; succs } in aux t k ( String . length k ) 0 d ( Pre d ) let find_node t k = let rec aux t k len i = if i = len then t else aux ( Cmap . find k . [ i ] t . succs ) k len ( i + 1 ) in aux t k ( String . length k ) 0 let find t k = try match ( find_node t k ) . v with | Key v | Pre v -> ` Ok v | Amb -> ` Ambiguous | Nil -> ` Not_found with Not_found -> ` Not_found let ambiguities t p = try let t = find_node t p in match t . v with | Key _ | Pre _ | Nil -> [ ] | Amb -> let add_char s c = s ^ ( String . make 1 c ) in let rem_char s = String . sub s 0 ( ( String . length s ) - 1 ) in let to_list m = Cmap . fold ( fun k t acc -> ( k , t ) :: acc ) m [ ] in let rec aux acc p = function | ( ( c , t ) :: succs ) :: rest -> let p ' = add_char p c in let acc ' = match t . v with | Pre _ | Amb -> acc | Key _ -> ( p ' :: acc ) | Nil -> assert false in aux acc ' p ' ( ( to_list t . succs ) :: succs :: rest ) | [ ] :: [ ] -> acc | [ ] :: rest -> aux acc ( rem_char p ) rest | [ ] -> assert false in aux [ ] p ( to_list t . succs :: [ ] ) with Not_found -> [ ] let of_list l = List . fold_left ( fun t ( s , v ) -> add t s v ) empty l end
type env_info = { env_var : string ; env_doc : string ; env_docs : string ; }
type absence = | Error | Val of string Lazy . t
type opt_kind = | Flag | Opt | Opt_vopt of string
type pos_kind = | All | Nth of bool * int | Left of bool * int | Right of bool * int
type arg_info = { id : int ; absent : absence ; env_info : env_info option ; doc : string ; docv : string ; docs : string ; p_kind : pos_kind ; o_kind : opt_kind ; o_names : string list ; o_all : bool ; }
let arg_id = let c = ref 0 in fun ( ) -> let id = ! c in incr c ; if id > ! c then assert false else id
let is_opt a = a . o_names <> [ ]
let is_pos a = a . o_names = [ ]
module Amap = Map . Make ( struct type t = arg_info let compare a a ' = compare a . id a ' . id end )
type arg = | O of ( int * string * ( string option ) ) list | P of string list
type cmdline = arg Amap . t
type man_block = [ | ` S of string | ` P of string | ` Pre of string | ` I of string * string | ` Noblank ]
type term_info = { name : string ; version : string option ; tdoc : string ; tdocs : string ; sdocs : string ; man : man_block list ; }
type eval_info = { term : term_info * arg_info list ; main : term_info * arg_info list ; choices : ( term_info * arg_info list ) list ; env : string -> string option }
let eval_kind ei = if ei . choices = [ ] then ` Simple else if ( fst ei . term ) == ( fst ei . main ) then ` M_main else ` M_choice
module Manpage = struct type title = string * int * string * string * string type block = man_block type t = title * block list let p_indent = 7 let l_indent = 4 let escape subst esc buf s = let subst s = let len = String . length s in if not ( len > 1 && s . [ 1 ] = ' , ' ) then ( subst s ) else if len = 2 then " " else esc s . [ 0 ] ( String . sub s 2 ( len - 2 ) ) in try Buffer . clear buf ; Buffer . add_substitute buf subst s ; let s = Buffer . contents buf in Buffer . clear buf ; Buffer . add_substitute buf subst s ; Buffer . contents buf with Not_found -> invalid_arg ( err_doc_string s ) let pr_tokens ( ? groff = false ) ppf s = let is_space = function ' ' | ' \ n ' | ' \ r ' | ' \ t ' -> true | _ -> false in let len = String . length s in let i = ref 0 in try while ( true ) do while ( ! i < len && is_space s . [ ! i ] ) do incr i done ; let start = ! i in if start = len then raise Exit ; while ( ! i < len && not ( is_space s . [ ! i ] ) && not ( s . [ ! i ] = ' ' ) ) - do incr i done ; pr_str ppf ( String . sub s start ( ! i - start ) ) ; if ! i = len then raise Exit ; if s . [ ! i ] = ' ' - then ( incr i ; if groff then pr_str ppf " " \\- else pr_char ppf ' ' ) ; - if ( ! i < len && is_space s . [ ! i ] ) then ( if groff then pr_char ppf ' ' else Format . pp_print_space ppf ( ) ) done with Exit -> ( ) let plain_esc c s = match c with ' g ' -> " " | _ -> s let pr_indent ppf c = for i = 1 to c do pr_char ppf ' ' done let pr_plain_blocks subst ppf ts = let buf = Buffer . create 1024 in let escape t = escape subst plain_esc buf t in let pr_tokens ppf t = pr_tokens ppf ( escape t ) in let rec aux = function | [ ] -> ( ) | t :: ts -> begin match t with | ` Noblank -> ( ) | ` P s -> pr ppf " % a [ @% a ] , " @@ pr_indent p_indent pr_tokens s | ` S s -> pr ppf " [ @% a ] " @ pr_tokens s | ` Pre s -> pr ppf " % a [ @% a ] , " @@ pr_indent p_indent pr_lines ( escape s ) | ` I ( label , s ) -> let label = escape label in let ll = String . length label in pr ppf " [ @% a [ @% a ] " @ pr_indent p_indent pr_tokens label ; if s = " " then ( ) else if ll < l_indent then pr ppf " % a [ @% a ] ] , " @@@ pr_indent ( l_indent - ll ) pr_tokens s else pr ppf " @\ n % a [ @% a ] ] , " @@@ pr_indent ( p_indent + l_indent ) pr_tokens s end ; begin match ts with | ` Noblank :: ts -> aux ts | ts -> Format . pp_print_cut ppf ( ) ; aux ts end in aux ts let pr_plain_page subst ppf ( _ , text ) = pr ppf " [ @< v >% a ] " @ ( pr_plain_blocks subst ) text let groff_esc c s = match c with | ' i ' -> ( str " \\ fI % s \\ fR " s ) | ' b ' -> ( str " \\ fB % s \\ fR " s ) | ' p ' -> " " | _ -> s let pr_groff_lines ppf s = let left = ref 0 and right = ref 0 and len = String . length s in let flush ( ) = Format . pp_print_string ppf ( String . sub s ! left ( ! right - ! left ) ) ; incr right ; left := ! right ; in while ( ! right <> len ) do if s . [ ! right ] = ' \ n ' then ( flush ( ) ; Format . pp_force_newline ppf ( ) ) else if s . [ ! right ] = ' ' - then ( flush ( ) ; pr_str ppf " " ) \\- else incr right ; done ; if ! left <> len then flush ( ) let pr_groff_blocks subst ppf text = let buf = Buffer . create 1024 in let escape t = escape subst groff_esc buf t in let pr_tokens ppf t = pr_tokens ~ groff : true ppf ( escape t ) in let pr_block = function | ` P s -> pr ppf " @\ n . P @\ n % a " pr_tokens s | ` Pre s -> pr ppf " @\ n . P @\ n . nf @\ n % a @\ n . fi " pr_groff_lines ( escape s ) | ` S s -> pr ppf " @\ n . SH % a " pr_tokens s | ` Noblank -> pr ppf " @\ n . sp - 1 " | ` I ( l , s ) -> pr ppf " @\ n . TP 4 @\ n % a @\ n % a " pr_tokens l pr_tokens s in List . iter pr_block text let pr_groff_page subst ppf ( ( n , s , a1 , a2 , a3 ) , t ) = pr ppf " . " \\\ Pipe this output to groff - man - Tutf8 | less @\ n \ . " \\\@\ n \ . TH " \% s " \ % d " \% s " \ " \% s " \ " \% s " \@\ n \ . " \\\ Disable hyphenation and ragged - right @\ n \ . nh @\ n \ . ad l \ % a " @? n s a1 a2 a3 ( pr_groff_blocks subst ) t let find_cmd cmds = let test , null = match Sys . os_type with | " Win32 " -> " where " , " NUL " | _ -> " type " , " / dev / null " in let cmd c = Sys . command ( str " % s % s 1 >% s 2 >% s " test c null null ) = 0 in try Some ( List . find cmd cmds ) with Not_found -> None let pr_to_pager print ppf v = let pager = let cmds = [ " less " ; " more " ] in let cmds = try ( Sys . getenv " PAGER " ) :: cmds with Not_found -> cmds in let cmds = try ( Sys . getenv " MANPAGER " ) :: cmds with Not_found -> cmds in find_cmd cmds in match pager with | None -> print ` Plain ppf v | Some pager -> let cmd = match ( find_cmd [ " groff " ; " nroff " ] ) with | None -> begin match pr_to_temp_file ( print ` Plain ) v with | None -> None | Some f -> Some ( str " % s < % s " pager f ) end | Some c -> begin match pr_to_temp_file ( print ` Groff ) v with | None -> None | Some f -> let xroff = if c = " groff " then c ^ " - Tascii - P - c " else c in Some ( str " % s - man < % s | % s " xroff f pager ) end in match cmd with | None -> print ` Plain ppf v | Some cmd -> if ( Sys . command cmd ) <> 0 then print ` Plain ppf v let rec print ( ? subst = fun x -> x ) fmt ppf page = match fmt with | ` Pager -> pr_to_pager ( print ~ subst ) ppf page | ` Plain -> pr_plain_page subst ppf page | ` Groff -> pr_groff_page subst ppf page end
module Help = struct let invocation ( ? sep = ' ' ) ei = match eval_kind ei with | ` Simple | ` M_main -> ( fst ei . main ) . name | ` M_choice -> str " % s % c % s " ( fst ei . main ) . name sep ( fst ei . term ) . name let title ei = let prog = String . capitalize ( fst ei . main ) . name in let name = String . uppercase ( invocation ~ sep ' ' :- ei ) in let left_footer = prog ^ match ( fst ei . main ) . version with | None -> " " | Some v -> str " % s " v in let center_header = str " % s Manual " prog in name , 1 , " " , left_footer , center_header let name_section ei = let tdoc d = if d = " " then " " else ( str " - % s " d ) in [ ` S " NAME " ; ` P ( str " % s % s " ( invocation ~ sep ' ' :- ei ) ( tdoc ( fst ei . term ) . tdoc ) ) ; ] let synopsis ei = match eval_kind ei with | ` M_main -> str " ( $ b , % s ) ( $ i , COMMAND ) . . . " ( invocation ei ) | ` Simple | ` M_choice -> let rev_cmp ( p , _ ) ( p ' , _ ) = match p ' , p with | p , All -> - 1 | All , p -> 1 | Left _ , Right _ -> - 1 | Right _ , Left _ -> 1 | Left ( false , k ) , Nth ( false , k ' ) | Nth ( false , k ) , Nth ( false , k ' ) | Nth ( false , k ) , Right ( false , k ' ) -> if k <= k ' then - 1 else 1 | Nth ( false , k ) , Left ( false , k ' ) | Right ( false , k ) , Nth ( false , k ' ) -> if k >= k ' then 1 else - 1 | Left ( true , k ) , Nth ( true , k ' ) | Nth ( true , k ) , Nth ( true , k ' ) | Nth ( true , k ) , Right ( true , k ' ) -> if k >= k ' then - 1 else 1 | Nth ( true , k ) , Left ( true , k ' ) | Right ( true , k ) , Nth ( true , k ' ) -> if k <= k ' then 1 else - 1 | p , p ' -> compare p p ' in let rec format_pos acc = function | a :: al -> if is_opt a then format_pos acc al else let v = if a . docv = " " then " ( $ i , ARG ) " else str " ( $ i , % s ) " a . docv in let v = if a . absent = Error then str " % s " v else str " [ % s ] " v in let v = v ^ match a . p_kind with Nth _ -> " " | _ -> " . . . " in format_pos ( ( a . p_kind , v ) :: acc ) al | [ ] -> acc in let args = List . sort rev_cmp ( format_pos [ ] ( snd ei . term ) ) in let args = String . concat " " ( List . rev_map snd args ) in str " ( $ b , % s ) [ ( $ i , OPTION ) ] . . . % s " ( invocation ei ) args let get_synopsis_section ei = let rec extract_synopsis syn = function | ` S _ :: _ as man -> List . rev syn , man | block :: rest -> extract_synopsis ( block :: syn ) rest | [ ] -> List . rev syn , [ ] in match ( fst ei . term ) . man with | ` S " SYNOPSIS " as s :: rest -> extract_synopsis [ s ] rest | man -> [ ` S " SYNOPSIS " ; ` P ( synopsis ei ) ; ] , man let or_env a = match a . env_info with | None -> " " | Some v -> str " or ( $ i , % s ) env " v . env_var let make_arg_label a = if is_pos a then str " ( $ i , % s ) " a . docv else let fmt_name var = match a . o_kind with | Flag -> fun n -> str " ( $ b , % s ) % s " n ( or_env a ) | Opt -> fun n -> if String . length n > 2 then str " ( $ b , % s ) ( =$ i , % s ) " n var else str " ( $ b , % s ) ( $ i , % s ) " n var | Opt_vopt _ -> fun n -> if String . length n > 2 then str " ( $ b , % s ) [ ( =$ i , % s ) ] " n var else str " ( $ b , % s ) [ ( $ i , % s ) ] " n var in let var = if a . docv = " " then " VAL " else a . docv in let names = List . sort compare a . o_names in let s = String . concat " , " ( List . rev_map ( fmt_name var ) names ) in s let arg_info_substs ~ buf a doc = let subst = function | " docv " -> str " ( $ i , % s ) " a . docv | " opt " when is_opt a -> let k = String . lowercase ( List . hd ( List . sort compare a . o_names ) ) in str " ( $ b , % s ) " k | " env " when a . env_info <> None -> begin match a . env_info with | None -> assert false | Some v -> str " ( $ i , % s ) " v . env_var end | s -> str " ( $% s ) " s in try Buffer . clear buf ; Buffer . add_substitute buf subst doc ; Buffer . contents buf with Not_found -> invalid_arg ( err_doc_string doc ) let make_arg_items ei = let buf = Buffer . create 200 in let cmp a a ' = let c = compare a . docs a ' . docs in if c <> 0 then c else match is_opt a , is_opt a ' with | true , true -> let key names = let k = String . lowercase ( List . hd ( List . sort rev_compare names ) ) in if k . [ 1 ] = ' ' - then String . sub k 1 ( String . length k - 1 ) else k in compare ( key a . o_names ) ( key a ' . o_names ) | false , false -> compare ( String . lowercase a . docv ) ( String . lowercase a ' . docv ) | true , false -> - 1 | false , true -> 1 in let format a = let absent = match a . absent with | Error -> " " | Val v -> match Lazy . force v with | " " -> " " | v -> str " absent =% s % s " v ( or_env a ) in let optvopt = match a . o_kind with | Opt_vopt v -> str " default =% s " v | _ -> " " in let argvdoc = match optvopt , absent with | " " , " " -> " " | s , " " | " " , s -> str " ( % s ) " s | s , s ' -> str " ( % s ) ( % s ) " s s ' in ( a . docs , ` I ( make_arg_label a ^ argvdoc , ( arg_info_substs ~ buf a a . doc ) ) ) in let is_arg_item a = not ( is_pos a && ( a . docv = " " || a . doc = " " ) ) in let l = List . sort cmp ( List . filter is_arg_item ( snd ei . term ) ) in List . rev_map format l let make_env_items_rev ei = let buf = Buffer . create 200 in let cmp a a ' = let e ' = match a ' . env_info with None -> assert false | Some a ' -> a ' in let e = match a . env_info with None -> assert false | Some a -> a in let c = compare e . env_docs e ' . env_docs in if c <> 0 then c else compare e . env_var e ' . env_var in let format a = let e = match a . env_info with None -> assert false | Some a -> a in ( e . env_docs , ` I ( str " ( $ i , % s ) " e . env_var , arg_info_substs ~ buf a e . env_doc ) ) in let is_env_item a = a . env_info <> None in let l = List . sort cmp ( List . filter is_env_item ( snd ei . term ) ) in List . rev_map format l let make_cmd_items ei = match eval_kind ei with | ` Simple | ` M_choice -> [ ] | ` M_main -> let add_cmd acc ( ti , _ ) = ( ti . tdocs , ` I ( ( str " ( $ b , % s ) " ti . name ) , ti . tdoc ) ) :: acc in List . sort rev_compare ( List . fold_left add_cmd [ ] ei . choices ) let text ei = let rec merge_items acc to_insert mark il = function | ` S s as sec :: ts -> let acc = List . rev_append to_insert acc in let acc = if mark then sec :: ` Orphan_mark :: acc else sec :: acc in let to_insert , il = List . partition ( fun ( n , _ ) -> n = s ) il in let to_insert = List . rev_map ( fun ( _ , i ) -> i ) to_insert in let to_insert = ( to_insert :> [ ` Orphan_mark | Manpage . block ] list ) in merge_items acc to_insert ( s = " DESCRIPTION " ) il ts | t :: ts -> let t = ( t :> [ ` Orphan_mark | Manpage . block ] ) in merge_items ( t :: acc ) to_insert mark il ts | [ ] -> let acc = List . rev_append to_insert acc in ( if mark then ` Orphan_mark :: acc else acc ) , il in let rec merge_orphans acc orphans = function | ` Orphan_mark :: ts -> let rec merge acc s = function | [ ] -> ( ` S s ) :: acc | ( s ' , i ) :: ss -> let i = ( i :> Manpage . block ) in if s = s ' then merge ( i :: acc ) s ss else merge ( i :: ( ` S s ) :: acc ) s ' ss in let acc = match orphans with | [ ] -> acc | ( s , _ ) :: _ -> merge acc s orphans in merge_orphans acc [ ] ts | ( # Manpage . block as e ) :: ts -> merge_orphans ( e :: acc ) orphans ts | [ ] -> acc in let cmds = make_cmd_items ei in let args = make_arg_items ei in let envs_rev = make_env_items_rev ei in let items_rev = List . rev_append cmds ( List . rev_append args envs_rev ) in let cmp ( s , _ ) ( s ' , _ ) = match s , s with | " ENVIRONMENT VARIABLES " , _ -> 1 | s , " ENVIRONMENT VARIABLES " -> - 1 | s , s ' -> compare s s ' in let items = List . rev ( List . stable_sort cmp items_rev ) in let synopsis , man = get_synopsis_section ei in let rev_text , orphans = merge_items [ ` Orphan_mark ] [ ] false items man in synopsis @ merge_orphans [ ] orphans rev_text let ei_subst ei = function | " tname " -> ( fst ei . term ) . name | " mname " -> ( fst ei . main ) . name | s -> str " ( $% s ) " s let man ei = title ei , ( name_section ei ) @ ( text ei ) let print fmt ppf ei = Manpage . print ~ subst ( : ei_subst ei ) fmt ppf ( man ei ) let pr_synopsis ppf ei = pr ppf " [ @% s ] " @ ( Manpage . escape ( ei_subst ei ) Manpage . plain_esc ( Buffer . create 100 ) ( synopsis ei ) ) let pr_version ppf ei = match ( fst ei . main ) . version with | None -> assert false | Some v -> pr ppf " [ @% a ] . " @@ pr_text v end
module Err = struct let invalid kind s exp = str " invalid % s % s , % s " kind ( quote s ) exp let invalid_val = invalid " value " let no kind s = str " no % s % s " ( quote s ) kind let not_dir s = str " % s is not a directory " ( quote s ) let is_dir s = str " % s is a directory " ( quote s ) let element kind s exp = str " invalid element in % s ( ` % s ' ) : % s " kind s exp let sep_miss sep s = invalid_val s ( str " missing a ` % c ' separator " sep ) let unknown kind ( ? hints = [ ] ) v = let did_you_mean s = str " , did you mean % s " ? s in let hints = match hints with [ ] -> " . " | hs -> did_you_mean ( alts_str hs ) in str " unknown % s % s % s " kind ( quote v ) hints let ambiguous kind s ambs = str " % s % s ambiguous and could be % s " kind ( quote s ) ( alts_str ambs ) let pos_excess excess = str " too many arguments , don ' t know what to do with % s " ( String . concat " , " ( List . map quote excess ) ) let flag_value f v = str " option % s is a flag , it cannot take the argument % s " ( quote f ) ( quote v ) let opt_value_missing f = str " option % s needs an argument " ( quote f ) let opt_parse_value f e = str " option % s : % s " ( quote f ) e let env_parse_value var e = str " environment variable % s : % s " ( quote var ) e let opt_repeated f f ' = if f = f ' then str " option % s cannot be repeated " ( quote f ) else str " options % s and % s cannot be present at the same time " ( quote f ) ( quote f ' ) let pos_parse_value a e = if a . docv = " " then e else match a . p_kind with | Nth _ -> str " % s argument : % s " a . docv e | _ -> str " % s . . . arguments : % s " a . docv e let arg_missing a = if is_opt a then let rec long_name = function | n :: l -> if ( String . length n ) > 2 || l = [ ] then n else long_name l | [ ] -> assert false in str " required option % s is missing " ( long_name a . o_names ) else if a . docv = " " then str " a required argument is missing " else str " required argument % s is missing " a . docv let print ppf ei e = pr ppf " % s : [ @% a ] . " @@ ( fst ei . main ) . name pr_text e let pr_backtrace err ei e bt = let bt = let len = String . length bt in if len > 0 then String . sub bt 0 ( len - 1 ) else bt in pr err " % s : [ @ internal error , uncaught exception :@\ n % a ] . " @@ ( fst ei . main ) . name pr_lines ( str " % s \ n % s " ( Printexc . to_string e ) bt ) let pr_try_help ppf ei = let exec = Help . invocation ei in let main = ( fst ei . main ) . name in if exec = main then pr ppf " [ @< 2 > Try ` % s -- help ' for more information . ] " @ exec else pr ppf " [ @< 2 > Try ` % s -- help ' or ` % s -- help ' for more information . ] " @ exec main let pr_usage ppf ei e = pr ppf " [ @< v >% s : [ @% a ] , [ @@@ Usage : [ @% a ] ] , @@@% a ] . " @@ ( fst ei . main ) . name pr_text e Help . pr_synopsis ei pr_try_help ei end
module Cmdline : sig exception Error of string val choose_term : term_info -> ( term_info * ' a ) list -> string list -> term_info * string list val create : ? peek_opts : bool -> arg_info list -> string list -> cmdline val opt_arg : cmdline -> arg_info -> ( int * string * ( string option ) ) list val pos_arg : cmdline -> arg_info -> string list exception Error of string let opt_arg cl a = match try Amap . find a cl with Not_found -> assert false with O l -> l | _ -> assert false let pos_arg cl a = match try Amap . find a cl with Not_found -> assert false with P l -> l | _ -> assert false let choose_term ti choices = function | [ ] -> ti , [ ] | maybe :: args ' as args -> if String . length maybe > 1 && maybe . [ 0 ] = ' ' - then ti , args else let index = let add acc ( choice , _ ) = Trie . add acc choice . name choice in List . fold_left add Trie . empty choices in match Trie . find index maybe with | ` Ok choice -> choice , args ' | ` Not_found -> let all = Trie . ambiguities index " " in let hints = suggest maybe all in raise ( Error ( Err . unknown " command " ~ hints maybe ) ) | ` Ambiguous -> let ambs = List . sort compare ( Trie . ambiguities index maybe ) in raise ( Error ( Err . ambiguous " command " maybe ambs ) ) let arg_info_indexes al = let rec aux opti posi cl = function | a :: l -> if is_pos a then aux opti ( a :: posi ) ( Amap . add a ( P [ ] ) cl ) l else let add t name = Trie . add t name a in aux ( List . fold_left add opti a . o_names ) posi ( Amap . add a ( O [ ] ) cl ) l | [ ] -> opti , posi , cl in aux Trie . empty [ ] Amap . empty al let parse_opt_arg s = let l = String . length s in if s . [ 1 ] <> ' ' - then if l = 2 then s , None else String . sub s 0 2 , Some ( String . sub s 2 ( l - 2 ) ) else try let i = String . index s ' ' = in String . sub s 0 i , Some ( String . sub s ( i + 1 ) ( l - i - 1 ) ) with Not_found -> s , None let parse_args ~ peek_opts opti cl args = let rec aux k opti cl pargs = function | [ ] -> cl , ( List . rev pargs ) | " " -- :: args -> cl , ( List . rev_append pargs args ) | s :: args -> let is_opt s = String . length s > 1 && s . [ 0 ] = ' ' - in let is_short_opt s = String . length s = 2 && s . [ 0 ] = ' ' - in if not ( is_opt s ) then aux ( k + 1 ) opti cl ( s :: pargs ) args else let name , value = parse_opt_arg s in match Trie . find opti name with | ` Ok a -> let value , args = match value , a . o_kind with | Some v , Flag when is_short_opt name -> None , ( " " - ^ v ) :: args | Some v , _ -> value , args | None , Flag -> value , args | None , _ -> match args with | v :: rest -> if is_opt v then None , args else Some v , rest | [ ] -> None , args in let arg = O ( ( k , name , value ) :: opt_arg cl a ) in aux ( k + 1 ) opti ( Amap . add a arg cl ) pargs args | ` Not_found when peek_opts -> aux ( k + 1 ) opti cl pargs args | ` Not_found -> let hints = if String . length s <= 2 then [ ] else let short_opt , long_opt = if s . [ 1 ] <> ' ' - then s , Printf . sprintf " -% s " s else String . sub s 1 ( String . length s - 1 ) , s in let short_opt , _ = parse_opt_arg short_opt in let long_opt , _ = parse_opt_arg long_opt in let all = Trie . ambiguities opti " " - in match List . mem short_opt all , suggest long_opt all with | false , [ ] -> [ ] | false , l -> l | true , [ ] -> [ short_opt ] | true , l -> if List . mem short_opt l then l else short_opt :: l in raise ( Error ( Err . unknown " option " ~ hints name ) ) | ` Ambiguous -> let ambs = List . sort compare ( Trie . ambiguities opti name ) in raise ( Error ( Err . ambiguous " option " name ambs ) ) in aux 0 opti cl [ ] args let process_pos_args posi cl pargs = if pargs = [ ] then cl else let rec take n acc l = if n = 0 then List . rev acc else take ( n - 1 ) ( List . hd l :: acc ) ( List . tl l ) in let rec aux pargs last cl max_spec = function | a :: al -> let arg , max_spec = match a . p_kind with | All -> P pargs , last | Nth ( rev , k ) -> let k = if rev then last - k else k in let max_spec = max k max_spec in if k < 0 || k > last then P [ ] , max_spec else P ( [ List . nth pargs k ] ) , max_spec | Left ( rev , k ) -> let k = if rev then last - k else k in let max_spec = max k max_spec in if k <= 0 || k > last then P [ ] , max_spec else P ( take k [ ] pargs ) , max_spec | Right ( rev , k ) -> let k = if rev then last - k else k in if k < 0 || k >= last then P [ ] , last else P ( List . rev ( take ( last - k ) [ ] ( List . rev pargs ) ) ) , last in aux pargs last ( Amap . add a arg cl ) max_spec al | [ ] -> cl , max_spec in let last = List . length pargs - 1 in let cl , max_spec = aux pargs last cl ( - 1 ) posi in if last <= max_spec then cl else let excess = List . rev ( take ( last - max_spec ) [ ] ( List . rev pargs ) ) in raise ( Error ( Err . pos_excess excess ) ) let create ( ? peek_opts = false ) al args = let opti , posi , cl = arg_info_indexes al in let cl , pargs = parse_args ~ peek_opts opti cl args in if peek_opts then cl else process_pos_args posi cl pargs end
module Arg = struct type ' a parser = string -> [ ` Ok of ' a | ` Error of string ] type ' a printer = Format . formatter -> ' a -> unit type ' a converter = ' a parser * ' a printer type env = env_info type ' a arg_converter = ( eval_info -> cmdline -> ' a ) type ' a t = arg_info list * ' a arg_converter type info = arg_info let env_var ( ? docs = " ENVIRONMENT VARIABLES " ) ( ? doc = " See option ( $ opt ) . " ) env_var = { env_var = env_var ; env_doc = doc ; env_docs = docs } let ( & ) f x = f x let parse_error e = raise ( Cmdline . Error e ) let some ( ? none = " " ) ( parse , print ) = ( fun s -> match parse s with ` Ok v -> ` Ok ( Some v ) | ` Error _ as e -> e ) , ( fun ppf v -> match v with None -> pr_str ppf none | Some v -> print ppf v ) let info ? docs ( ? docv = " " ) ( ? doc = " " ) ? env names = let dash n = if String . length n = 1 then " " - ^ n else " " -- ^ n in let docs = match docs with | None -> if names = [ ] then " ARGUMENTS " else " OPTIONS " | Some s -> s in { id = arg_id ( ) ; absent = Val ( lazy " " ) ; env_info = env ; doc = doc ; docv = docv ; docs = docs ; p_kind = All ; o_kind = Flag ; o_names = List . rev_map dash names ; o_all = false ; } let env_bool_parse s = match String . lowercase s with | " " | " false " | " no " | " n " | " 0 " -> ` Ok false | " true " | " yes " | " y " | " 1 " -> ` Ok true | s -> ` Error ( Err . invalid_val s ( alts_str [ " true " ; " yes " ; " false " ; " no " ] ) ) let parse_to_list parser s = match parser s with | ` Ok v -> ` Ok [ v ] | ` Error _ as e -> e let try_env ei a parse ~ absent = match a . env_info with | None -> absent | Some env -> match ei . env env . env_var with | None -> absent | Some v -> match parse v with | ` Ok v -> v | ` Error e -> parse_error ( Err . env_parse_value env . env_var e ) let flag a = if is_pos a then invalid_arg err_not_opt else let convert ei cl = match Cmdline . opt_arg cl a with | [ ] -> try_env ei a env_bool_parse ~ absent : false | [ _ , _ , None ] -> true | [ _ , f , Some v ] -> parse_error ( Err . flag_value f v ) | ( _ , f , _ ) :: ( _ , g , _ ) :: _ -> parse_error ( Err . opt_repeated f g ) in [ a ] , convert let flag_all a = if is_pos a then invalid_arg err_not_opt else let a = { a with o_all = true } in let convert ei cl = match Cmdline . opt_arg cl a with | [ ] -> try_env ei a ( parse_to_list env_bool_parse ) ~ absent [ ] : | l -> let truth ( _ , f , v ) = match v with | None -> true | Some v -> parse_error ( Err . flag_value f v ) in List . rev_map truth l in [ a ] , convert let vflag v l = let convert _ cl = let rec aux fv = function | ( v , a ) :: rest -> begin match Cmdline . opt_arg cl a with | [ ] -> aux fv rest | [ _ , f , None ] -> begin match fv with | None -> aux ( Some ( f , v ) ) rest | Some ( g , _ ) -> parse_error ( Err . opt_repeated g f ) end | [ _ , f , Some v ] -> parse_error ( Err . flag_value f v ) | ( _ , f , _ ) :: ( _ , g , _ ) :: _ -> parse_error ( Err . opt_repeated g f ) end | [ ] -> match fv with None -> v | Some ( _ , v ) -> v in aux None l in let flag ( _ , a ) = if is_pos a then invalid_arg err_not_opt else a in List . rev_map flag l , convert let vflag_all v l = let convert _ cl = let rec aux acc = function | ( fv , a ) :: rest -> begin match Cmdline . opt_arg cl a with | [ ] -> aux acc rest | l -> let fval ( k , f , v ) = match v with | None -> ( k , fv ) | Some v -> parse_error ( Err . flag_value f v ) in aux ( List . rev_append ( List . rev_map fval l ) acc ) rest end | [ ] -> if acc = [ ] then v else List . rev_map snd ( List . sort rev_compare acc ) in aux [ ] l in let flag ( _ , a ) = if is_pos a then invalid_arg err_not_opt else { a with o_all = true } in List . rev_map flag l , convert let parse_opt_value parse f v = match parse v with | ` Ok v -> v | ` Error e -> parse_error ( Err . opt_parse_value f e ) let opt ? vopt ( parse , print ) v a = if is_pos a then invalid_arg err_not_opt else let a = { a with absent = Val ( lazy ( str_of_pp print v ) ) ; o_kind = match vopt with | None -> Opt | Some dv -> Opt_vopt ( str_of_pp print dv ) } in let convert ei cl = match Cmdline . opt_arg cl a with | [ ] -> try_env ei a parse ~ absent : v | [ _ , f , Some v ] -> parse_opt_value parse f v | [ _ , f , None ] -> begin match vopt with | None -> parse_error ( Err . opt_value_missing f ) | Some optv -> optv end | ( _ , f , _ ) :: ( _ , g , _ ) :: _ -> parse_error ( Err . opt_repeated g f ) in [ a ] , convert let opt_all ? vopt ( parse , print ) v a = if is_pos a then invalid_arg err_not_opt else let a = { a with absent = Val ( lazy " " ) ; o_all = true ; o_kind = match vopt with | None -> Opt | Some dv -> Opt_vopt ( str_of_pp print dv ) } in let convert ei cl = match Cmdline . opt_arg cl a with | [ ] -> try_env ei a ( parse_to_list parse ) ~ absent : v | l -> let parse ( k , f , v ) = match v with | Some v -> ( k , parse_opt_value parse f v ) | None -> match vopt with | None -> parse_error ( Err . opt_value_missing f ) | Some dv -> ( k , dv ) in List . rev_map snd ( List . sort rev_compare ( List . rev_map parse l ) ) in [ a ] , convert let parse_pos_value parse a v = match parse v with | ` Ok v -> v | ` Error e -> parse_error ( Err . pos_parse_value a e ) let pos ( ? rev = false ) k ( parse , print ) v a = if is_opt a then invalid_arg err_not_pos else let a = { a with p_kind = Nth ( rev , k ) ; absent = Val ( lazy ( str_of_pp print v ) ) } in let convert ei cl = match Cmdline . pos_arg cl a with | [ ] -> try_env ei a parse ~ absent : v | [ v ] -> parse_pos_value parse a v | _ -> assert false in [ a ] , convert let pos_list kind ( parse , _ ) v a = if is_opt a then invalid_arg err_not_pos else let a = { a with p_kind = kind } in let convert ei cl = match Cmdline . pos_arg cl a with | [ ] -> try_env ei a ( parse_to_list parse ) ~ absent : v | l -> List . rev ( List . rev_map ( parse_pos_value parse a ) l ) in [ a ] , convert let pos_all c v a = pos_list All c v a let pos_left ( ? rev = false ) k = pos_list ( Left ( rev , k ) ) let pos_right ( ? rev = false ) k = pos_list ( Right ( rev , k ) ) let absent_error al = List . rev_map ( fun a -> { a with absent = Error } ) al let value a = a let required ( al , convert ) = let al = absent_error al in let convert ei cl = match convert ei cl with | Some v -> v | None -> parse_error ( Err . arg_missing ( List . hd al ) ) in al , convert let non_empty ( al , convert ) = let al = absent_error al in let convert ei cl = match convert ei cl with | [ ] -> parse_error ( Err . arg_missing ( List . hd al ) ) | l -> l in al , convert let last ( al , convert ) = let convert ei cl = match convert ei cl with | [ ] -> parse_error ( Err . arg_missing ( List . hd al ) ) | l -> List . hd ( List . rev l ) in al , convert let bool = ( fun s -> try ` Ok ( bool_of_string s ) with Invalid_argument _ -> ` Error ( Err . invalid_val s ( alts_str [ " true " ; " false " ] ) ) ) , Format . pp_print_bool let char = ( fun s -> if String . length s = 1 then ` Ok s . [ 0 ] else ` Error ( Err . invalid_val s " expected a character " ) ) , pr_char let parse_with t_of_str exp s = try ` Ok ( t_of_str s ) with Failure _ -> ` Error ( Err . invalid_val s exp ) let int = parse_with int_of_string " expected an integer " , Format . pp_print_int let int32 = parse_with Int32 . of_string " expected a 32 - bit integer " , ( fun ppf -> pr ppf " % ld " ) let int64 = parse_with Int64 . of_string " expected a 64 - bit integer " , ( fun ppf -> pr ppf " % Ld " ) let nativeint = parse_with Nativeint . of_string " expected a processor - native integer " , ( fun ppf -> pr ppf " % nd " ) let float = parse_with float_of_string " expected a floating point number " , Format . pp_print_float let string = ( fun s -> ` Ok s ) , pr_str let enum sl = if sl = [ ] then invalid_arg err_empty_list else let t = Trie . of_list sl in let parse s = match Trie . find t s with | ` Ok _ as r -> r | ` Ambiguous -> let ambs = List . sort compare ( Trie . ambiguities t s ) in ` Error ( Err . ambiguous " enum value " s ambs ) | ` Not_found -> let alts = List . rev ( List . rev_map ( fun ( s , _ ) -> s ) sl ) in ` Error ( Err . invalid_val s ( " expected " ^ ( alts_str alts ) ) ) in let print ppf v = let sl_inv = List . rev_map ( fun ( s , v ) -> ( v , s ) ) sl in try pr_str ppf ( List . assoc v sl_inv ) with Not_found -> invalid_arg err_incomplete_enum in parse , print let file = ( fun s -> if Sys . file_exists s then ` Ok s else ` Error ( Err . no " file or directory " s ) ) , pr_str let dir = ( fun s -> if Sys . file_exists s then if Sys . is_directory s then ` Ok s else ` Error ( Err . not_dir s ) else ` Error ( Err . no " directory " s ) ) , pr_str let non_dir_file = ( fun s -> if Sys . file_exists s then if not ( Sys . is_directory s ) then ` Ok s else ` Error ( Err . is_dir s ) else ` Error ( Err . no " file " s ) ) , pr_str let split_and_parse sep parse s = let parse sub = match parse sub with | ` Error e -> failwith e | ` Ok v -> v in let rec split accum j = let i = try String . rindex_from s j sep with Not_found -> - 1 in if ( i = - 1 ) then let p = String . sub s 0 ( j + 1 ) in if p <> " " then parse p :: accum else accum else let p = String . sub s ( i + 1 ) ( j - i ) in let accum ' = if p <> " " then parse p :: accum else accum in split accum ' ( i - 1 ) in split [ ] ( String . length s - 1 ) let list ( ? sep = ' , ' ) ( parse , pr_e ) = let parse s = try ` Ok ( split_and_parse sep parse s ) with | Failure e -> ` Error ( Err . element " list " s e ) in let rec print ppf = function | v :: l -> pr_e ppf v ; if ( l <> [ ] ) then ( pr_char ppf sep ; print ppf l ) | [ ] -> ( ) in parse , print let array ( ? sep = ' , ' ) ( parse , pr_e ) = let parse s = try ` Ok ( Array . of_list ( split_and_parse sep parse s ) ) with | Failure e -> ` Error ( Err . element " array " s e ) in let print ppf v = let max = Array . length v - 1 in for i = 0 to max do pr_e ppf v . ( i ) ; if i <> max then pr_char ppf sep done in parse , print let split_left sep s = try let i = String . index s sep in let len = String . length s in Some ( ( String . sub s 0 i ) , ( String . sub s ( i + 1 ) ( len - i - 1 ) ) ) with Not_found -> None let pair ( ? sep = ' , ' ) ( pa0 , pr0 ) ( pa1 , pr1 ) = let parser s = match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v0 , v1 ) -> match pa0 v0 , pa1 v1 with | ` Ok v0 , ` Ok v1 -> ` Ok ( v0 , v1 ) | ` Error e , _ | _ , ` Error e -> ` Error ( Err . element " pair " s e ) in let printer ppf ( v0 , v1 ) = pr ppf " % a % c % a " pr0 v0 sep pr1 v1 in parser , printer let t2 = pair let t3 ( ? sep = ' , ' ) ( pa0 , pr0 ) ( pa1 , pr1 ) ( pa2 , pr2 ) = let parse s = match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v0 , s ) -> match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v1 , v2 ) -> match pa0 v0 , pa1 v1 , pa2 v2 with | ` Ok v0 , ` Ok v1 , ` Ok v2 -> ` Ok ( v0 , v1 , v2 ) | ` Error e , _ , _ | _ , ` Error e , _ | _ , _ , ` Error e -> ` Error ( Err . element " triple " s e ) in let print ppf ( v0 , v1 , v2 ) = pr ppf " % a % c % a % c % a " pr0 v0 sep pr1 v1 sep pr2 v2 in parse , print let t4 ( ? sep = ' , ' ) ( pa0 , pr0 ) ( pa1 , pr1 ) ( pa2 , pr2 ) ( pa3 , pr3 ) = let parse s = match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v0 , s ) -> match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v1 , s ) -> match split_left sep s with | None -> ` Error ( Err . sep_miss sep s ) | Some ( v2 , v3 ) -> match pa0 v0 , pa1 v1 , pa2 v2 , pa3 v3 with | ` Ok v1 , ` Ok v2 , ` Ok v3 , ` Ok v4 -> ` Ok ( v1 , v2 , v3 , v4 ) | ` Error e , _ , _ , _ | _ , ` Error e , _ , _ | _ , _ , ` Error e , _ | _ , _ , _ , ` Error e -> ` Error ( Err . element " quadruple " s e ) in let print ppf ( v0 , v1 , v2 , v3 ) = pr ppf " % a % c % a % c % a % c % a " pr0 v0 sep pr1 v1 sep pr2 v2 sep pr3 v3 in parse , print let doc_quote = quote let doc_alts = alts_str let doc_alts_enum ? quoted enum = alts_str ? quoted ( List . map fst enum ) end
module Term = struct type info = term_info type ' + a t = arg_info list * ( eval_info -> cmdline -> ' a ) type ' a result = [ | ` Ok of ' a | ` Error of [ ` Parse | ` Term | ` Exn ] | ` Version | ` Help ] exception Term of [ ` Help of [ ` Pager | ` Plain | ` Groff ] * string option | ` Error of bool * string ] let info ( ? sdocs = " OPTIONS " ) ( ? man = [ ] ) ( ? docs = " COMMANDS " ) ( ? doc = " " ) ? version name = { name = name ; version = version ; tdoc = doc ; tdocs = docs ; sdocs = sdocs ; man = man } let name ti = ti . name let const v = [ ] , ( fun _ _ -> v ) let pure = const let app ( al , f ) ( al ' , v ) = List . rev_append al al ' , fun ei cl -> ( f ei cl ) ( v ei cl ) let ( $ ) = app type ' a ret = [ ` Help of [ ` Pager | ` Plain | ` Groff ] * string option | ` Error of ( bool * string ) | ` Ok of ' a ] let ret ( al , v ) = al , fun ei cl -> match v ei cl with | ` Ok v -> v | ` Error ( u , e ) -> raise ( Term ( ` Error ( u , e ) ) ) | ` Help h -> raise ( Term ( ` Help h ) ) let main_name = [ ] , ( fun ei _ -> ( fst ei . main ) . name ) let choice_names = [ ] , fun ei _ -> List . rev_map ( fun e -> ( fst e ) . name ) ei . choices let man_format = let fmts = [ " pager " , ` Pager ; " groff " , ` Groff ; " plain " , ` Plain ] in let doc = " Show output in format ( $ docv ) ( pager , plain or groff ) . " in Arg . ( value & opt ( enum fmts ) ` Pager & info [ " man - format " ] ~ docv " : FMT " ~ doc ) let remove_exec argv = try List . tl ( Array . to_list argv ) with Failure _ -> invalid_arg err_argv let add_std_opts ei = let docs = ( fst ei . term ) . sdocs in let args , v_lookup = if ( fst ei . main ) . version = None then [ ] , None else let ( a , lookup ) = Arg . flag ( Arg . info [ " version " ] ~ docs ~ doc " : Show version information . " ) in a , Some lookup in let args , h_lookup = let ( a , lookup ) = let fmt = Arg . enum [ " pager " , ` Pager ; " groff " , ` Groff ; " plain " , ` Plain ] in let doc = " Show this help in format ( $ docv ) ( pager , plain or groff ) . " in let a = Arg . info [ " help " ] ~ docv " : FMT " ~ docs ~ doc in Arg . opt ~ vopt ( : Some ` Pager ) ( Arg . some fmt ) None a in List . rev_append a args , lookup in h_lookup , v_lookup , { ei with term = ( fst ei . term ) , List . rev_append args ( snd ei . term ) } let eval_term help err ei f args = let help_arg , vers_arg , ei = add_std_opts ei in try let cl = Cmdline . create ( snd ei . term ) args in match help_arg ei cl , vers_arg with | Some fmt , _ -> Help . print fmt help ei ; ` Help | None , Some v_arg when v_arg ei cl -> Help . pr_version help ei ; ` Version | _ -> ` Ok ( f ei cl ) with | Cmdline . Error e -> Err . pr_usage err ei e ; ` Error ` Parse | Term ( ` Error ( usage , e ) ) -> if usage then Err . pr_usage err ei e else Err . print err ei e ; ` Error ` Term | Term ( ` Help ( fmt , cmd ) ) -> let ei = match cmd with | Some cmd -> let cmd = try List . find ( fun ( i , _ ) -> i . name = cmd ) ei . choices with Not_found -> invalid_arg ( err_help cmd ) in { ei with term = cmd } | None -> { ei with term = ei . main } in let _ , _ , ei = add_std_opts ei in Help . print fmt help ei ; ` Help let env_default v = try Some ( Sys . getenv v ) with Not_found -> None let eval ( ? help = Format . std_formatter ) ( ? err = Format . err_formatter ) ( ? catch = true ) ( ? env = env_default ) ( ? argv = Sys . argv ) ( ( al , f ) , ti ) = let term = ti , al in let ei = { term = term ; main = term ; choices = [ ] ; env = env } in try eval_term help err ei f ( remove_exec argv ) with | e when catch -> Err . pr_backtrace err ei e ( Printexc . get_backtrace ( ) ) ; ` Error ` Exn let eval_choice ( ? help = Format . std_formatter ) ( ? err = Format . err_formatter ) ( ? catch = true ) ( ? env = env_default ) ( ? argv = Sys . argv ) ( ( ( al , f ) as t ) , ti ) choices = let ei_choices = List . rev_map ( fun ( ( al , _ ) , ti ) -> ti , al ) choices in let main = ( ti , al ) in let ei = { term = main ; main = main ; choices = ei_choices ; env = env } in try let chosen , args = Cmdline . choose_term ti ei_choices ( remove_exec argv ) in let find_chosen ( _ , ti ) = ti = chosen in let ( al , f ) , _ = List . find find_chosen ( ( t , ti ) :: choices ) in let ei = { ei with term = ( chosen , al ) } in eval_term help err ei f args with | Cmdline . Error e -> Err . pr_usage err ei e ; ` Error ` Parse | e when catch -> Err . pr_backtrace err ei e ( Printexc . get_backtrace ( ) ) ; ` Error ` Exn let eval_peek_opts ( ? version_opt = false ) ( ? env = env_default ) ( ? argv = Sys . argv ) ( al , f ) = let args = remove_exec argv in let version = if version_opt then Some " dummy " else None in let term = info ? version " dummy " , al in let ei = { term = term ; main = term ; choices = [ ] ; env = env } in let help_arg , vers_arg , ei = add_std_opts ei in try let cl = Cmdline . create ~ peek_opts : true ( snd ei . term ) args in match help_arg ei cl , vers_arg with | Some fmt , _ -> ( try ( Some ( f ei cl ) , ` Help ) with e -> None , ` Help ) | None , Some v_arg when v_arg ei cl -> ( try ( Some ( f ei cl ) , ` Version ) with e -> None , ` Version ) | _ -> let v = f ei cl in Some v , ` Ok v with | Cmdline . Error _ -> None , ( ` Error ` Parse ) | Term _ -> None , ( ` Error ` Term ) | e -> None , ( ` Error ` Exn ) end
module List = struct include List let map f l = List . rev_map f l |> List . rev let rev_split l = let rec inner xs ys = function | ( x , y ) :: xys -> inner ( x :: xs ) ( y :: ys ) xys | [ ] -> ( xs , ys ) in inner [ ] [ ] l let split l = rev_split ( List . rev l ) end
type wrap = [ | ` Wrap_atoms | ` Always_wrap | ` Never_wrap | ` Force_breaks | ` Force_breaks_rec | ` No_breaks ]
type label_break = [ | ` Auto | ` Always | ` Always_rec | ` Never ]
type style = { tag_open : string ; tag_close : string }
type atom_param = { atom_style : style_name option ; }
let atom = { atom_style = None }
type list_param = { space_after_opening : bool ; space_after_separator : bool ; space_before_separator : bool ; separators_stick_left : bool ; space_before_closing : bool ; stick_to_label : bool ; align_closing : bool ; wrap_body : wrap ; indent_body : int ; list_style : style_name option ; opening_style : style_name option ; body_style : style_name option ; separator_style : style_name option ; closing_style : style_name option ; }
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