text
stringlengths 0
601k
|
---|
let caml_bytes_equal = Primitive . simple ~ name " : caml_bytes_equal " ~ arity : 2 ~ alloc : false |
let caml_notequal = Primitive . simple ~ name " : caml_notequal " ~ arity : 2 ~ alloc : true |
let caml_string_notequal = Primitive . simple ~ name " : caml_string_notequal " ~ arity : 2 ~ alloc : false |
let caml_bytes_notequal = Primitive . simple ~ name " : caml_bytes_notequal " ~ arity : 2 ~ alloc : false |
let caml_lessequal = Primitive . simple ~ name " : caml_lessequal " ~ arity : 2 ~ alloc : true |
let caml_string_lessequal = Primitive . simple ~ name " : caml_string_lessequal " ~ arity : 2 ~ alloc : false |
let caml_bytes_lessequal = Primitive . simple ~ name " : caml_bytes_lessequal " ~ arity : 2 ~ alloc : false |
let caml_lessthan = Primitive . simple ~ name " : caml_lessthan " ~ arity : 2 ~ alloc : true |
let caml_string_lessthan = Primitive . simple ~ name " : caml_string_lessthan " ~ arity : 2 ~ alloc : false |
let caml_bytes_lessthan = Primitive . simple ~ name " : caml_bytes_lessthan " ~ arity : 2 ~ alloc : false |
let caml_greaterequal = Primitive . simple ~ name " : caml_greaterequal " ~ arity : 2 ~ alloc : true |
let caml_string_greaterequal = Primitive . simple ~ name " : caml_string_greaterequal " ~ arity : 2 ~ alloc : false |
let caml_bytes_greaterequal = Primitive . simple ~ name " : caml_bytes_greaterequal " ~ arity : 2 ~ alloc : false |
let caml_greaterthan = Primitive . simple ~ name " : caml_greaterthan " ~ arity : 2 ~ alloc : true |
let caml_string_greaterthan = Primitive . simple ~ name " : caml_string_greaterthan " ~ arity : 2 ~ alloc : false |
let caml_bytes_greaterthan = Primitive . simple ~ name " : caml_bytes_greaterthan " ~ arity : 2 ~ alloc : false |
let caml_compare = Primitive . simple ~ name " : caml_compare " ~ arity : 2 ~ alloc : true |
let caml_int_compare = Primitive . simple ~ name " : caml_int_compare " ~ arity : 2 ~ alloc : false |
let caml_float_compare = unboxed_compare " caml_float_compare " Unboxed_float |
let caml_string_compare = Primitive . simple ~ name " : caml_string_compare " ~ arity : 2 ~ alloc : false |
let caml_bytes_compare = Primitive . simple ~ name " : caml_bytes_compare " ~ arity : 2 ~ alloc : false |
let caml_nativeint_compare = unboxed_compare " caml_nativeint_compare " ( Unboxed_integer Pnativeint ) |
let caml_int32_compare = unboxed_compare " caml_int32_compare " ( Unboxed_integer Pint32 ) |
let caml_int64_compare = unboxed_compare " caml_int64_compare " ( Unboxed_integer Pint64 ) |
let comparison_primitive comparison comparison_kind = match comparison , comparison_kind with | Equal , Compare_generic -> Pccall caml_equal | Equal , Compare_ints -> Pintcomp Ceq | Equal , Compare_floats -> Pfloatcomp CFeq | Equal , Compare_strings -> Pccall caml_string_equal | Equal , Compare_bytes -> Pccall caml_bytes_equal | Equal , Compare_nativeints -> Pbintcomp ( Pnativeint , Ceq ) | Equal , Compare_int32s -> Pbintcomp ( Pint32 , Ceq ) | Equal , Compare_int64s -> Pbintcomp ( Pint64 , Ceq ) | Not_equal , Compare_generic -> Pccall caml_notequal | Not_equal , Compare_ints -> Pintcomp Cne | Not_equal , Compare_floats -> Pfloatcomp CFneq | Not_equal , Compare_strings -> Pccall caml_string_notequal | Not_equal , Compare_bytes -> Pccall caml_bytes_notequal | Not_equal , Compare_nativeints -> Pbintcomp ( Pnativeint , Cne ) | Not_equal , Compare_int32s -> Pbintcomp ( Pint32 , Cne ) | Not_equal , Compare_int64s -> Pbintcomp ( Pint64 , Cne ) | Less_equal , Compare_generic -> Pccall caml_lessequal | Less_equal , Compare_ints -> Pintcomp Cle | Less_equal , Compare_floats -> Pfloatcomp CFle | Less_equal , Compare_strings -> Pccall caml_string_lessequal | Less_equal , Compare_bytes -> Pccall caml_bytes_lessequal | Less_equal , Compare_nativeints -> Pbintcomp ( Pnativeint , Cle ) | Less_equal , Compare_int32s -> Pbintcomp ( Pint32 , Cle ) | Less_equal , Compare_int64s -> Pbintcomp ( Pint64 , Cle ) | Less_than , Compare_generic -> Pccall caml_lessthan | Less_than , Compare_ints -> Pintcomp Clt | Less_than , Compare_floats -> Pfloatcomp CFlt | Less_than , Compare_strings -> Pccall caml_string_lessthan | Less_than , Compare_bytes -> Pccall caml_bytes_lessthan | Less_than , Compare_nativeints -> Pbintcomp ( Pnativeint , Clt ) | Less_than , Compare_int32s -> Pbintcomp ( Pint32 , Clt ) | Less_than , Compare_int64s -> Pbintcomp ( Pint64 , Clt ) | Greater_equal , Compare_generic -> Pccall caml_greaterequal | Greater_equal , Compare_ints -> Pintcomp Cge | Greater_equal , Compare_floats -> Pfloatcomp CFge | Greater_equal , Compare_strings -> Pccall caml_string_greaterequal | Greater_equal , Compare_bytes -> Pccall caml_bytes_greaterequal | Greater_equal , Compare_nativeints -> Pbintcomp ( Pnativeint , Cge ) | Greater_equal , Compare_int32s -> Pbintcomp ( Pint32 , Cge ) | Greater_equal , Compare_int64s -> Pbintcomp ( Pint64 , Cge ) | Greater_than , Compare_generic -> Pccall caml_greaterthan | Greater_than , Compare_ints -> Pintcomp Cgt | Greater_than , Compare_floats -> Pfloatcomp CFgt | Greater_than , Compare_strings -> Pccall caml_string_greaterthan | Greater_than , Compare_bytes -> Pccall caml_bytes_greaterthan | Greater_than , Compare_nativeints -> Pbintcomp ( Pnativeint , Cgt ) | Greater_than , Compare_int32s -> Pbintcomp ( Pint32 , Cgt ) | Greater_than , Compare_int64s -> Pbintcomp ( Pint64 , Cgt ) | Compare , Compare_generic -> Pccall caml_compare | Compare , Compare_ints -> Pccall caml_int_compare | Compare , Compare_floats -> Pccall caml_float_compare | Compare , Compare_strings -> Pccall caml_string_compare | Compare , Compare_bytes -> Pccall caml_bytes_compare | Compare , Compare_nativeints -> Pccall caml_nativeint_compare | Compare , Compare_int32s -> Pccall caml_int32_compare | Compare , Compare_int64s -> Pccall caml_int64_compare |
let lambda_of_loc kind loc = let loc_start = loc . Location . loc_start in let ( file , lnum , cnum ) = Location . get_pos_info loc_start in let file = if Filename . is_relative file then file else Location . rewrite_absolute_path file in let enum = loc . Location . loc_end . Lexing . pos_cnum - loc_start . Lexing . pos_cnum + cnum in match kind with | Loc_POS -> Lconst ( Const_block ( 0 , [ Const_immstring file ; Const_base ( Const_int lnum ) ; Const_base ( Const_int cnum ) ; Const_base ( Const_int enum ) ; ] ) ) | Loc_FILE -> Lconst ( Const_immstring file ) | Loc_MODULE -> let filename = Filename . basename file in let name = Env . get_unit_name ( ) in let module_name = if name = " " then " " //^ filename " " ^// else name in Lconst ( Const_immstring module_name ) | Loc_LOC -> let loc = Printf . sprintf " File % S , line % d , characters % d -% d " file lnum cnum enum in Lconst ( Const_immstring loc ) | Loc_LINE -> Lconst ( Const_base ( Const_int lnum ) ) |
let caml_restore_raw_backtrace = Primitive . simple ~ name " : caml_restore_raw_backtrace " ~ arity : 2 ~ alloc : false |
let try_ids = Hashtbl . create 8 |
let add_exception_ident id = Hashtbl . replace try_ids id ( ) |
let remove_exception_ident id = Hashtbl . remove try_ids id |
let lambda_of_prim prim_name prim loc args arg_exps = match prim , args with | Primitive ( prim , arity ) , args when arity = List . length args -> Lprim ( prim , args , loc ) | External prim , args when prim = prim_sys_argv -> Lprim ( Pccall prim , Lconst ( Const_pointer 0 ) :: args , loc ) | External prim , args -> Lprim ( Pccall prim , args , loc ) | Comparison ( comp , knd ) , ( [ _ ; _ ] as args ) -> let prim = comparison_primitive comp knd in Lprim ( prim , args , loc ) | Raise kind , [ arg ] -> let kind = match kind , arg with | Raise_regular , Lvar argv when Hashtbl . mem try_ids argv -> Raise_reraise | _ , _ -> kind in let arg = match arg_exps with | None -> arg | Some [ arg_exp ] -> event_after arg_exp arg | Some _ -> assert false in Lprim ( Praise kind , [ arg ] , loc ) | Raise_with_backtrace , [ exn ; bt ] -> let vexn = Ident . create_local " exn " in let raise_arg = match arg_exps with | None -> Lvar vexn | Some [ exn_exp ; _ ] -> event_after exn_exp ( Lvar vexn ) | Some _ -> assert false in Llet ( Strict , Pgenval , vexn , exn , Lsequence ( Lprim ( Pccall caml_restore_raw_backtrace , [ Lvar vexn ; bt ] , loc ) , Lprim ( Praise Raise_reraise , [ raise_arg ] , loc ) ) ) | Lazy_force , [ arg ] -> Matching . inline_lazy_force arg Location . none | Loc kind , [ ] -> lambda_of_loc kind loc | Loc kind , [ arg ] -> let lam = lambda_of_loc kind loc in Lprim ( Pmakeblock ( 0 , Immutable , None ) , [ lam ; arg ] , loc ) | Send , [ obj ; meth ] -> Lsend ( Public , meth , obj , [ ] , loc ) | Send_self , [ obj ; meth ] -> Lsend ( Self , meth , obj , [ ] , loc ) | Send_cache , [ obj ; meth ; cache ; pos ] -> Lsend ( Cached , meth , obj , [ cache ; pos ] , loc ) | ( Raise _ | Raise_with_backtrace | Lazy_force | Loc _ | Primitive _ | Comparison _ | Send | Send_self | Send_cache ) , _ -> raise ( Error ( loc , Wrong_arity_builtin_primitive prim_name ) ) |
let check_primitive_arity loc p = let prim = lookup_primitive loc p in let ok = match prim with | Primitive ( _ , arity ) -> arity = p . prim_arity | External _ -> true | Comparison _ -> p . prim_arity = 2 | Raise _ -> p . prim_arity = 1 | Raise_with_backtrace -> p . prim_arity = 2 | Lazy_force -> p . prim_arity = 1 | Loc _ -> p . prim_arity = 1 || p . prim_arity = 0 | Send | Send_self -> p . prim_arity = 2 | Send_cache -> p . prim_arity = 4 in if not ok then raise ( Error ( loc , Wrong_arity_builtin_primitive p . prim_name ) ) |
let transl_primitive loc p env ty path = let prim = lookup_primitive_and_mark_used loc p env path in let has_constant_constructor = false in let prim = match specialize_primitive env ty ~ has_constant_constructor prim with | None -> prim | Some prim -> prim in let rec make_params n = if n <= 0 then [ ] else ( Ident . create_local " prim " , Pgenval ) :: make_params ( n - 1 ) in let params = make_params p . prim_arity in let args = List . map ( fun ( id , _ ) -> Lvar id ) params in let body = lambda_of_prim p . prim_name prim loc args None in match params with | [ ] -> body | _ -> Lfunction { kind = Curried ; params ; return = Pgenval ; attr = default_stub_attribute ; loc = loc ; body = body ; } |
let primitive_is_ccall = function | Pccall _ | Pstringrefs | Pbytesrefs | Pbytessets | Parrayrefs _ | Parraysets _ | Pbigarrayref _ | Pbigarrayset _ | Pduprecord _ | Pdirapply | Prevapply -> true | _ -> false |
let primitive_needs_event_after = function | Primitive ( prim , _ ) -> primitive_is_ccall prim | External _ -> true | Comparison ( comp , knd ) -> primitive_is_ccall ( comparison_primitive comp knd ) | Lazy_force | Send | Send_self | Send_cache -> true | Raise _ | Raise_with_backtrace | Loc _ -> false |
let transl_primitive_application loc p env ty path exp args arg_exps = let prim = lookup_primitive_and_mark_used loc p env ( Some path ) in let has_constant_constructor = match arg_exps with | [ _ ; { exp_desc = Texp_construct ( _ , { cstr_tag = Cstr_constant _ } , _ ) } ] | [ { exp_desc = Texp_construct ( _ , { cstr_tag = Cstr_constant _ } , _ ) } ; _ ] | [ _ ; { exp_desc = Texp_variant ( _ , None ) } ] | [ { exp_desc = Texp_variant ( _ , None ) } ; _ ] -> true | _ -> false in let prim = match specialize_primitive env ty ~ has_constant_constructor prim with | None -> prim | Some prim -> prim in let lam = lambda_of_prim p . prim_name prim loc args ( Some arg_exps ) in let lam = if primitive_needs_event_after prim then begin match exp with | None -> lam | Some exp -> event_after exp lam end else begin lam end in lam |
let report_error ppf = function | Unknown_builtin_primitive prim_name -> fprintf ppf " Unknown builtin primitive " \% s " " \ prim_name | Wrong_arity_builtin_primitive prim_name -> fprintf ppf " Wrong arity for builtin primitive " \% s " " \ prim_name |
let ( ) = Location . register_error_of_exn ( function | Error ( loc , err ) -> Some ( Location . error_of_printer ~ loc report_error err ) | _ -> None ) |
let string s = Lconst ( Const_base ( Const_string ( s , None ) ) ) |
let int i = Lconst ( Const_base ( Const_int i ) ) |
let marshal_loc ( x : Location . t ) = let s = Marshal . to_string x [ ] in string s |
let true_ = Lconst ( Const_pointer 1 ) |
let false_ = Lconst ( Const_pointer 0 ) |
let quote_bool b = if b then true_ else false_ |
let none = Lconst ( Const_pointer 0 ) |
let some x = Lprim ( Pmakeblock ( 0 , Immutable , None ) , [ x ] , Location . none ) |
let option opt = match opt with | None -> none | Some x -> some x |
let nil = Lconst ( Const_pointer 0 ) |
let cons hd tl = Lprim ( Pmakeblock ( 0 , Immutable , None ) , [ hd ; tl ] , Location . none ) |
let rec list l = match l with | [ ] -> nil | hd :: tl -> cons hd ( list tl ) |
let pair ( x , y ) = Lprim ( Pmakeblock ( 0 , Immutable , None ) , [ x ; y ] , Location . none ) |
module Lam = struct let stdmod_path = Ident . lift_string " CamlinternalQuote " let lambda_mod = " Lambda " let camlinternalQuote = lazy ( match Env . open_pers_signature stdmod_path Env . initial_safe_string with | exception Not_found -> fatal_error @@ " Module " ^ stdmod_path ^ " unavailable . " | env -> env ) let static_pos = function | Path . Uniphase ( Static , i ) -> i | Path . Biphase ( i , _ ) -> i | _ -> fatal_error ( stdmod_path ^ " primitive at unexpected position . " ) let combinator modname field = lazy ( let env = Lazy . force camlinternalQuote in let lid = Longident . Ldot ( Longident . Ldot ( Longident . Lident lambda_mod , modname ) , field ) in match Env . lookup_value lid env with | ( Path . Pdot ( Path . Pdot ( Path . Pdot ( Path . Pident ident , _ , pos1 ) , _ , pos2 ) , _ , pos3 ) , _ ) -> Lprim ( Pfield ( static_pos pos3 ) , [ Lprim ( Pfield ( static_pos pos2 ) , [ Lprim ( Pfield ( static_pos pos1 ) , [ Lprim ( Pgetglobal ident , [ ] , Location . none ) ] , Location . none ) ] , Location . none ) ] , Location . none ) | _ -> fatal_error @@ " Primitive " ^ stdmod_path ^ " . " ^ lambda_mod ^ " . " ^ modname ^ " . " ^ field ^ " not found . " | exception Not_found -> fatal_error @@ " Primitive " ^ stdmod_path ^ " . " ^ lambda_mod ^ " . " ^ modname ^ " . " ^ field " ^ not found . " ) let apply comb args = let comb = Lazy . force comb in Lapply { ap_func = comb ; ap_args = args ; ap_loc = Location . none ; ap_should_be_tailcall = false ; ap_inlined = Default_inline ; ap_specialised = Default_specialise ; } module Loc = struct let unmarshal = combinator " Loc " " unmarshal " end module Constant = struct let unmarshal = combinator " Constant " " unmarshal " end module Identifier = struct let unmarshal = combinator " Identifier " " unmarshal " end module Attribute = struct let unmarshal_inline_attr = combinator " Attribute " " unmarshal_inline_attr " let unmarshal_specialise_attr = combinator " Attribute " " unmarshal_specialise_attr " let unmarshal_function_kind = combinator " Attribute " " unmarshal_function_kind " let unmarshal_function_attr = combinator " Attribute " " unmarshal_function_attr " let unmarshal_let_kind = combinator " Attribute " " unmarshal_let_kind " let unmarshal_value_kind = combinator " Attribute " " unmarshal_value_kind " let unmarshal_direction_flag = combinator " Attribute " " unmarshal_direction_flag " let unmarshal_method_kind = combinator " Attribute " " unmarshal_method_kind " end module Exp = struct let var = combinator " Exp " " var " let constant = combinator " Exp " " constant " let application = combinator " Exp " " application " let function_ = combinator " Exp " " function_ " let let_ = combinator " Exp " " let_ " let letrec = combinator " Exp " " letrec " let primitive = combinator " Exp " " primitive " let switch = combinator " Exp " " switch " let stringswitch = combinator " Exp " " stringswitch " let staticraise = combinator " Exp " " staticraise " let staticcatch = combinator " Exp " " staticcatch " let trywith = combinator " Exp " " trywith " let ifthenelse = combinator " Exp " " ifthenelse " let sequence = combinator " Exp " " sequence " let while_ = combinator " Exp " " while_ " let for_ = combinator " Exp " " for_ " let assign = combinator " Exp " " assign " let send = combinator " Exp " " send " end module Primitive = struct let unmarshal = combinator " Primitive " " unmarshal " end let marshal_constant ( x : Lambda . structured_constant ) = let s = Marshal . to_string x [ ] in string s let quote_loc ( x : Location . t ) = let s = marshal_loc x in apply Loc . unmarshal [ s ] let quote_constant ( x : Lambda . structured_constant ) = let s = marshal_constant x in apply Constant . unmarshal [ s ] let quote_ident ( id : Ident . t ) = let s = string ( Marshal . to_string id [ ] ) in apply Identifier . unmarshal [ s ] let quote_inline_attr ( attr : inline_attribute ) = let s = Marshal . to_string attr [ ] in apply Attribute . unmarshal_inline_attr [ string s ] let quote_specialise_attr ( attr : specialise_attribute ) = let s = Marshal . to_string attr [ ] in apply Attribute . unmarshal_specialise_attr [ string s ] let quote_fn_kind ( k : function_kind ) = let s = Marshal . to_string k [ ] in apply Attribute . unmarshal_function_kind [ string s ] let quote_fn_attr ( attr : function_attribute ) = let s = Marshal . to_string attr [ ] in apply Attribute . unmarshal_function_attr [ string s ] let quote_let_kind ( k : let_kind ) = let s = Marshal . to_string k [ ] in apply Attribute . unmarshal_let_kind [ string s ] let quote_value_kind ( k : value_kind ) = let s = Marshal . to_string k [ ] in apply Attribute . unmarshal_value_kind [ string s ] let quote_prim ( p : primitive ) = let s = Marshal . to_string p [ ] in apply Primitive . unmarshal [ string s ] let quote_direction_flag ( f : direction_flag ) = let s = Marshal . to_string f [ ] in apply Attribute . unmarshal_direction_flag [ string s ] let quote_method_kind ( k : meth_kind ) = let s = Marshal . to_string k [ ] in apply Attribute . unmarshal_method_kind [ string s ] let rec lift_lambda = function | Lvar id -> apply Exp . var [ quote_ident id ] | Lconst cst -> apply Exp . constant [ quote_constant cst ] | Lapply { ap_func ; ap_args ; ap_loc ; ap_should_be_tailcall ; ap_inlined ; ap_specialised ; } -> apply Exp . application [ quote_loc ap_loc ; lift_lambda ap_func ; list ( List . map lift_lambda ap_args ) ; quote_bool ap_should_be_tailcall ; quote_inline_attr ap_inlined ; quote_specialise_attr ap_specialised ; ] | Lfunction { kind ; params ; body ; attr ; loc ; } -> apply Exp . function_ [ quote_loc loc ; quote_fn_kind kind ; list ( List . map quote_ident params ) ; lift_lambda body ; quote_fn_attr attr ; ] | Llet ( lkind , vkind , id , v , body ) -> apply Exp . let_ [ quote_let_kind lkind ; quote_value_kind vkind ; quote_ident id ; lift_lambda v ; lift_lambda body ; ] | Lletrec ( vbs , body ) -> apply Exp . letrec [ list ( List . map quote_vb vbs ) ; lift_lambda body ; ] | Lprim ( prim , args , loc ) -> apply Exp . primitive [ quote_loc loc ; quote_prim prim ; list ( List . map lift_lambda args ) ; ] | Lswitch ( lam , { sw_numconsts ; sw_consts ; sw_numblocks ; sw_blocks ; sw_failaction ; } ) -> apply Exp . switch [ lift_lambda lam ; int sw_numconsts ; list ( List . map ( fun ( i , l ) -> pair ( int i , lift_lambda l ) ) sw_consts ) ; int sw_numblocks ; list ( List . map ( fun ( i , l ) -> pair ( int i , lift_lambda l ) ) sw_blocks ) ; option ( Misc . may_map lift_lambda sw_failaction ) ; ] | Lstringswitch ( lam , cases , lam_opt , loc ) -> apply Exp . stringswitch [ quote_loc loc ; lift_lambda lam ; list ( List . map ( fun ( str , lam ) -> pair ( string str , lift_lambda lam ) ) cases ) ; option ( Misc . may_map lift_lambda lam_opt ) ; ] | Lstaticraise ( i , lams ) -> apply Exp . staticraise [ int i ; list ( List . map lift_lambda lams ) ; ] | Lstaticcatch ( lam , ( i , ids ) , body ) -> apply Exp . staticcatch [ lift_lambda lam ; pair ( int i , list ( List . map quote_ident ids ) ) ; lift_lambda body ; ] | Ltrywith ( lam , id , body ) -> apply Exp . trywith [ lift_lambda lam ; quote_ident id ; lift_lambda body ; ] | Lifthenelse ( cond , ift , iff ) -> apply Exp . ifthenelse [ lift_lambda cond ; lift_lambda ift ; lift_lambda iff ; ] | Lsequence ( l , l ' ) -> apply Exp . sequence [ lift_lambda l ; lift_lambda l ' ; ] | Lwhile ( cond , body ) -> apply Exp . while_ [ lift_lambda cond ; lift_lambda body ; ] | Lfor ( id , init , final , direction , body ) -> apply Exp . for_ [ quote_ident id ; lift_lambda init ; lift_lambda final ; quote_direction_flag direction ; lift_lambda body ; ] | Lassign ( id , lam ) -> apply Exp . assign [ quote_ident id ; lift_lambda lam ; ] | Lsend ( meth_kind , obj , meth , args , loc ) -> apply Exp . send [ quote_method_kind meth_kind ; lift_lambda obj ; lift_lambda meth ; list ( List . map lift_lambda args ) ; quote_loc loc ] | Levent ( e , _ ) -> lift_lambda e | Lifused ( _ , e ) -> lift_lambda e | Lescape lam -> lam and quote_vb ( id , lam ) = let id = quote_ident id in let lam = lift_lambda lam in pair ( id , lam ) let transl_clos_field loc path_id _name idx = apply Exp . primitive [ quote_loc loc ; quote_prim ( Pfield idx ) ; list [ Lvar path_id ] ; ] let quote_expression transl _pclos e = let lam = transl e in lift_lambda lam let path_arg _loc path = lift_lambda path end _ , pos1 ) , _ , pos2 ) , _ , pos3 ) , _ ) -> Lprim ( Pfield ( static_pos pos3 ) , [ Lprim ( Pfield ( static_pos pos2 ) , [ Lprim ( Pfield ( static_pos pos1 ) , [ Lprim ( Pgetglobal ident , [ ] , Location . none ) ] , Location . none ) ] , Location . none ) ] , Location . none ) | _ -> fatal_error @@ " Primitive " ^ stdmod_path ^ " . " ^ parsetree_mod ^ " . " ^ modname ^ " . " ^ field ^ " not found . " | exception Not_found -> fatal_error @@ " Primitive " ^ stdmod_path ^ " . " ^ parsetree_mod ^ " . " ^ modname ^ " . " ^ field " ^ not found . " ) let apply loc comb args = let comb = Lazy . force comb in Lapply { ap_func = comb ; ap_args = args ; ap_loc = loc ; ap_should_be_tailcall = false ; ap_inlined = Default_inline ; ap_specialised = Default_specialise ; } module Loc = struct let none = combinator " Loc " " none " let unmarshal = combinator " Loc " " unmarshal " end module Name = struct let unmarshal = combinator " Name " " unmarshal " end end ) * module Constant = struct let unmarshal = combinator " Constant " " unmarshal " end module Identifier = struct let unmarshal = combinator " Ident " " unmarshal " let lfrommacro = combinator " Ident " " lfrommacro " end module ArgLabel = struct let unmarshal = combinator " ArgLabel " " unmarshal " end module Variant = struct let of_string = combinator " Variant " " of_string " end module Method = struct let of_string = combinator " Method " " of_string " end module Pat = struct let any = combinator " Pat " " any " let var = combinator " Pat " " var " let alias = combinator " Pat " " alias " let constant = combinator " Pat " " constant " let tuple = combinator " Pat " " tuple " let construct = combinator " Pat " " construct " let variant = combinator " Pat " " variant " let record = combinator " Pat " " record " let array = combinator " Pat " " array " let or_ = combinator " Pat " " or_ " let lazy_ = combinator " Pat " " lazy_ " let exception_ = combinator " Pat " " exception_ " end module Case = struct let nonbinding = combinator " Case " " nonbinding " let simple = combinator " Case " " simple " let pattern = combinator " Case " " pattern " let guarded = combinator " Case " " guarded " end module Exp = struct let var = combinator " Exp " " var " let ident = combinator " Exp " " ident " let constant = combinator " Exp " " constant " let local = combinator " Exp " " local " let let_nonbinding = combinator " Exp " " let_nonbinding " let let_simple = combinator " Exp " " let_simple " let let_rec_simple = combinator " Exp " " let_rec_simple " let let_pattern = combinator " Exp " " let_pattern " let fun_nonbinding = combinator " Exp " " fun_nonbinding " let fun_simple = combinator " Exp " " fun_simple " let fun_pattern = combinator " Exp " " fun_pattern " let function_ = combinator " Exp " " function_ " let apply = combinator " Exp " " apply " let match_ = combinator " Exp " " match_ " let try_ = combinator " Exp " " try_ " let tuple = combinator " Exp " " tuple " let construct = combinator " Exp " " construct " let variant = combinator " Exp " " variant " let record = combinator " Exp " " record " let field = combinator " Exp " " field " let setfield = combinator " Exp " " setfield " let array = combinator " Exp " " array " let ifthenelse = combinator " Exp " " ifthenelse " let sequence = combinator " Exp " " sequence " let while_ = combinator " Exp " " while_ " let for_ = combinator " Exp " " for_ " let send = combinator " Exp " " send " let assert_ = combinator " Exp " " assert_ " let lazy_ = combinator " Exp " " lazy_ " let quote = combinator " Exp " " quote " let escape = combinator " Exp " " escape " let to_closed = combinator " Exp " " to_closed " end let marshal_name ( x : string loc ) = let s = Marshal . to_string x [ ] in string s let marshal_constant ( x : CamlinternalAST . constant ) = let s = Marshal . to_string x [ ] in string s let marshal_ident ( x : Longident . t loc ) = let s = Marshal . to_string x [ ] in string s let marshal_arg_label ( x : Asttypes . arg_label ) = let s = Marshal . to_string x [ ] in string s let func id body = Lfunction { kind = Curried ; params = [ id ] ; body = body ; attr = default_function_attribute ; loc = Location . none ; } let list_func ids body = let rec loop list_id = function | [ ] -> body | [ id ] -> Llet ( Alias , Pgenval , id , Lprim ( Pfield 0 , [ Lvar list_id ] , Location . none ) , body ) | id :: ids -> let tail_id = Ident . create " tl " in Llet ( Alias , Pgenval , id , Lprim ( Pfield 0 , [ Lvar list_id ] , Location . none ) , Llet ( Alias , Pgenval , tail_id , Lprim ( Pfield 1 , [ Lvar list_id ] , Location . none ) , loop tail_id ids ) ) in let list_id = Ident . create " list " in let body = loop list_id ids in Lfunction { kind = Curried ; params = [ list_id ] ; body = body ; attr = default_function_attribute ; loc = Location . none ; } let bind id def body = Llet ( Strict , Pgenval , id , def , body ) let quote_loc ( loc : Location . t ) = if loc = Location . none then use Loc . none else apply Location . none Loc . unmarshal [ marshal_loc loc ] let quote_constant loc ( const : Asttypes . constant ) = let const : CamlinternalAST . constant = let open CamlinternalAST in match const with | Const_int x -> Pconst_integer ( string_of_int x , None ) | Const_char x -> Pconst_char x | Const_string ( x , y ) -> Pconst_string ( x , y ) | Const_float x -> Pconst_float ( x , None ) | Const_int32 x -> Pconst_integer ( Int32 . to_string x , Some ' l ' ) | Const_int64 x -> Pconst_integer ( Int64 . to_string x , Some ' L ' ) | Const_nativeint x -> Pconst_integer ( Nativeint . to_string x , Some ' n ' ) in apply loc Constant . unmarshal [ marshal_constant const ] let quote_name loc ( str : string loc ) = apply loc Ident . unmarshal [ marshal_name str ] let quote_variant loc ( variant : label ) = apply loc Variant . of_string [ string variant ] let wrap_local loc id ( name : string loc ) body = let name = quote_name name . loc name in apply loc Exp . local [ quote_loc loc ; name ; func id body ] let quote_method loc ( meth : Typedtree . meth ) = let name = match meth with | Tmeth_name name -> name | Tmeth_val id -> Ident . name id in apply loc Method . of_string [ string name ] let quote_arg_label loc ( lbl : Asttypes . arg_label ) = apply loc ArgLabel . unmarshal [ marshal_arg_label lbl ] let lid_of_path p = let rec loop = function | Path . Pident id -> if Ident . global id then Longident . Lglobal ( Ident . name id ) else Longident . Lident ( Ident . name id ) | Path . Pdot ( p , s , _ ) -> Longident . Ldot ( loop p , s ) | Path . Papply ( p , p ' ) -> Longident . Lapply ( loop p , loop p ' ) in loop p let lid_of_type_path env ty = let desc = ( Ctype . repr ( Ctype . expand_head_opt env ( Ctype . correct_levels ty ) ) ) . desc in match desc with | Tconstr ( p , _ , _ ) -> lid_of_path p | _ -> fatal_error " No path for type " let quote_variant_constructor env loc constr = let lid = match lid_of_type_path env constr . cstr_res with | Longident . Lident _ -> Longident . Lident constr . cstr_name | Longident . Lglobal _ -> Longident . Lglobal constr . cstr_name | Longident . Ldot ( lid , _ ) -> Longident . Ldot ( lid , constr . cstr_name ) | Longident . Lfrommacro _ -> assert false | Longident . Lapply _ -> assert false in let lid = mkloc lid loc in apply loc Identifier . unmarshal [ marshal_ident lid ] let quote_record_label env loc lbl = let lid = match lid_of_type_path env lbl . lbl_res with | Longident . Lident _ -> Longident . Lident lbl . lbl_name | Longident . Lglobal _ -> Longident . Lglobal lbl . lbl_name | Longident . Ldot ( lid , _ ) -> Longident . Ldot ( lid , lbl . lbl_name ) | Longident . Lfrommacro _ -> assert false | Longident . Lapply _ -> assert false in let lid = mkloc lid loc in apply loc Identifier . unmarshal [ marshal_ident lid ] let transl_clos_field loc path_id str index = apply loc Identifier . lfrommacro [ Lvar path_id ; string str ; Lconst ( Const_base ( Const_int index ) ) ] let path_arg loc p = let lid = mkloc ( lid_of_path p ) loc in let lid = marshal_ident lid in apply loc Identifier . unmarshal [ lid ] let rec quote_pattern p = let env = p . pat_env in let loc = p . pat_loc in match p . pat_desc with | Tpat_any -> apply loc Pat . any [ quote_loc loc ] | Tpat_var ( id , _ ) -> apply loc Pat . var [ quote_loc loc ; Lvar id ] | Tpat_alias ( pat , id , _ ) -> let pat = quote_pattern pat in apply loc Pat . alias [ quote_loc loc ; pat ; Lvar id ] | Tpat_constant const -> let const = quote_constant loc const in apply loc Pat . constant [ quote_loc loc ; const ] | Tpat_tuple pats -> let pats = List . map quote_pattern pats in apply loc Pat . tuple [ quote_loc loc ; list pats ] | Tpat_construct ( lid , constr , args ) -> let constr = quote_variant_constructor env lid . loc constr in let args = match args with | [ ] -> None | [ arg ] -> let arg = quote_pattern arg in Some arg | _ :: _ -> let args = List . map quote_pattern args in Some ( apply loc Pat . tuple [ quote_loc loc ; list args ] ) in apply loc Pat . construct [ quote_loc loc ; constr ; option args ] | Tpat_variant ( variant , argo , _ ) -> let variant = quote_variant loc variant in let argo = Misc . may_map quote_pattern argo in apply loc Pat . variant [ quote_loc loc ; variant ; option argo ] | Tpat_record ( lbl_pats , closed ) -> let lbl_pats = List . map ( fun ( lid , lbl , pat ) -> let lbl = quote_record_label env ( lid : Longident . t loc ) . loc lbl in let pat = quote_pattern pat in pair ( lbl , pat ) ) lbl_pats in let closed = match closed with | Asttypes . Closed -> true_ | Asttypes . Open -> false_ in apply loc Pat . record [ quote_loc loc ; list lbl_pats ; closed ] | Tpat_array pats -> let pats = List . map quote_pattern pats in apply loc Pat . array [ quote_loc loc ; list pats ] | Tpat_or ( pat1 , pat2 , _ ) -> let pat1 = quote_pattern pat1 in let pat2 = quote_pattern pat2 in apply loc Pat . or_ [ quote_loc loc ; pat1 ; pat2 ] | Tpat_lazy pat -> let pat = quote_pattern pat in apply loc Pat . lazy_ [ quote_loc loc ; pat ] type case_binding = | Non_binding of lambda * lambda | Simple of lambda * lambda | Pattern of lambda * lambda | Guarded of lambda * lambda let rec case_binding exn transl pclos stage case : case_binding = let pat = case . c_lhs in let pat_loc = pat . pat_loc in match case . c_guard with | None -> begin match pat . pat_desc , exn with | Tpat_var ( id , name ) , false -> let name = quote_name name . loc name in let body = quote_expression transl pclos stage case . c_rhs in Simple ( name , func id body ) | _ -> match pat_bound_idents pat with | [ ] -> let pat = quote_pattern pat in let pat = if exn then apply pat_loc Pat . exception_ [ quote_loc pat_loc ; pat ] else pat in let exp = quote_expression transl pclos stage case . c_rhs in Non_binding ( pat , exp ) | id_names -> let ids = List . map fst id_names in let names = List . map ( fun ( _ , name ) -> quote_name ( name : string loc ) . loc name ) id_names in let pat = quote_pattern pat in let pat = if exn then apply pat_loc Pat . exception_ [ quote_loc pat_loc ; pat ] else pat in let exp = quote_expression transl pclos stage case . c_rhs in let pat_id = Ident . create " pattern " in let exp_id = Ident . create " expression " in let body = bind pat_id pat ( bind exp_id exp ( pair ( Lvar pat_id , Lvar exp_id ) ) ) in Pattern ( list names , list_func ids body ) end | Some guard -> let id_names = pat_bound_idents case . c_lhs in let ids = List . map fst id_names in let names = List . map ( fun ( _ , name ) -> quote_name ( name : string loc ) . loc name ) id_names in let pat = quote_pattern case . c_lhs in let pat = if exn then apply pat_loc Pat . exception_ [ quote_loc pat_loc ; pat ] else pat in let guard = quote_expression transl pclos stage guard in let exp = quote_expression transl pclos stage case . c_rhs in let pat_id = Ident . create " pattern " in let guard_id = Ident . create " guard " in let exp_id = Ident . create " expression " in let body = bind pat_id pat ( bind guard_id guard ( bind exp_id exp ( triple ( Lvar pat_id , Lvar guard_id , Lvar exp_id ) ) ) ) in Guarded ( list names , list_func ids body ) and quote_case_binding loc cb = match cb with | Non_binding ( pat , exp ) -> apply loc Case . nonbinding [ quote_loc loc ; pat ; exp ] | Simple ( name , body ) -> apply loc Case . simple [ quote_loc loc ; name ; body ] | Pattern ( names , body ) -> apply loc Case . pattern [ quote_loc loc ; names ; body ] | Guarded ( names , body ) -> apply loc Case . guarded [ quote_loc loc ; names ; body ] and quote_case exn transl pclos stage loc case = quote_case_binding loc ( case_binding exn transl pclos stage case ) and quote_nonrecursive_let transl pclos stage vbs body = List . fold_right ( fun vb body -> let loc = vb . vb_loc in let pat = vb . vb_pat in let exp = vb . vb_expr in match pat . pat_desc with | Tpat_var ( id , name ) -> let name = quote_name name . loc name in let exp = quote_expression transl pclos stage exp in apply loc Exp . let_simple [ quote_loc loc ; name ; exp ; func id body ] | _ -> match pat_bound_idents pat with | [ ] -> let pat = quote_pattern pat in let exp = quote_expression transl pclos stage exp in apply loc Exp . let_nonbinding [ quote_loc loc ; pat ; exp ; body ] | id_names -> let ids = List . map fst id_names in let names = List . map ( fun ( _ , name ) -> quote_name ( name : string loc ) . loc name ) id_names in let pat = quote_pattern pat in let exp = quote_expression transl pclos stage exp in let pat_id = Ident . create " pattern " in let body_id = Ident . create " body " in let body = bind pat_id pat ( bind body_id body ( pair ( Lvar pat_id , Lvar body_id ) ) ) in apply loc Exp . let_pattern [ quote_loc loc ; list names ; exp ; list_func ids body ] ) vbs ( quote_expression transl pclos stage body ) and quote_recursive_let transl pclos stage loc vbs body = let id_names , exps = List . fold_right ( fun vb ( id_names , exps ) -> let pat = vb . vb_pat in let exp = vb . vb_expr in match pat . pat_desc with | Tpat_var ( id , name ) | Tpat_alias ( { pat_desc = Tpat_any } , id , name ) -> let name = quote_name name . loc name in let exp = quote_expression transl pclos stage exp in ( ( id , name ) :: id_names , exp :: exps ) | _ -> assert false ) vbs ( [ ] , [ ] ) in let ids = List . map fst id_names in let names = List . map snd id_names in let exps_id = Ident . create " exps " in let body_id = Ident . create " body " in let body = bind exps_id ( list exps ) ( bind body_id ( quote_expression transl pclos stage body ) ( pair ( Lvar exps_id , Lvar body_id ) ) ) in apply loc Exp . let_rec_simple [ quote_loc loc ; list names ; list_func ids body ] and quote_expression transl pclos stage e = let env = e . exp_env in let loc = e . exp_loc in match e . exp_desc with | Texp_ident ( path , lid , _ ) -> begin let quote_path path = let env = e . exp_env in if Env . cur_stage env <> Env . find_stage path env then let lid = lid_of_path path in let lid = mkloc lid loc in let lid = apply loc Identifier . unmarshal [ marshal_ident lid ] in apply loc Exp . ident [ quote_loc loc ; lid ] else begin match path with | Path . Pident id -> apply loc Exp . var [ quote_loc loc ; Lvar id ] | _ -> fatal_error " Cross - stage identifier has compound path " end in match pclos with | None -> quote_path path | Some ( path_id , map ) -> try let field_idx = Env . PathMap . find path map in let ppf = Format . str_formatter in let open Parsetree in Pprintast . expression ppf { pexp_desc = ( Pexp_ident lid ) ; pexp_loc = Location . none ; pexp_attributes = [ ] ; } ; let str = Format . flush_str_formatter ( ) in let lid = transl_clos_field loc path_id str field_idx in apply loc Exp . ident [ quote_loc loc ; lid ] with Not_found -> quote_path path end | Texp_constant const -> let const = quote_constant loc const in apply loc Exp . constant [ quote_loc loc ; const ] | Texp_let ( rf , vbs , body ) -> begin match rf with | Nonrecursive -> quote_nonrecursive_let transl pclos stage vbs body | Recursive -> quote_recursive_let transl pclos stage loc vbs body end | Texp_function ( label , cases , _ ) -> begin let cbs = List . map ( case_binding false transl pclos stage ) cases in match cbs with | [ Non_binding ( pat , exp ) ] -> let label = quote_arg_label loc label in apply loc Exp . fun_nonbinding [ quote_loc loc ; label ; pat ; exp ] | [ Simple ( name , body ) ] -> let label = quote_arg_label loc label in apply loc Exp . fun_simple [ quote_loc loc ; name ; label ; none ; body ] | [ Pattern ( names , body ) ] -> let label = quote_arg_label loc label in apply loc Exp . fun_pattern [ quote_loc loc ; names ; label ; none ; body ] | cases -> let cases = List . map ( quote_case_binding loc ) cases in apply loc Exp . function_ [ quote_loc loc ; list cases ] end | Texp_apply ( fn , args ) -> let fn = quote_expression transl pclos stage fn in let args = List . filter ( fun ( _ , exp ) -> exp <> None ) args in let args = List . map ( fun ( lbl , exp ) -> match exp with | None -> assert false | Some exp -> let lbl = quote_arg_label loc lbl in let exp = quote_expression transl pclos stage exp in pair ( lbl , exp ) ) args in apply loc Exp . apply [ quote_loc loc ; fn ; list args ] | Texp_match ( exp , cases , exn_cases , _ ) -> let exp = quote_expression transl pclos stage exp in let cases = List . map ( quote_case false transl pclos stage loc ) cases in let exn_cases = List . map ( quote_case true transl pclos stage loc ) exn_cases in apply loc Exp . match_ [ quote_loc loc ; exp ; list ( cases @ exn_cases ) ] | Texp_try ( exp , cases ) -> let exp = quote_expression transl pclos stage exp in let cases = List . map ( quote_case false transl pclos stage loc ) cases in apply loc Exp . try_ [ quote_loc loc ; exp ; list cases ] | Texp_tuple exps -> let exps = List . map ( quote_expression transl pclos stage ) exps in apply loc Exp . tuple [ quote_loc loc ; list exps ] | Texp_construct ( lid , constr , args ) -> let constr = quote_variant_constructor env lid . loc constr in let args = match args with | [ ] -> None | [ arg ] -> let arg = quote_expression transl pclos stage arg in Some arg | _ :: _ -> let args = List . map ( quote_expression transl pclos stage ) args in Some ( apply loc Exp . tuple [ quote_loc loc ; list args ] ) in apply loc Exp . construct [ quote_loc loc ; constr ; option args ] | Texp_variant ( variant , argo ) -> let variant = quote_variant loc variant in let argo = Misc . may_map ( quote_expression transl pclos stage ) argo in apply loc Exp . variant [ quote_loc loc ; variant ; option argo ] | Texp_record { fields = fields ; extended_expression = base } -> let lbl_exps = List . map ( function | ( lbl , ( Overridden ( lid , exp ) ) ) -> let lbl = quote_record_label env ( lid : Longident . t loc ) . loc lbl in let exp = quote_expression transl pclos stage exp in pair ( lbl , exp ) | _ -> assert false ) @@ List . filter ( function | ( _ , ( Overridden _ ) ) -> true | _ -> false ) @@ Array . to_list fields in let base = Misc . may_map ( quote_expression transl pclos stage ) base in apply loc Exp . record [ quote_loc loc ; list lbl_exps ; option base ] | Texp_field ( rcd , lid , lbl ) -> let rcd = quote_expression transl pclos stage rcd in let lbl = quote_record_label env lid . loc lbl in apply loc Exp . field [ quote_loc loc ; rcd ; lbl ] | Texp_setfield ( rcd , lid , lbl , exp ) -> let rcd = quote_expression transl pclos stage rcd in let lbl = quote_record_label env lid . loc lbl in let exp = quote_expression transl pclos stage exp in apply loc Exp . setfield [ quote_loc loc ; rcd ; lbl ; exp ] | Texp_array exps -> let exps = List . map ( quote_expression transl pclos stage ) exps in apply loc Exp . array [ quote_loc loc ; list exps ] | Texp_ifthenelse ( cond , then_ , else_ ) -> let cond = quote_expression transl pclos stage cond in let then_ = quote_expression transl pclos stage then_ in let else_ = Misc . may_map ( quote_expression transl pclos stage ) else_ in apply loc Exp . ifthenelse [ quote_loc loc ; cond ; then_ ; option else_ ] | Texp_sequence ( exp1 , exp2 ) -> let exp1 = quote_expression transl pclos stage exp1 in let exp2 = quote_expression transl pclos stage exp2 in apply loc Exp . sequence [ quote_loc loc ; exp1 ; exp2 ] | Texp_while ( cond , body ) -> let cond = quote_expression transl pclos stage cond in let body = quote_expression transl pclos stage body in apply loc Exp . while_ [ quote_loc loc ; cond ; body ] | Texp_for ( id , pat , low , high , dir , body ) -> let low = quote_expression transl pclos stage low in let high = quote_expression transl pclos stage high in let dir = match dir with | Asttypes . Upto -> true_ | Asttypes . Downto -> false_ in let name = match pat . Parsetree . ppat_desc with | Parsetree . Ppat_var name -> name | Parsetree . Ppat_any -> Location . mkloc " _ " pat . Parsetree . ppat_loc | _ -> assert false in let name = quote_name name . loc name in let body = quote_expression transl pclos stage body in apply loc Exp . for_ [ quote_loc loc ; name ; low ; high ; dir ; func id body ] | Texp_send ( obj , meth , _ ) -> let obj = quote_expression transl pclos stage obj in let meth = quote_method loc meth in apply loc Exp . send [ quote_loc loc ; obj ; meth ] | Texp_assert exp -> let exp = quote_expression transl pclos stage exp in apply loc Exp . assert_ [ quote_loc loc ; exp ] | Texp_lazy exp -> let exp = quote_expression transl pclos stage exp in apply loc Exp . lazy_ [ quote_loc loc ; exp ] | Texp_quote exp -> let exp = quote_expression transl pclos ( stage + 1 ) exp in apply loc Exp . quote [ quote_loc loc ; exp ] | Texp_escape exp -> if stage > 0 then begin let exp = quote_expression transl pclos ( stage - 1 ) exp in apply loc Exp . escape [ quote_loc loc ; exp ] end else transl exp | Texp_new _ | Texp_instvar _ | Texp_setinstvar _ | Texp_override _ | Texp_letmodule _ | Texp_object _ | Texp_pack _ | Texp_unreachable | Texp_letexception _ | Texp_extension_constructor _ -> fatal_error " Expression cannot be quoted " let quote_expression transl pclos exp = quote_expression transl pclos 0 exp let transl_close_expression loc lam = apply loc Exp . to_closed [ lam ] end ) * |
let transl_close_expression _loc e = e |
let wrap_local _loc _id _name lam = lam |
let check_buflen cs = let cslen = Cstruct . len cs in if cslen < packet_length then invalid_arg ( " HID packets must be 64 bytes long , got " ^ string_of_int cslen ) |
module Status = struct type t = . . type t += | Invalid_pin of int | Incorrect_length | Incorrect_length_for_ins | Incompatible_file_structure | Security_status_unsatisfied | Hid_required | Conditions_of_use_not_satisfied | Incorrect_data | File_not_found | Parse_error | Incorrect_params | Incorrect_class | Ins_not_supported | Memory_error | Referenced_data_not_found | Technical_problem of int | Ok | Unknown of int let of_int = function | 0x6700 -> Incorrect_length | 0x6981 -> Incompatible_file_structure | 0x6982 -> Security_status_unsatisfied | 0x6983 -> Hid_required | 0x6985 -> Conditions_of_use_not_satisfied | 0x6a80 -> Incorrect_data | 0x9404 -> File_not_found | 0x9405 -> Parse_error | 0x6b00 -> Incorrect_params | 0x6c00 -> Incorrect_length | 0x6d00 -> Ins_not_supported | 0x6e00 -> Incorrect_class | 0x9000 -> Ok | 0x917e -> Incorrect_length_for_ins | 0x9200 -> Memory_error | 0x6a88 -> Referenced_data_not_found | v when v >= 0x63c0 && v <= 0x63cf -> Invalid_pin ( v land 0x0f ) | v when v >= 0x6f00 && v <= 0x6fff -> Technical_problem ( v land 0xff ) | v -> Unknown v let string_fs = ref [ ] let register_string_f f = string_fs := f :: ! string_fs let to_string = function | Conditions_of_use_not_satisfied -> " Conditions of use not satisfied " | File_not_found -> " File not found " | Hid_required -> " HID required " | Incompatible_file_structure -> " Incompatible file structure " | Incorrect_class -> " Incorrect class " | Incorrect_data -> " Incorrect data " | Incorrect_length -> " Incorrect length " | Incorrect_length_for_ins -> " Incorrect length for instruction " | Incorrect_params -> " Incorrect parameters " | Ins_not_supported -> " Instruction not supported " | Invalid_pin i -> " Invalid pin " ^ string_of_int i | Memory_error -> " Memory error " | Ok -> " Ok " | Parse_error -> " Parse error " | Referenced_data_not_found -> " Referenced data not found " | Security_status_unsatisfied -> " Security status unsatisfied " | Technical_problem i -> " Technical problem " ^ string_of_int i | Unknown i -> Printf . sprintf " Unknown status code 0x % x " i | t -> try List . fold_left begin fun a f -> match f t with Some s -> failwith s | None -> a end " Unregistered status message " ! string_fs with Failure s -> s let help_suggestor_f = ref ( fun _ -> None ) let register_help_suggestor_f f = help_suggestor_f := f let to_help_suggestion t = ! help_suggestor_f t let show t = to_string t let pp ppf t = Format . fprintf ppf " % s % a " ( to_string t ) ( fun ppf -> function | None -> Format . fprintf ppf " " | Some s -> Format . fprintf ppf " - % a " Format . pp_print_text s ) ( to_help_suggestion t ) end |
module Header = struct type t = { cmd : cmd ; seq : int ; } and cmd = Ping | Apdu let cmd_of_int = function | 0x05 -> Some Apdu | 0x02 -> Some Ping | _ -> None module Error = struct type t = | Header_too_short of int | Invalid_channel of int | Invalid_command_tag of int | Unexpected_sequence_number of { expected : int ; actual : int } let pp ppf = function | Header_too_short i -> Format . fprintf ppf " Header too short ( got % d bytes ) " i | Invalid_channel i -> Format . fprintf ppf " Invalid channel ( % d ) " i | Invalid_command_tag i -> Format . fprintf ppf " Invalid command tag ( % d ) " i | Unexpected_sequence_number { expected ; actual } -> Format . fprintf ppf " Unexpected sequence number ( expected % d , got % d ) " expected actual end let fail_header_too_short i = R . error ( Error . Header_too_short i ) let fail_invalid_chan i = R . error ( Error . Invalid_channel i ) let fail_invalid_cmd i = R . error ( Error . Invalid_command_tag i ) let fail_unexpected_seqnum ~ expected ~ actual = R . error ( Error . Unexpected_sequence_number { expected ; actual } ) let read cs = let cslen = Cstruct . len cs in begin if cslen < 5 then fail_header_too_short cslen else R . ok ( ) end >>= fun ( ) -> let channel_id = Cstruct . BE . get_uint16 cs 0 in let cmd = Cstruct . get_uint8 cs 2 in let seq = Cstruct . BE . get_uint16 cs 3 in begin if channel_id <> channel then fail_invalid_chan channel_id else R . ok ( ) end >>= fun ( ) -> begin match cmd_of_int cmd with | Some cmd -> R . ok cmd | None -> fail_invalid_cmd cmd end >>= fun cmd -> R . ok ( { cmd ; seq } , Cstruct . shift cs 5 ) let check_seqnum t expected_seq = if expected_seq <> t . seq then fail_unexpected_seqnum ~ actual : t . seq ~ expected : expected_seq else R . ok ( ) end |
type transport_error = | Hidapi of string | Incomplete_write of int | Incomplete_read of int |
let pp_transport_error ppf = function | Hidapi s -> Format . pp_print_string ppf s | Incomplete_write i -> Format . fprintf ppf " wrote % d bytes , expected to write 64 \ bytes " i | Incomplete_read i -> Format . fprintf ppf " read % d bytes , expected to read 64 \ bytes " i |
type error = | AppError of { status : Status . t ; msg : string } | ApduError of Header . Error . t | TransportError of transport_error |
let app_error ~ msg r = R . reword_error ( fun status -> AppError { status ; msg } ) r |
let apdu_error r = R . reword_error ( fun e -> ApduError e ) r |
let pp_error ppf = function | AppError { status ; msg } -> Format . fprintf ppf " Application level error ( % s ) : % a " msg Status . pp status | ApduError e -> Format . fprintf ppf " APDU level error : % a " Header . Error . pp e | TransportError e -> Format . fprintf ppf " Transport level error : % a " pp_transport_error e |
let check_nbwritten = function | n when n = packet_length -> R . ok ( ) | n -> R . error ( TransportError ( Incomplete_write n ) ) |
let check_nbread = function | n when n = packet_length -> R . ok ( ) | n -> R . error ( TransportError ( Incomplete_read n ) ) |
let write_hidapi h ? len buf = R . reword_error ( fun s -> TransportError ( Hidapi s ) ) ( Hidapi . write h ? len Cstruct . ( to_bigarray ( sub buf 0 packet_length ) ) ) >>= check_nbwritten |
let read_hidapi ? timeout h buf = R . reword_error ( fun s -> TransportError ( Hidapi s ) ) ( Hidapi . read ? timeout h buf packet_length ) >>= check_nbread |
let write_ping ( ? buf = Cstruct . create packet_length ) h = check_buflen buf ; let open Cstruct in BE . set_uint16 buf 0 channel ; set_uint8 buf 2 ping ; BE . set_uint16 buf 3 0 ; memset ( sub buf 5 59 ) 0 ; write_hidapi h buf |
let write_apdu ? pp ( ? buf = Cstruct . create packet_length ) h p = check_buflen buf ; let apdu_len = Apdu . length p in let apdu_buf = Cstruct . create apdu_len in let _nb_written = Apdu . write apdu_buf p in begin match pp with | None -> ( ) | Some pp -> Format . fprintf pp " -> REQ % a . " @ Cstruct . hexdump_pp apdu_buf ; Format . pp_print_flush pp ( ) end ; let apdu_p = ref 0 in let i = ref 0 in let open Cstruct in BE . set_uint16 buf 0 channel ; set_uint8 buf 2 apdu ; BE . set_uint16 buf 3 ! i ; BE . set_uint16 buf 5 apdu_len ; let nb_to_write = ( min apdu_len ( packet_length - 7 ) ) in blit apdu_buf 0 buf 7 nb_to_write ; write_hidapi h buf >>= fun ( ) -> apdu_p := ! apdu_p + nb_to_write ; incr i ; let rec inner apdu_p = if apdu_p >= apdu_len then R . ok ( ) else begin memset buf 0 ; BE . set_uint16 buf 0 channel ; set_uint8 buf 2 apdu ; BE . set_uint16 buf 3 ! i ; let nb_to_write = ( min ( apdu_len - apdu_p ) ( packet_length - 5 ) ) in blit apdu_buf apdu_p buf 5 nb_to_write ; write_hidapi h buf >>= fun ( ) -> incr i ; inner ( apdu_p + nb_to_write ) end in inner ! apdu_p |
let read ? pp ( ? buf = Cstruct . create packet_length ) h = check_buflen buf ; let expected_seq = ref 0 in let full_payload = ref ( Cstruct . create 0 ) in let payload = ref ( Cstruct . create 0 ) in let rec inner ( ) = read_hidapi ~ timeout : 600_000 h ( Cstruct . to_bigarray buf ) >>= fun ( ) -> begin match pp with | None -> ( ) | Some pp -> Format . fprintf pp " <- RAW PKT % a . " @ Cstruct . hexdump_pp ( Cstruct . sub buf 0 packet_length ) ; Format . pp_print_flush pp ( ) end ; apdu_error ( Header . read buf ) >>= fun ( hdr , buf ) -> apdu_error ( Header . check_seqnum hdr ! expected_seq ) >>= fun ( ) -> if hdr . seq = 0 then begin let len = Cstruct . BE . get_uint16 buf 0 in let cs = Cstruct . shift buf 2 in payload := Cstruct . create len ; full_payload := ! payload ; let nb_to_read = min len ( packet_length - 7 ) in Cstruct . blit cs 0 ! payload 0 nb_to_read ; payload := Cstruct . shift ! payload nb_to_read ; expected_seq := ! expected_seq + 1 ; end else begin let nb_to_read = min ( Cstruct . len ! payload ) ( packet_length - 5 ) in Cstruct . blit buf 0 ! payload 0 nb_to_read ; payload := Cstruct . shift ! payload nb_to_read ; expected_seq := ! expected_seq + 1 end ; match Cstruct . len ! payload , hdr . cmd with | 0 , Ping -> R . ok ( Status . Ok , Cstruct . create 0 ) | 0 , Apdu -> let payload_len = Cstruct . len ! full_payload in let sw = Cstruct . BE . get_uint16 ! full_payload ( payload_len - 2 ) in R . ok ( Status . of_int sw , Cstruct . sub ! full_payload 0 ( payload_len - 2 ) ) | _ -> inner ( ) in inner ( ) |
let ping ? pp ? buf h = write_ping ? buf h >>= fun ( ) -> read ? pp ? buf h >>| ignore |
let apdu ? pp ( ? msg " " ) = ? buf h apdu = write_apdu ? pp ? buf h apdu >>= fun ( ) -> read ? pp ? buf h >>= fun ( status , payload ) -> begin match pp with | None -> ( ) | Some pp -> Format . fprintf pp " <- RESP [ % a ] % a . " @ Status . pp status Cstruct . hexdump_pp payload ; Format . pp_print_flush pp ( ) end ; match status with | Status . Ok -> R . ok payload | status -> app_error ~ msg ( R . error status ) |
let write_payload ? pp ( ? msg " = write_payload " ) ? buf ( ? mark_last = false ) ~ cmd ? p1 ? p2 h cs = let rec inner cs = let cs_len = Cstruct . len cs in let lc = min Apdu . max_data_length cs_len in let last = lc = cs_len in let p1 = match last , mark_last , p1 with | true , true , None -> Some 0x80 | true , true , Some p1 -> Some ( 0x80 lor p1 ) | _ -> p1 in apdu ? pp ~ msg ? buf h Apdu . ( create ? p1 ? p2 ~ lc ~ data ( : Cstruct . sub cs 0 lc ) cmd ) >>= fun response -> if last then R . ok response else inner ( Cstruct . shift cs lc ) in if Cstruct . len cs = 0 then R . ok cs else inner cs |
type ' a message_handler = Bigstring . t -> pos : int -> len : int -> ' a |
module Handler_result = struct type ' a t = | Stop of ' a | Continue | Wait of unit Deferred . t end |
module type Reader = sig type t [ @@ deriving sexp_of ] val close : t -> unit Deferred . t val is_closed : t -> bool val read_forever : t -> on_message ( : Bigstring . t -> pos : int -> len : int -> ' a Handler_result . t ) -> on_end_of_batch ( : unit -> unit ) -> ( ' a , [ ` Eof | ` Closed ] ) Result . t Deferred . t end |
module Send_result = struct type message_too_big = { size : int ; max_message_size : int } [ @@ deriving sexp_of ] type ' a t = | Sent of ' a | Closed | Message_too_big of message_too_big [ @@ deriving sexp_of ] end |
module type Writer = sig type t [ @@ deriving sexp_of ] val close : t -> unit Deferred . t val is_closed : t -> bool val monitor : t -> Monitor . t val bytes_to_write : t -> int val stopped : t -> unit Deferred . t val flushed : t -> unit Deferred . t val ready_to_write : t -> unit Deferred . t val send_bin_prot : t -> ' a Bin_prot . Type_class . writer -> ' a -> unit Send_result . t val send_bin_prot_and_bigstring : t -> ' a Bin_prot . Type_class . writer -> ' a -> buf : Bigstring . t -> pos : int -> len : int -> unit Send_result . t val send_bin_prot_and_bigstring_non_copying : t -> ' a Bin_prot . Type_class . writer -> ' a -> buf : Bigstring . t -> pos : int -> len : int -> unit Deferred . t Send_result . t end |
let cpt = ref 0 |
let tot_time = ref 0 . |
let measure_time f s iter = let t0 = Unix . gettimeofday ( ) in let a = f ( ) in let t1 = Unix . gettimeofday ( ) in Printf . printf " % s time % d : % Fs -> average % Fs \ n " %! s ! cpt ( t1 . - t0 ) ( ( t1 . - t0 ) . / ( float iter ) ) ; tot_time := ! tot_time . + ( t1 . - t0 ) ; incr cpt ; a ; ; |
let devices = measure_time Spoc . Devices . init " init " 1 |
let tile_dim = ref 32l |
let block_rows = ref 8l |
let transpose = kern idata odata -> let open Std in let mutable x = thread_idx_x + block_idx_x * @ tile_dim in let mutable y = thread_idx_y + block_idx_y * @ tile_dim in let width = grid_dim_x * @ tile_dim in let ( tile : float32 array ) = create_array ( @ tile_dim * ( @ tile_dim + 1 ) ) in let mutable j = 0 in while j < @ tile_dim do tile . ( ( thread_idx_y + j ) * @ tile_dim + thread_idx_x ) <>- ( idata . [ ( < y + j ) * width + x ] > : float32 ) ; j := j + @ block_rows ; done ; block_barrier ( ) ; x := thread_idx_x + block_idx_y * @ tile_dim ; y := thread_idx_y + block_idx_x * @ tile_dim ; j := 0 ; while j < @ tile_dim do odata . [ ( < y + j ) * width + x ] > <- tile . ( thread_idx_x * @ tile_dim + ( thread_idx_y + j ) ) ; j := j + @ block_rows ; done |
let _ = let nx = ref 1024 and ny = ref 1024 in let dev_id = ref 0 in let arg0 = ( " - d " , Arg . Int ( fun i -> dev_id := i ) , " Choose the device ( default : 0 ) " ) in let arg1 = ( " - nx " , Arg . Int ( fun i -> nx := i ) , " Matrix width ( default 1024 ) " ) in let arg2 = ( " - ny " , Arg . Int ( fun i -> ny := i ) , " Matrix height ( default 1024 ) " ) in Arg . parse [ arg0 ; arg1 ; arg2 ] ( fun s -> ( ) ) " " ; let m1 = Vector . create Vector . float32 ( ! nx * ! ny ) and m2 = Vector . create Vector . float32 ( ! nx * ! ny ) in let dev = devices . ( ! dev_id ) in measure_time ( fun ( ) -> let kind = match dev . Devices . specific_info with | Devices . OpenCLInfo clI -> Devices . OpenCL | _ -> Devices . Cuda in for i = 1 to 10 do ignore ( Kirc . gen ~ only : kind transpose dev ) ; done ; ) " Code generation " 10 ; for i = 0 to ( ! nx - 1 ) * ( ! ny - 1 ) do Mem . set m1 i ( float i ) ; done ; Mem . to_device m1 dev ; Mem . to_device m2 dev ; let open Kernel in let block = { blockX = Int32 . to_int ! tile_dim ; blockY = Int32 . to_int ! block_rows ; blockZ = 1 } and grid = { gridX = ! nx / ( Int32 . to_int ! tile_dim ) ; gridY = ! ny / ( Int32 . to_int ! tile_dim ) ; gridZ = 1 } in Kirc . run transpose ( m1 , m2 ) ( block , grid ) 0 dev ; Devices . flush dev ( ) ; Printf . printf " Starting iterations \ n " ; %! measure_time ( fun ( ) -> for iter = 1 to 10 do Kirc . run transpose ( m1 , m2 ) ( block , grid ) 0 dev ; Devices . flush ~ queue_id : 0 dev ( ) ; done ; ) " Transposition kernel " 10 ; measure_time ( fun ( ) -> for iter = 1 to ! nIters do ignore ( Kirc . gen ~ only : Devices . OpenCL bodyForce dev ) done ; ) " OpenCL Code generation " ; let tot_time = ref 0 . 0 in for iter = 1 to ! nIters do let t0 = Unix . gettimeofday ( ) in Kirc . run bodyForce ( bodiesPos , bodiesVel , dt , ! nBodies ) ( block , grid ) 0 dev ; for i = 0 to ! nBodies - 1 do let bP , bV = ( Mem . get bodiesPos i ) , ( Mem . get bodiesVel i ) in Mem . set bodiesPos i { x = bP . x . + bV . x . * dt ; y = bP . y . + bV . y . * dt ; z = bP . z . + bV . z . * dt ; w = 0 . } ; done ; let tElapsed = ( Unix . gettimeofday ( ) . - t0 ) in if iter > 1 then tot_time := ! tot_time . + tElapsed ; Printf . printf " Iteration % d : . % 3f seconds \ n " %! iter tElapsed ; Printf . printf " Total time : % f \ n " ! tot_time ; ; ; ) * |
module type D = sig type t val equal : t -> t -> bool val to_string : t -> string end |
module type S = sig type d type t exception Unresolved val empty : unit -> t val unknown : unit -> t val pop : t -> t val push : t -> d -> t val to_list_exn : t -> d list val top_exn : t -> d option val unify : t -> t -> unit val print : t -> unit val print_pair : string -> t -> t -> unit end |
module Make ( D : D ) = struct type d = D . t type t = stack ref and h = handler ref and stack = | Empty | Unknown | Link of t | Push of { h : h ; t : t } and handler = | Unknown | Link of h | Label of d let rec rep ( t : t ) = match ! t with | Link t -> rep t | Empty | Unknown | Push _ -> t let rec rep_h ( h : h ) = match ! h with | Link h -> rep_h h | Unknown | Label _ -> h let empty ( ) = ref Empty let unknown ( ) = ref ( Unknown : stack ) let push t h = ref ( Push { h = ref ( Label h ) ; t = rep t } ) let push_unknown t = ref ( Push { h = ref ( Unknown : handler ) ; t = rep t } ) exception Unresolved let top_exn t = match ( ! rep t ) with | Empty -> None | Push p -> ( match ( ! rep_h p . h ) with | Label l -> Some l | Link _ -> assert false | Unknown -> raise Unresolved ) | Link _ -> assert false | Unknown -> raise Unresolved let rec to_list_exn t = match ( ! rep t ) with | Empty -> [ ] | Push p -> ( match ( ! rep_h p . h ) with | Label l -> l :: to_list_exn p . t | Link _ -> assert false | Unknown -> raise Unresolved ) | Link _ -> assert false | Unknown -> raise Unresolved let rec print_h h = match ! h with | Label l -> Printf . printf " % s " ( D . to_string l ) | Link h ' -> Printf . printf " " ; = print_h h ' | Unknown -> Printf . printf " " ? let rec print t = match ! t with | Empty -> Printf . printf " empty \ n " | Unknown -> Printf . printf " ??\ n " | Link s -> Printf . printf " " ; = print s | Push p -> print_h p . h ; Printf . printf " " ; :: print p . t let print_pair_h msg h1 h2 = Printf . printf " % s \ n " msg ; print_h h1 ; print_h h2 let print_pair msg t1 t2 = Printf . printf " % s \ n " msg ; print t1 ; print t2 let fail ( ) = Misc . fatal_error " Malformed trap stack : mismatched pop / push trap handlers . " let link_h ( ~ src : h ) ( ~ dst : h ) = assert ( ! src = Unknown ) ; let rec loop cur = if cur == src then Misc . fatal_error " Trap_stack . unify created a cycle . " ; match ! cur with | Unknown -> ( ) | Label _ -> ( ) | Link h -> loop h in loop dst ; src := Link dst let rec unify_h ( h1 : h ) ( h2 : h ) = match ( ! h1 , ! h2 ) with | Link h1 , Link h2 -> unify_h h1 h2 | Link h , _ -> unify_h h h2 | _ , Link h -> unify_h h1 h | Unknown , _ -> link_h ~ src : h1 ~ dst : h2 | _ , Unknown -> link_h ~ src : h2 ~ dst : h1 | Label l1 , Label l2 -> if not ( D . equal l1 l2 ) then ( print_pair_h " handler labels disagree " : h1 h2 ; fail ( ) ) let link ( ~ src : t ) ( ~ dst : t ) = assert ( ! src = Unknown ) ; let rec loop cur = if cur == src then Misc . fatal_error " Trap_stack . unify created a cycle . " ; match ! cur with | Unknown -> ( ) | Empty -> ( ) | Link t -> loop t | Push { h = _ ; t } -> loop t in loop dst ; src := Link dst let rec unify s1 s2 = match ( ! s1 , ! s2 ) with | Empty , Empty -> ( ) | Link s1 , Link s2 -> unify s1 s2 | Link s , _ -> unify s s2 | _ , Link s -> unify s1 s | Unknown , _ -> link ~ src : s1 ~ dst : s2 | _ , Unknown -> link ~ src : s2 ~ dst : s1 | Push p1 , Push p2 -> unify_h p1 . h p2 . h ; unify p1 . t p2 . t | Empty , _ | _ , Empty -> print_pair " empty " s1 s2 ; fail ( ) let pop t = let res = unknown ( ) in let t ' = push_unknown res in unify t t ' ; res end |
let ( ) = try let k = push emp 1 in let t1 = pop k in let t2 = pop ( push k 2 ) in unify t1 t2 ; assert false with _ -> ( ) |
let ( ) = let t1 = unknown ( ) in let t2 = emp in unify t1 t2 |
let ( ) = let t1 = unknown ( ) in let t2 = push emp 1 in unify t1 t2 |
let ( ) = let t1 = push ( unknown ( ) ) 1 in let t2 = push emp 1 in unify t1 t2 |
let ( ) = let t1 = pop ( unknown ( ) ) in let t2 = pop ( push emp 1 ) in unify t1 t2 |
let ( ) = let t1 = pop ( unknown ( ) ) in let t2 = pop ( push ( pop ( unknown ( ) ) ) 1 ) in unify t1 t2 ; unify t2 t1 |
let ( ) = let t1 = pop ( push ( unknown ( ) ) 1 ) in Printf . printf " t1 is " ; print t1 ; Printf . printf " rep t1 is " ; print ( rep t1 ) |
let ( ) = let t1 = pop ( pop ( push ( unknown ( ) ) 1 ) ) in Printf . printf " t1 is " ; print t1 ; Printf . printf " rep t1 is " ; print ( rep t1 ) |
let ( ) = let k = push emp 1 in let t1 = pop k in let t2 = pop ( push k 2 ) in Printf . printf " t2 is " ; print t2 ; Printf . printf " rep of t2 is " ; print t2 ; Printf . printf " t1 is " ; print t1 ; Printf . printf " rep t1 is " ; print ( rep t1 ) ; Printf . printf " now t2 is " ; print t2 |
module Core ( Req : Preface_specs . Traversable . WITH_TRAVERSE ) = Req |
module Core_over_applicative ( A : Preface_specs . APPLICATIVE ) ( Req : Preface_specs . Traversable . WITH_TRAVERSE with type ' a t = ' a A . t ) = Core ( Req ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.