text
stringlengths 0
601k
|
---|
let cTKtoCAMLanimatedGif s = match splitlist s with | [ width ; height ; frames ; loop ] -> { frames = List . map cTKtoCAMLgifFrame ( splitlist frames ) ; animWidth = int_of_string width ; animHeight = int_of_string height ; loop = int_of_string loop } | _ -> raise ( Invalid_argument ( " cTKtoCAMLgifFrame : " ^ s ) )
|
let available ( ) = let packages = splitlist ( Protocol . tkEval [ | TkToken " package " ; TkToken " names " ] ) | in List . mem " Tkanim " packages
|
let create file = let s = Protocol . tkEval [ | TkToken " animation " ; TkToken " create " ; TkToken file ] | in let anmgif = cTKtoCAMLanimatedGif s in match anmgif . frames with | [ ] -> raise ( TkError " Null frame in a gif " ) ? | [ x ] -> Still ( ImagePhoto x . imagephoto ) | _ -> Animated anmgif
|
let delete anim = List . iter ( fun { imagephoto = i } -> Imagephoto . delete i ) anim . frames
|
let width anm = anm . animWidth
|
let height anm = anm . animHeight
|
let images anm = List . map ( fun x -> x . imagephoto ) anm . frames
|
let image_existence_check img = try ignore ( Imagephoto . height img ) with TkError s -> prerr_endline ( " tkanim : " ^ s ) ; raise ( TkError s )
|
let imagephoto_copy dst src opts = image_existence_check src ; Imagephoto . copy dst src opts
|
let animate_gen w i anim = let length = List . length anim . frames in let frames = Array . of_list anim . frames in let current = ref 0 in let loop = ref anim . loop in let f = frames . ( ! current ) in imagephoto_copy i f . imagephoto [ ImgTo ( f . left , f . top , f . left + f . frameWidth , f . top + f . frameHeight ) ] ; let visible = ref true in let animated = ref false in let timer = ref None in let display_current ( ) = let f = frames . ( ! current ) in imagephoto_copy i f . imagephoto [ ImgTo ( f . left , f . top , f . left + f . frameWidth , f . top + f . frameHeight ) ] in let rec tick ( ) = if not ( Winfo . exists w && Winfo . viewable w ) then begin if ! debug then prerr_endline " Stopped ( Visibility ) " ; visible := false ; end else begin display_current ( ) ; let t = Timer . add ( if f . delay = 0 then 100 else f . delay * 10 ) ( fun ( ) -> incr current ; if ! current = length then begin current := 0 ; if ! loop > 1 then begin decr loop ; if ! loop = 0 then begin if ! debug then prerr_endline " Loop end " ; loop := anim . loop ; timer := None end end end ; tick ( ) ) in timer := Some t end in let start ( ) = animated := true ; tick ( ) in let stop ( ) = match ! timer with | Some t -> Timer . remove t ; timer := None ; animated := false | None -> ( ) in let next ( ) = if ! timer = None then begin incr current ; if ! current = length then current := 0 ; display_current ( ) end in bind w [ [ ] , Visibility ] ( BindSet ( [ ] , ( fun _ -> if not ! visible then begin visible := true ; if ! animated then start ( ) end ) ) ) ; ( function | false -> if ! animated then stop ( ) else start ( ) | true -> next ( ) )
|
let animate label anim = let i = Imagephoto . create [ Width ( Pixels anim . animWidth ) ; Height ( Pixels anim . animHeight ) ] in bind label [ [ ] , Destroy ] ( BindExtend ( [ ] , ( fun _ -> Imagephoto . delete i ) ) ) ; Label . configure label [ ImagePhoto i ] ; animate_gen label i anim
|
let animate_canvas_item canvas tag anim = let i = Imagephoto . create [ Width ( Pixels anim . animWidth ) ; Height ( Pixels anim . animHeight ) ] in bind canvas [ [ ] , Destroy ] ( BindExtend ( [ ] , ( fun _ -> Imagephoto . delete i ) ) ) ; Canvas . configure_image canvas tag [ ImagePhoto i ] ; animate_gen canvas i anim
|
let gifdata s = let tmp_dir = ref Filename . temp_dir_name in let mktemp = let cnter = ref 0 and pid = Unix . getpid ( ) in ( function prefx -> incr cnter ; ( Filename . concat ! tmp_dir ( prefx ^ string_of_int pid ^ " . " ^ string_of_int ! cnter ) ) ) in let fname = mktemp " gifdata " in let oc = open_out_bin fname in try output_string oc s ; close_out oc ; let anim = create fname in Unix . unlink fname ; anim with e -> begin Unix . unlink fname ; raise e end
|
let rec find_loc_expression char_start char_stop expr = if char_start = expr . Typedtree . exp_loc . Location . loc_start && char_stop = expr . Typedtree . exp_loc . Location . loc_end then raise ( Found expr ) ; if char_start >= expr . Typedtree . exp_loc . Location . loc_start && char_stop <= expr . Typedtree . exp_loc . Location . loc_end then find_loc_expression_desc char_start char_stop expr . Typedtree . exp_desc | Typedtree . Texp_ident _ -> ( ) | Typedtree . Texp_constant _ -> ( ) | Typedtree . Texp_let ( _ , bindings , expr ) -> List . iter ( fun ( _ , expr ) -> find_loc_expression char_start char_stop expr ) bindings ; find_loc_expression char_start char_stop expr | Typedtree . Texp_function bindings -> List . iter ( fun ( _ , expr ) -> find_loc_expression char_start char_stop expr ) bindings | Typedtree . Texp_apply ( expr0 , exprs ) -> find_loc_expression char_start char_stop expr0 ; List . iter ( find_loc_expression char_start char_stop ) exprs | Typedtree . Texp_match ( expr , bindings ) -> find_loc_expression char_start char_stop expr ; List . iter ( fun ( _ , expr ) -> find_loc_expression char_start char_stop expr ) bindings | Typedtree . Texp_try ( expr , bindings ) -> find_loc_expression char_start char_stop expr ; List . iter ( fun ( _ , expr ) -> find_loc_expression char_start char_stop expr ) bindings | Typedtree . Texp_tuple exprs -> List . iter ( find_loc_expression char_start char_stop ) exprs | Typedtree . Texp_construct ( _ , expr_opt ) -> ( match expr_opt with None -> ( ) | Some e -> find_loc_expression char_start char_stop e ) | Typedtree . Texp_record ( rec_fields , expr_opt ) -> List . iter ( fun ( _ , e ) -> find_loc_expression char_start char_stop e ) rec_fields ; ( match expr_opt with None -> ( ) | Some e -> find_loc_expression char_start char_stop e ) | Typedtree . Texp_field ( expr , _ ) -> find_loc_expression char_start char_stop expr | Typedtree . Texp_setfield ( expr0 , _ , expr1 ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 | Typedtree . Texp_array exprs -> List . iter ( find_loc_expression char_start char_stop ) exprs | Typedtree . Texp_ifthenelse ( expr0 , expr1 , expr2_opt ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 ; ( match expr2_opt with None -> ( ) | Some e -> find_loc_expression char_start char_stop e ) | Typedtree . Texp_sequence ( expr0 , expr1 ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 | Typedtree . Texp_while ( expr0 , expr1 ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 | Typedtree . Texp_for ( _ , expr0 , expr1 , _ , expr2 ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 ; find_loc_expression char_start char_stop expr2 | Typedtree . Texp_constraint ( expr , _ , _ ) -> find_loc_expression char_start char_stop expr | Typedtree . Texp_when ( expr0 , expr1 ) -> find_loc_expression char_start char_stop expr0 ; find_loc_expression char_start char_stop expr1 | Typedtree . Texp_letmodule ( _ , _ , _ ) -> failwith " tkloadsrc . ml : Texp_letmodule never handled since years " :/ if char_start = mod_expr . Typedtree . mod_loc . Location . loc_start && char_stop = mod_expr . Typedtree . mod_loc . Location . loc_end then ( ) else if char_start >= mod_expr . Typedtree . mod_loc . Location . loc_start && char_stop <= mod_expr . Typedtree . mod_loc . Location . loc_end then find_loc_module_expr_desc char_start char_stop mod_expr . Typedtree . mod_desc else ( ) | Typedtree . Tmod_ident _ -> ( ) | Typedtree . Tmod_structure structure -> find_loc_structure char_start char_stop structure | Typedtree . Tmod_functor ( _ , _ ) -> ( ) | Typedtree . Tmod_apply ( mod_expr0 , mod_expr1 ) -> find_loc_module_expr char_start char_stop mod_expr0 ; find_loc_module_expr char_start char_stop mod_expr1 List . iter ( find_loc_structure_item char_start char_stop ) structure | Typedtree . Tstr_eval expr -> find_loc_expression char_start char_stop expr | Typedtree . Tstr_value ( _ , bindings ) -> List . iter ( fun ( _ , expr ) -> find_loc_expression char_start char_stop expr ) bindings | Typedtree . Tstr_primitive ( _ , _ ) -> ( ) | Typedtree . Tstr_type _ -> ( ) | Typedtree . Tstr_exception _ -> ( ) | Typedtree . Tstr_module ( _ , mod_expr ) -> find_loc_module_expr char_start char_stop mod_expr ; ;
|
let line_column_to_char_number lines_mappping line char = ( lines_mappping . ( line ) ) + char ; ;
|
let char_number_to_line_column lines_mappping char_number = let max_l = Array . length lines_mappping in let rec find l = if l > max_l then assert false ; if char_number < lines_mappping . ( l ) then begin let line = l - 1 in let char = char_number - lines_mappping . ( l - 1 ) in ( line , char ) end else find ( l + 1 ) in find 1 ; ;
|
let create_mark_radical = let cpt = ref 0 in function ( ) -> let name = " MARK " ^ ( string_of_int ! cpt ) in incr cpt ; name ; ;
|
let create_popup parent_w expression = let new_window = Toplevel . create parent_w [ ] in Wm . title_set new_window " Zoom " ; let label0_w = Label . create new_window [ Text " Type of expression " ] in let text0_w = Text . create new_window [ Background ( NamedColor " LightSteelBlue " ) ; let label1_w = Label . create new_window [ Text " Effect of expression " ] in let text1_w = Text . create new_window [ Background ( NamedColor " LightSteelBlue " ) ; let butt0_w = Button . create new_window [ Text " Close " ; bind text0_w [ ( [ ] , ButtonPressDetail 3 ) ] ( BindSet ( [ ] , fun _ -> destroy new_window ) ) ; bind text1_w [ ( [ ] , ButtonPressDetail 3 ) ] ( BindSet ( [ ] , fun _ -> destroy new_window ) ) ; Text . tag_add_char text0_w " WHERE " ( TextIndex ( End , [ ] ) ) ; Text . tag_configure text0_w " WHERE " [ Background White ] ; pack [ label0_w ] [ Side Side_Top ; Fill Fill_Both ] ; pack [ text0_w ] [ Side Side_Top ; Expand true ; Fill Fill_Both ] ; pack [ label1_w ] [ Side Side_Top ; Fill Fill_Both ] ; pack [ text1_w ] [ Side Side_Top ; Expand true ; Fill Fill_Both ] ; pack [ butt0_w ] [ Fill Fill_Both ] ; let ty_expr = expression . Typedtree . exp_type in let mark_r = create_mark_radical ( ) in let pcontext = { Printcontext . widget = text0_w ; Printcontext . root_type = Printcontext . Ml ty_expr ; Printcontext . left_indent = 0 ; Printcontext . mark_radical = mark_r ; Printcontext . tag_buffer = ref " " ; Printcontext . tag_scan_flag = ref false } in let ( old_print , old_flush ) = pp_get_formatter_output_functions std_formatter ( ) in pp_set_formatter_output_functions std_formatter ( fun s pos num -> ( fun ( ) -> ( ) ) ; Text . configure text0_w [ State Normal ] ; pp_print_as std_formatter 0 ( " \ 006START " ^ mark_r " ^\ 008 " ) ; fprintf std_formatter " % a @\ n . " @ ( Tkprinttypes . pp_ml_type pcontext ) ty_expr ; pp_print_as std_formatter 0 ( " \ 006STOP " ^ mark_r " ^\ 008 " ) ; fprintf std_formatter " " @? ; Text . configure text0_w [ State Disabled ] ; pp_set_formatter_output_functions std_formatter old_print old_flush ; let effect_expr = expression . Typedtree . exp_exn in let mark_r = create_mark_radical ( ) in let pcontext = { Printcontext . widget = text1_w ; Printcontext . root_type = Printcontext . Phi effect_expr ; Printcontext . left_indent = 0 ; Printcontext . mark_radical = mark_r ; Printcontext . tag_buffer = ref " " ; Printcontext . tag_scan_flag = ref false } in let ( old_print , old_flush ) = pp_get_formatter_output_functions std_formatter ( ) in pp_set_formatter_output_functions std_formatter ( fun s pos num -> ( fun ( ) -> ( ) ) ; Text . configure text1_w [ State Normal ] ; pp_print_as std_formatter 0 ( " \ 006START " ^ mark_r " ^\ 008 " ) ; effect_expr . Typecore . phi_print <- true ; fprintf std_formatter " % a @\ n . " @ ( Tkprinttypes . pp_phi_type pcontext ) effect_expr ; pp_print_as std_formatter 0 ( " \ 006STOP " ^ mark_r " ^\ 008 " ) ; fprintf std_formatter " " @? ; Text . configure text1_w [ State Disabled ] ; pp_set_formatter_output_functions std_formatter old_print old_flush ; ;
|
let make_callback widget lines_mappping syntax_tree _ = try begin let ( line , char ) = ( match Text . index widget ( TextIndex ( TagFirst " sel " , [ ] ) ) with LineChar ( l , c ) -> ( l - 1 , c ) | _ -> assert false ) in let char_start = line_column_to_char_number lines_mappping line char in let ( line ' , char ' ) = ( match Text . index widget ( TextIndex ( TagLast " sel " , [ ] ) ) with LineChar ( l , c ) -> ( l - 1 , c ) | _ -> assert false ) in let char_stop = line_column_to_char_number lines_mappping line ' char ' in try find_loc_structure char_start char_stop syntax_tree ; Bell . ring ( ) with Found expr -> let ( start_l , start_c ) = char_number_to_line_column lines_mappping ( expr . Typedtree . exp_loc . Location . loc_start ) in let ( stop_l , stop_c ) = char_number_to_line_column lines_mappping ( expr . Typedtree . exp_loc . Location . loc_end ) in Text . tag_delete widget [ " EXPR " ] ; Text . tag_add widget " EXPR " ( TextIndex ( LineChar ( start_l + 1 , start_c ) , [ ] ) ) ( TextIndex ( LineChar ( stop_l + 1 , stop_c ) , [ ] ) ) ; Text . tag_configure widget " EXPR " [ Relief Raised ; BorderWidth ( Pixels 1 ) ; Background Red ] ; create_popup widget expr end with Protocol . TkError _ -> Bell . ring ( ) ; ;
|
let load_source widget filename syntax_tree = let in_channel = Stdlibpath . open_in_with_path filename in let char_of_begin_line = ref 0 in let current_mapping = ref [ ] in try while true do current_mapping := ! char_of_begin_line :: ! current_mapping ; let l = ( input_line in_channel ) " ^\ n " in char_of_begin_line := ! char_of_begin_line + String . length l ; Text . insert widget ( TextIndex ( End , [ ] ) ) l [ ] done with End_of_file -> close_in in_channel ; let array_of_list = Array . of_list ( List . rev ! current_mapping ) in let callback = make_callback widget array_of_list syntax_tree in bind widget [ ( [ ] , ButtonReleaseDetail 1 ) ] ( BindSet ( [ ] , callback ) ) ; ;
|
let scan_string pcontext s pos num = let text_w = pcontext . Printcontext . widget in let tag_buffer = pcontext . Printcontext . tag_buffer in let tag_scan_flag = pcontext . Printcontext . tag_scan_flag in let start = ref pos in for i = pos to pos + num - 1 do match s . [ i ] with | ' \ 006 ' -> ( String . sub s ! start ( i - ! start ) ) [ ! tag_buffer ] ; | ' \ 007 ' -> | ' \ 008 ' -> | whatever -> done ; if not ! tag_scan_flag then Text . insert text_w ( TextIndex ( End , [ ] ) ) ( String . sub s ! start ( num - ! start ) ) [ ! tag_buffer ] ; ;
|
let scan_string_at pcontext index s pos num = let text_w = pcontext . Printcontext . widget in let tag_buffer = pcontext . Printcontext . tag_buffer in let tag_scan_flag = pcontext . Printcontext . tag_scan_flag in let left_indent = pcontext . Printcontext . left_indent in let start = ref pos in for i = pos to pos + num - 1 do match s . [ i ] with | ' \ 006 ' -> ( String . sub s ! start ( i - ! start ) ) [ ! tag_buffer ] ; | ' \ 007 ' -> | ' \ 008 ' -> | ' \ 010 ' -> ( String . sub s ! start ( i - ! start ) ) [ ! tag_buffer ] ; start := i + 1 | whatever -> done ; if not ! tag_scan_flag then Text . insert text_w index ( String . sub s ! start ( num - ! start ) ) [ ! tag_buffer ] ; ;
|
let create_mark_radical = let cpt = ref 0 in function ( ) -> let name = " MARK " ^ ( string_of_int ! cpt ) in incr cpt ; name ; ;
|
let pp_label_description pcontext ppf lbl_desc = fprintf ppf " % a :@ % a " Printbasic . pp_mutable_flag lbl_desc . Typedtree . fld_mut ( Tkprinttypes . pp_ml_type_scheme pcontext ) lbl_desc . Typedtree . fld_scheme ; ;
|
let rec pp_signature pcontext ppf signature = let iter_pp_signature_item = Printbasic . iter_pp " " ( pp_signature_item pcontext ) in fprintf ppf " % a " iter_pp_signature_item signature | Typedtree . Tsig_value ( ident , scheme ) -> let mark_r = create_mark_radical ( ) in let pcontext ' = { pcontext with Printcontext . mark_radical = mark_r } in fprintf ppf " @< 0 >% sval @< 0 >% s [ @ % s :@ @< 0 >% s % a ] @@< 0 >% s " " \ 006VAL \ 007 " " \ 006 \ 007 " ( Ident . name ident ) ( " \ 006START " ^ mark_r " ^\ 008 " ) ( Tkprinttypes . pp_ml_type_scheme pcontext ' ) scheme ( " \ 006STOP " ^ mark_r " ^\ 008 " ) ; | Typedtree . Tsig_type ( ident , ty_declaration ) -> fprintf ppf " typ [ @ e % a ] " @ ( Tkprinttypes . pp_type_declaration pcontext ) ( ident , ty_declaration ) | Typedtree . Tsig_module ( ident , mod_ty ) -> fprintf ppf " @< 0 >% smod [ @ ule @< 0 >% s % s :@ % a ] " @ " \ 006MODULE \ 007 " " \ 006 \ 007 " ( Ident . name ident ) ( pp_module_type pcontext ) mod_ty | Typedtree . Tsig_constructor ( id , cd ) -> let mark_r = create_mark_radical ( ) in let pcontext ' = { pcontext with begin match cd . Typedtree . cstr_kind with | Typedtree . Exn file -> " \ 006CONSTRUCTOR \ 007 " " \ 006 \ 007 " file ( Ident . name id ) ( Tkprinttypes . pp_ml_type_scheme pcontext ' ) cd . Typedtree . cstr_scheme | Typedtree . Sum -> " \ 006CONSTRUCTOR \ 007 " " \ 006 \ 007 " ( Tkprinttypes . pp_ml_type_scheme pcontext ' ) cd . Typedtree . cstr_scheme end | Typedtree . Tsig_label ( id , lbl_descr ) -> let mark_r = create_mark_radical ( ) in let pcontext ' = { pcontext with fprintf ppf " @< 0 >% srec [ @ ord label @< 0 >% s % s @< 0 >% s % a ] @@< 0 >% s " " \ 006LABEL \ 007 " " \ 006 \ 007 " ( Ident . name id ) ( " \ 006START " ^ mark_r " ^\ 008 " ) ( pp_label_description pcontext ' ) lbl_descr ( " \ 006STOP " ^ mark_r " ^\ 008 " ) | Typedtree . Tmty_signature signature -> fprintf ppf " [ @< hv > sig ; @< 1 1 [ >@< hv >% a ] @@ end ] " @ ( pp_signature pcontext ) signature | Typedtree . Tmty_functor ( _ , _ ) -> fprintf ppf " functor ( body skiped : only applications are displayed ) " ; ;
|
let jobs : ( unit -> unit ) Queue . t = Queue . create ( )
|
let m = Mutex . create ( )
|
let with_jobs f = Mutex . lock m ; let y = f jobs in Mutex . unlock m ; y
|
let loop_id = ref None
|
let gui_safe ( ) = ! loop_id = Some ( Thread . id ( Thread . self ( ) ) )
|
let running ( ) = ! loop_id <> None
|
let has_jobs ( ) = not ( with_jobs Queue . is_empty )
|
let n_jobs ( ) = with_jobs Queue . length
|
let do_next_job ( ) = with_jobs Queue . take ( )
|
let async j x = with_jobs ( Queue . add ( fun ( ) -> j x ) )
|
let sync f x = if ! loop_id = None then failwith " Tkthread . sync " ; if gui_safe ( ) then f x else let m = Mutex . create ( ) in let res = ref None in Mutex . lock m ; let c = Condition . create ( ) in let j x = let y = f x in Mutex . lock m ; res := Some y ; Mutex . unlock m ; Condition . signal c in async j x ; Condition . wait c m ; match ! res with Some y -> y | None -> assert false
|
let rec job_timer ( ) = Timer . set ~ ms : 10 ~ callback : ( fun ( ) -> for i = 1 to n_jobs ( ) do do_next_job ( ) done ; job_timer ( ) )
|
let thread_main ( ) = try loop_id := Some ( Thread . id ( Thread . self ( ) ) ) ; ignore ( Protocol . openTk ( ) ) ; job_timer ( ) ; Protocol . mainLoop ( ) ; loop_id := None ; with exn -> loop_id := None ; raise exn
|
let start ( ) = let th = Thread . create thread_main ( ) in loop_id := Some ( Thread . id th ) ; th
|
let no_documentation = Printf . sprintf " ` % s ` documentation is not available . \ n Consider contributing Pull Request to https :// github . com / tldr - pages / tldr "
|
let display_page command platform update_cache = ignore update_cache ; match get_page command platform with | Missing -> Stdio . printf " % s \ n " ( no_documentation command ) | Error e -> Stdio . printf " % s \ n " e | Success page -> Display . display page
|
module Args = struct open Arg let command = let doc = " Display the tldr page for ( $ docv ) " in non_empty & pos_all string [ ] & info [ ] ~ docv " : COMMAND " ~ doc let platform = let doc = " Display the command for a given ( $ docv ) . Options can be one of [ linux , sunos , osx ] . " in value & opt string Environment . system & info [ " p " ; " platform " ] ~ docv " : PLATFORM " ~ doc let update_cache = let doc = " Update the local cache . " in value & flag & info [ " u " ; " update " ] ~ docv " : UPDATE " ~ doc end
|
let ( ) = let open Term in let info = let doc = " Simplified man pages " in let man = [ ` S Manpage . s_bugs ; ` P " Email bug reports to < rosaleschase . j @ gmail . com . " > ] in info " tldr " ~ version " : 0 . 3 . 0 " ~ doc ~ man in let run_t = const display_page $ ( const ( String . concat ~ sep " " ) :- $ Args . command ) $ Args . platform $ Args . update_cache in exit @@ eval ( run_t , info )
|
let try_to_close t = match % map Session . close_tls t with | Ok ( ) -> ( ) | Error tls_close_error -> Log . Global . error_s [ % sexp ( tls_close_error : Error . t ) ] ; ;
|
let pipe t = let b_reader = Cstruct . create 0x8000 in let rec f_reader writer = match % bind Session . read t b_reader with | Ok 0 -> Pipe . close writer ; return ( ) | Ok len -> let % bind ( ) = Pipe . write writer ( Cstruct . to_string ( Cstruct . sub b_reader 0 len ) ) in f_reader writer | Error read_error -> Log . Global . error_s [ % sexp ( read_error : Error . t ) ] ; Pipe . close writer ; return ( ) in let rec f_writer reader = let % bind pipe_read = Pipe . read reader in match pipe_read with | ` Ok s -> ( match % bind Session . writev t [ Cstruct . of_string s ] with | Ok ( ) -> f_writer reader | Error ( _ : Error . t ) -> try_to_close t ) | ` Eof -> try_to_close t in Pipe . create_reader ~ close_on_exception : false f_reader , Pipe . create_writer f_writer ; ;
|
let upgrade_connection tls_session ( ( _ : Reader . t ) , outer_writer ) = let pipe_r , pipe_w = pipe tls_session in let % bind inner_reader = Reader . of_pipe ( Info . of_string " tls_reader " ) pipe_r in let % map inner_writer , ` Closed_and_flushed_downstream inner_cafd = Writer . of_pipe ( Info . of_string " tls_writer " ) pipe_w in Writer . set_raise_when_consumer_leaves inner_writer false ; let outer_cafd = let % bind ( ) = Writer . close_finished inner_writer in let % bind ( ) = inner_cafd in let % bind ( ) = try_to_close tls_session in Writer . flushed outer_writer in tls_session , inner_reader , inner_writer , ` Tls_closed_and_flushed_downstream outer_cafd ; ;
|
let upgrade_server_reader_writer_to_tls config rw = let open Deferred . Or_error . Let_syntax in let % bind tls_session = Session . server_of_fd config rw in upgrade_connection tls_session rw |> Deferred . ok ; ;
|
let upgrade_client_reader_writer_to_tls ? host config rw = let open Deferred . Or_error . Let_syntax in let % bind tls_session = Session . client_of_fd ? host config rw in upgrade_connection tls_session rw |> Deferred . ok ; ;
|
let listen ? buffer_age_limit ? max_connections ? max_accepts_per_batch ? backlog ? socket ~ on_handler_error config where_to_listen handle_client = let tls_handler sock outer_reader outer_writer = let % bind ( tls_session , inner_reader , inner_writer , ` Tls_closed_and_flushed_downstream inner_cafd ) = upgrade_server_reader_writer_to_tls config ( outer_reader , outer_writer ) |> Deferred . Or_error . ok_exn in Monitor . protect ( fun ( ) -> handle_client sock tls_session inner_reader inner_writer ) ~ finally ( : fun ( ) -> Deferred . all_unit [ Reader . close inner_reader ; Writer . close inner_writer ; inner_cafd ] ) in Tcp . Server . create ? buffer_age_limit ? max_connections ? max_accepts_per_batch ? backlog ? socket ~ on_handler_error where_to_listen tls_handler ; ;
|
let connect ? socket ? buffer_age_limit ? interrupt ? reader_buffer_size ? writer_buffer_size ? timeout ? time_source config where_to_connect ~ host = let open Deferred . Or_error . Let_syntax in let % bind ( _ : ( [ ` Active ] , ' a ) Socket . t ) , outer_reader , outer_writer = Tcp . connect ? socket ? buffer_age_limit ? interrupt ? reader_buffer_size ? writer_buffer_size ? timeout ? time_source where_to_connect |> Deferred . ok in let % bind ( tls_session , inner_reader , inner_writer , ` Tls_closed_and_flushed_downstream inner_cafd ) = upgrade_client_reader_writer_to_tls ? host config ( outer_reader , outer_writer ) in don ' t_wait_for ( let % bind . Deferred ( ) = inner_cafd in Deferred . all_unit [ Writer . close outer_writer ; Reader . close outer_reader ] ) ; return ( tls_session , inner_reader , inner_writer ) ; ;
|
let ( ) = Mirage_crypto_rng_async . initialize ( module Mirage_crypto_rng . Fortuna )
|
let ( . <> ) f g x = f ( g x )
|
module type FLOW = sig type t type error type ' + a io val read : t -> bytes -> int -> int -> ( [ ` End | ` Len of int ] , error ) result io val fully_write : t -> string -> int -> int -> ( unit , error ) result io val close : t -> unit io val bind : ' a io -> ( ' a -> ' b io ) -> ' b io val map : ( ' a -> ' b ) -> ' a io -> ' b io val return : ' a -> ' a io end
|
module Make ( Flow : FLOW ) = struct type error = | Alert of Tls . Packet . alert_type | Failure of Tls . Engine . failure | Flow_error of Flow . error | Closed let ( >>= ) = Flow . bind let ( >>| ) x f = Flow . map f x let return = Flow . return type t = { socket : Flow . t ; mutable state : [ ` Active of Tls . Engine . state | ` Eof | ` Error of error ] ; mutable linger : Cstruct . t list ; } let fully_write socket ( { Cstruct . len ; _ } as cs ) = Flow . fully_write socket ( Cstruct . to_string cs ) 0 len >>| R . reword_error ( fun err -> Flow_error err ) let read socket = let buf = Bytes . create 0x1000 in Flow . read socket buf 0 ( Bytes . length buf ) >>= function | Ok ` End -> return ` Eof | Ok ( ` Len len ) -> return ( ` Data ( Cstruct . of_bytes ~ off : 0 ~ len buf ) ) | Error err -> return ( ` Error ( Flow_error err ) ) let check_write flow f_res = ( match flow . state , f_res with | ` Active _ , Error err -> flow . state <- ` Error err ; Flow . close flow . socket | _ -> return ( ) ) >>| fun ( ) -> match f_res with | Ok ( ) -> Ok ( ) | Error e -> Error e let read_react flow = let handle tls buf = match Tls . Engine . handle_tls tls buf with | Ok ( res , ` Response resp , ` Data data ) -> flow . state <- ( match res with | ` Ok tls -> ` Active tls | ` Eof -> ` Eof | ` Alert alert -> ` Error ( Alert alert ) ) ; ( match resp with | None -> return ( Ok ( ) ) | Some buf -> fully_write flow . socket buf >>= check_write flow ) >>= fun _ -> ( match res with | ` Ok _ -> return ( ) | _ -> Flow . close flow . socket ) >>= fun ( ) -> return @@ ` Ok data | Error ( fail , ` Response resp ) -> let r = ` Error ( Failure fail ) in flow . state <- r ; fully_write flow . socket resp |> fun _ -> Flow . close flow . socket >>= fun ( ) -> return r in match flow . state with | ` Eof | ` Error _ as e -> return e | ` Active _ -> read flow . socket >>= function | ` Eof | ` Error _ as e -> flow . state <- e ; return e | ` Data buf -> match flow . state with | ` Active tls -> handle tls buf | ` Eof | ` Error _ as e -> return e let rec read flow = match flow . linger with | [ ] -> ( read_react flow >>= function | ` Ok None -> read flow | ` Ok ( Some buf ) -> return ( Result . Ok ( ` Data buf ) ) | ` Eof -> return ( Result . Ok ` Eof ) | ` Error e -> return ( Result . Error e ) ) | bufs -> flow . linger <- [ ] ; return @@ Ok ( ` Data ( Cstruct . concat @@ List . rev bufs ) ) let writev flow bufs = match flow . state with | ` Eof -> return ( Result . Error Closed ) | ` Error err -> return ( Result . Error err ) | ` Active tls -> match Tls . Engine . send_application_data tls bufs with | Some ( tls , answer ) -> flow . state <- ` Active tls ; fully_write flow . socket answer >>= check_write flow | None -> assert false let write flow cs = writev flow [ cs ] let close flow = match flow . state with | ` Active tls -> flow . state <- ` Eof ; let _ , buf = Tls . Engine . send_close_notify tls in fully_write flow . socket buf >>= fun _ -> return ( ) | _ -> return ( ) let rec drain_handshake flow = match flow . state with | ` Active tls when not ( Tls . Engine . handshake_in_progress tls ) -> return ( Ok flow ) | _ -> ( read_react flow >>= function | ` Ok ( Some mbuf ) -> flow . linger <- mbuf :: flow . linger ; drain_handshake flow | ` Ok None -> drain_handshake flow | ` Error err -> return ( Result . Error err ) | ` Eof -> return ( Result . Error Closed ) ) let init_client cfg socket = let tls , init = Tls . Engine . client cfg in let flow = { socket ; state = ` Active tls ; linger = [ ] } in fully_write socket init >>= fun _ -> drain_handshake flow let init_server cfg socket = let flow = { socket ; state = ` Active ( Tls . Engine . server cfg ) ; linger = [ ] } in drain_handshake flow end
|
let o f g x = f ( g x )
|
let resolve host service = let open Lwt_unix in getprotobyname " tcp " >>= fun tcp -> getaddrinfo host service [ AI_PROTOCOL tcp . p_proto ] >>= function | [ ] -> let msg = Printf . sprintf " no address for % s :% s " host service in fail ( Invalid_argument msg ) | ai :: _ -> return ai . ai_addr
|
module Lwt_cs = struct let naked ~ name f fd cs = Cstruct . ( f fd cs . buffer cs . off cs . len ) >>= fun res -> match Lwt_unix . getsockopt_error fd with | None -> return res | Some err -> fail @@ Unix . Unix_error ( err , name , " " ) let write = naked ~ name " : Tls_lwt . write " Lwt_bytes . write and read = naked ~ name " : Tls_lwt . read " Lwt_bytes . read let rec write_full fd = function | cs when Cstruct . length cs = 0 -> return_unit | cs -> write fd cs >>= o ( write_full fd ) ( Cstruct . shift cs ) end
|
module Unix = struct type t = { fd : Lwt_unix . file_descr ; mutable state : [ ` Active of Tls . Engine . state | ` Eof | ` Error of exn ] ; mutable linger : Cstruct . t option ; recv_buf : Cstruct . t ; } let safely th = Lwt . catch ( fun ( ) -> th >>= fun _ -> return_unit ) ( fun _ -> return_unit ) let ( read_t , write_t ) = let recording_errors op t cs = Lwt . catch ( fun ( ) -> op t . fd cs ) ( fun exn -> ( match t . state with | ` Error _ | ` Eof -> ( ) | ` Active _ -> t . state <- ` Error exn ) ; fail exn ) in ( recording_errors Lwt_cs . read , recording_errors Lwt_cs . write_full ) let when_some f = function None -> return_unit | Some x -> f x let rec read_react t = let handle tls buf = match Tls . Engine . handle_tls tls buf with | Ok ( state ' , ` Response resp , ` Data data ) -> let state ' = match state ' with | ` Ok tls -> ` Active tls | ` Eof -> ` Eof | ` Alert a -> ` Error ( Tls_alert a ) in t . state <- state ' ; safely ( resp |> when_some ( write_t t ) ) >|= fun ( ) -> ` Ok data | Error ( alert , ` Response resp ) -> t . state <- ` Error ( Tls_failure alert ) ; write_t t resp >>= fun ( ) -> read_react t in match t . state with | ` Error e -> fail e | ` Eof -> return ` Eof | ` Active _ -> read_t t t . recv_buf >>= fun n -> match ( t . state , n ) with | ( ` Active _ , 0 ) -> t . state <- ` Eof ; return ` Eof | ( ` Active tls , n ) -> handle tls ( Cstruct . sub t . recv_buf 0 n ) | ( ` Error e , _ ) -> fail e | ( ` Eof , _ ) -> return ` Eof let rec read t buf = let writeout res = let open Cstruct in let rlen = length res in let n = min ( length buf ) rlen in blit res 0 buf 0 n ; t . linger <- ( if n < rlen then Some ( sub res n ( rlen - n ) ) else None ) ; return n in match t . linger with | Some res -> writeout res | None -> read_react t >>= function | ` Eof -> return 0 | ` Ok None -> read t buf | ` Ok ( Some res ) -> writeout res let writev t css = match t . state with | ` Error err -> fail err | ` Eof -> fail @@ Invalid_argument " tls : closed socket " | ` Active tls -> match Tls . Engine . send_application_data tls css with | Some ( tls , tlsdata ) -> ( t . state <- ` Active tls ; write_t t tlsdata ) | None -> fail @@ Invalid_argument " tls : write : socket not ready " let write t cs = writev t [ cs ] let rec drain_handshake t = let push_linger t mcs = match ( mcs , t . linger ) with | ( None , _ ) -> ( ) | ( scs , None ) -> t . linger <- scs | ( Some cs , Some l ) -> t . linger <- Some ( Cstruct . append l cs ) in match t . state with | ` Active tls when not ( Tls . Engine . handshake_in_progress tls ) -> return t | _ -> read_react t >>= function | ` Eof -> fail End_of_file | ` Ok cs -> push_linger t cs ; drain_handshake t let reneg ? authenticator ? acceptable_cas ? cert ( ? drop = true ) t = match t . state with | ` Error err -> fail err | ` Eof -> fail @@ Invalid_argument " tls : closed socket " | ` Active tls -> match Tls . Engine . reneg ? authenticator ? acceptable_cas ? cert tls with | None -> fail @@ Invalid_argument " tls : can ' t renegotiate " | Some ( tls ' , buf ) -> if drop then t . linger <- None ; t . state <- ` Active tls ' ; write_t t buf >>= fun ( ) -> drain_handshake t >>= fun _ -> return_unit let key_update ? request t = match t . state with | ` Error err -> fail err | ` Eof -> fail @@ Invalid_argument " tls : closed socket " | ` Active tls -> match Tls . Engine . key_update ? request tls with | Error _ -> fail @@ Invalid_argument " tls : can ' t update key " | Ok ( tls ' , buf ) -> t . state <- ` Active tls ' ; write_t t buf let close_tls t = match t . state with | ` Active tls -> let ( _ , buf ) = Tls . Engine . send_close_notify tls in t . state <- ` Eof ; write_t t buf | _ -> return_unit let close t = safely ( close_tls t ) >>= fun ( ) -> Lwt_unix . close t . fd let server_of_fd config fd = drain_handshake { state = ` Active ( Tls . Engine . server config ) ; fd = fd ; linger = None ; recv_buf = Cstruct . create 4096 } let client_of_fd config ? host fd = let config ' = match host with | None -> config | Some host -> Tls . Config . peer config host in let t = { state = ` Eof ; fd = fd ; linger = None ; recv_buf = Cstruct . create 4096 } in let ( tls , init ) = Tls . Engine . client config ' in let t = { t with state = ` Active tls } in write_t t init >>= fun ( ) -> drain_handshake t let accept conf fd = Lwt_unix . accept fd >>= fun ( fd ' , addr ) -> Lwt . catch ( fun ( ) -> server_of_fd conf fd ' >|= fun t -> ( t , addr ) ) ( fun exn -> safely ( Lwt_unix . close fd ' ) >>= fun ( ) -> fail exn ) let connect conf ( host , port ) = resolve host ( string_of_int port ) >>= fun addr -> let fd = Lwt_unix . ( socket ( Unix . domain_of_sockaddr addr ) SOCK_STREAM 0 ) in Lwt . catch ( fun ( ) -> let host = Result . to_option ( Result . bind ( Domain_name . of_string host ) Domain_name . host ) in Lwt_unix . connect fd addr >>= fun ( ) -> client_of_fd conf ? host fd ) ( fun exn -> safely ( Lwt_unix . close fd ) >>= fun ( ) -> fail exn ) let read_bytes t bs off len = read t ( Cstruct . of_bigarray ~ off ~ len bs ) let write_bytes t bs off len = write t ( Cstruct . of_bigarray ~ off ~ len bs ) let epoch t = match t . state with | ` Active tls -> ( match Tls . Engine . epoch tls with | ` InitialEpoch -> assert false | ` Epoch data -> Ok data ) | ` Eof -> Error ( ) | ` Error _ -> Error ( ) end
|
let of_t ? close t = let close = match close with | Some f -> ( fun ( ) -> Unix . safely ( f ( ) ) ) | None -> ( fun ( ) -> match Lwt_unix . state t . Unix . fd with | Lwt_unix . Closed -> Lwt . return_unit | Lwt_unix . Opened | Lwt_unix . Aborted _ -> Unix . ( safely ( close t ) ) ) in ( Lwt_io . make ~ close ~ mode : Lwt_io . Input ( Unix . read_bytes t ) ) , ( Lwt_io . make ~ close ~ mode : Lwt_io . Output @@ fun a b c -> Unix . write_bytes t a b c >>= fun ( ) -> return c )
|
let accept_ext conf fd = Unix . accept conf fd >|= fun ( t , peer ) -> ( of_t t , peer ) Unix . connect conf addr >|= of_t
|
let accept certificate = let config = Tls . Config . server ~ certificates : certificate ( ) in accept_ext config let config = Tls . Config . client ~ authenticator ( ) in connect_ext config addr
|
let ( ) = Mirage_crypto_rng_lwt . initialize ( )
|
let ( ) = Printexc . register_printer ( function | Tls_alert typ -> Some ( " TLS alert from peer : " ^ Tls . Packet . alert_type_to_string typ ) | Tls_failure f -> Some ( " TLS failure : " ^ Tls . Engine . string_of_failure f ) | _ -> None )
|
module Make ( F : Mirage_flow . S ) = struct module FLOW = F type error = [ ` Tls_alert of Tls . Packet . alert_type | ` Tls_failure of Tls . Engine . failure | ` Read of F . error | ` Write of F . write_error ] type write_error = [ Mirage_flow . write_error | error ] let pp_error ppf = function | ` Tls_failure f -> Fmt . string ppf @@ Tls . Engine . string_of_failure f | ` Tls_alert a -> Fmt . string ppf @@ Tls . Packet . alert_type_to_string a | ` Read e -> F . pp_error ppf e | ` Write e -> F . pp_write_error ppf e let pp_write_error ppf = function | # Mirage_flow . write_error as e -> Mirage_flow . pp_write_error ppf e | # error as e -> pp_error ppf e type flow = { role : [ ` Server | ` Client ] ; flow : FLOW . flow ; mutable state : [ ` Active of Tls . Engine . state | ` Eof | ` Error of error ] ; mutable linger : Cstruct . t list ; } let tls_alert a = ` Error ( ` Tls_alert a ) let tls_fail f = ` Error ( ` Tls_failure f ) let list_of_option = function None -> [ ] | Some x -> [ x ] let lift_read_result = function | Ok ( ` Data _ | ` Eof as x ) -> x | Error e -> ` Error ( ` Read e ) let lift_write_result = function | Ok ( ) -> ` Ok ( ) | Error e -> ` Error ( ` Write e ) let check_write flow f_res = let res = lift_write_result f_res in ( match flow . state , res with | ` Active _ , ( ` Eof | ` Error _ as e ) -> flow . state <- e ; FLOW . close flow . flow | _ -> return_unit ) >|= fun ( ) -> match f_res with | Ok ( ) -> Ok ( ) | Error e -> Error ( ` Write e :> write_error ) let read_react flow = let handle tls buf = match Tls . Engine . handle_tls tls buf with | Ok ( res , ` Response resp , ` Data data ) -> flow . state <- ( match res with | ` Ok tls -> ` Active tls | ` Eof -> ` Eof | ` Alert alert -> tls_alert alert ) ; ( match resp with | None -> return @@ Ok ( ) | Some buf -> FLOW . write flow . flow buf >>= check_write flow ) >>= fun _ -> ( match res with | ` Ok _ -> return_unit | _ -> FLOW . close flow . flow ) >>= fun ( ) -> return @@ ` Ok data | Error ( fail , ` Response resp ) -> let reason = tls_fail fail in flow . state <- reason ; FLOW . ( write flow . flow resp >>= fun _ -> close flow . flow ) >>= fun ( ) -> return reason in match flow . state with | ` Eof | ` Error _ as e -> return e | ` Active _ -> FLOW . read flow . flow >|= lift_read_result >>= function | ` Eof | ` Error _ as e -> flow . state <- e ; return e | ` Data buf -> match flow . state with | ` Active tls -> handle tls buf | ` Eof | ` Error _ as e -> return e let rec read flow = match flow . linger with | [ ] -> ( read_react flow >>= function | ` Ok None -> read flow | ` Ok ( Some buf ) -> return @@ Ok ( ` Data buf ) | ` Eof -> return @@ Ok ` Eof | ` Error e -> return @@ Error e ) | bufs -> flow . linger <- [ ] ; return @@ Ok ( ` Data ( Cstruct . concat @@ List . rev bufs ) ) let writev flow bufs = match flow . state with | ` Eof -> return @@ Error ` Closed | ` Error e -> return @@ Error ( e :> write_error ) | ` Active tls -> match Tls . Engine . send_application_data tls bufs with | Some ( tls , answer ) -> flow . state <- ` Active tls ; FLOW . write flow . flow answer >>= check_write flow | None -> assert false let write flow buf = writev flow [ buf ] let rec drain_handshake flow = match flow . state with | ` Active tls when not ( Tls . Engine . handshake_in_progress tls ) -> return @@ Ok flow | _ -> read_react flow >>= function | ` Ok mbuf -> flow . linger <- list_of_option mbuf @ flow . linger ; drain_handshake flow | ` Error e -> return @@ Error ( e :> write_error ) | ` Eof -> return @@ Error ` Closed let reneg ? authenticator ? acceptable_cas ? cert ( ? drop = true ) flow = match flow . state with | ` Eof -> return @@ Error ` Closed | ` Error e -> return @@ Error ( e :> write_error ) | ` Active tls -> match Tls . Engine . reneg ? authenticator ? acceptable_cas ? cert tls with | None -> invalid_arg " Renegotiation already in progress " | Some ( tls ' , buf ) -> if drop then flow . linger <- [ ] ; flow . state <- ` Active tls ' ; FLOW . write flow . flow buf >>= fun _ -> drain_handshake flow >|= function | Ok _ -> Ok ( ) | Error _ as e -> e let key_update ? request flow = match flow . state with | ` Eof -> return @@ Error ` Closed | ` Error e -> return @@ Error ( e :> write_error ) | ` Active tls -> match Tls . Engine . key_update ? request tls with | Error _ -> invalid_arg " Key update failed " | Ok ( tls ' , buf ) -> flow . state <- ` Active tls ' ; FLOW . write flow . flow buf >>= check_write flow let close flow = match flow . state with | ` Active tls -> flow . state <- ` Eof ; let ( _ , buf ) = Tls . Engine . send_close_notify tls in FLOW . ( write flow . flow buf >>= fun _ -> close flow . flow ) | _ -> return_unit let client_of_flow conf ? host flow = let conf ' = match host with | None -> conf | Some host -> Tls . Config . peer conf host in let ( tls , init ) = Tls . Engine . client conf ' in let tls_flow = { role = ` Client ; flow = flow ; state = ` Active tls ; linger = [ ] ; } in FLOW . write flow init >>= fun _ -> drain_handshake tls_flow let server_of_flow conf flow = let tls_flow = { role = ` Server ; flow = flow ; state = ` Active ( Tls . Engine . server conf ) ; linger = [ ] ; } in drain_handshake tls_flow let epoch flow = match flow . state with | ` Eof | ` Error _ -> Error ( ) | ` Active tls -> match Tls . Engine . epoch tls with | ` InitialEpoch -> assert false | ` Epoch e -> Ok e end
|
module X509 ( KV : Mirage_kv . RO ) ( C : Mirage_clock . PCLOCK ) = struct let ca_roots_file = Mirage_kv . Key . v " ca - roots . crt " let default_cert = " server " let err_fail pp = function | Ok x -> return x | Error e -> Fmt . kstr fail_with " % a " pp e let pp_msg ppf = function ` Msg m -> Fmt . string ppf m let decode_or_fail f cs = err_fail pp_msg ( f cs ) let read kv name = KV . get kv name >>= err_fail KV . pp_error >|= Cstruct . of_string let read_crl kv = function | None -> Lwt . return None | Some filename -> read kv ( Mirage_kv . Key . v filename ) >>= fun data -> err_fail pp_msg ( X509 . CRL . decode_der data ) >|= fun crl -> Some [ crl ] let authenticator ? allowed_hashes ? crl kv = let time ( ) = Some ( Ptime . v ( C . now_d_ps ( ) ) ) in let now = Ptime . v ( C . now_d_ps ( ) ) in read kv ca_roots_file >>= decode_or_fail X509 . Certificate . decode_pem_multiple >>= fun cas -> let ta = X509 . Validation . valid_cas ~ time : now cas in read_crl kv crl >|= fun crls -> X509 . Authenticator . chain_of_trust ? crls ? allowed_hashes ~ time ta let certificate kv = let read name = read kv ( Mirage_kv . Key . v ( name ^ " . pem " ) ) >>= decode_or_fail X509 . Certificate . decode_pem_multiple >>= fun certs -> read kv ( Mirage_kv . Key . v ( name ^ " . key " ) ) >>= decode_or_fail X509 . Private_key . decode_pem >|= fun pk -> ( certs , pk ) in function | ` Default -> read default_cert | ` Name name -> read name end
|
type tmc_call_information = { loc : scoped_location ; explicit : bool ; }
|
type subterm_information = { tmc_calls : tmc_call_information list ; }
|
type ambiguous_arguments = { explicit : bool ; arguments : subterm_information list ; }
|
type error = | Ambiguous_constructor_arguments of ambiguous_arguments
|
type ' offset destination = { var : Ident . t ; offset : ' offset ; loc : Debuginfo . Scoped_location . t ; }
|
let offset_code ( Offset t ) = t
|
let add_dst_params ( { var ; offset } : Ident . t destination ) params = ( var , Pgenval ) :: ( offset , Pintval ) :: params
|
let add_dst_args ( { var ; offset } : offset destination ) args = Lvar var :: offset_code offset :: args
|
let assign_to_dst { var ; offset ; loc } lam = Lprim ( Psetfield_computed ( Pointer , Heap_initialization ) , [ Lvar var ; offset_code offset ; lam ] , loc )
|
module Constr : sig type t = { tag : int ; flag : Asttypes . mutable_flag ; shape : block_shape ; before : lambda list ; after : lambda list ; loc : Debuginfo . Scoped_location . t ; } val apply : t -> lambda -> lambda val with_placeholder : t -> ( offset destination -> lambda ) -> lambda val delay_impure : block_id : int -> t -> ( t -> lambda ) -> lambda type t = { tag : int ; flag : Asttypes . mutable_flag ; shape : block_shape ; before : lambda list ; after : lambda list ; loc : Debuginfo . Scoped_location . t ; } let apply constr t = let block_args = List . append constr . before @@ t :: constr . after in Lprim ( Pmakeblock ( constr . tag , constr . flag , constr . shape ) , block_args , constr . loc ) let tmc_placeholder = Lconst ( Const_base ( Const_int ( 0xBBBB / 2 ) ) ) let with_placeholder constr ( body : offset destination -> lambda ) = let k_with_placeholder = apply { constr with flag = Mutable } tmc_placeholder in let placeholder_pos = List . length constr . before in let placeholder_pos_lam = Lconst ( Const_base ( Const_int placeholder_pos ) ) in let block_var = Ident . create_local " block " in Llet ( Strict , Pgenval , block_var , k_with_placeholder , body { var = block_var ; offset = Offset placeholder_pos_lam ; loc = constr . loc ; } ) let delay_impure : block_id : int -> t -> ( t -> lambda ) -> lambda = let bind_list ~ block_id ~ arg_offset lambdas k = let can_be_delayed = function | Lvar _ | Lconst _ -> true | _ -> false in let bindings , args = lambdas |> List . mapi ( fun i lam -> if can_be_delayed lam then ( None , lam ) else begin let v = Ident . create_local ( Printf . sprintf " block % d_arg % d " block_id ( arg_offset + i ) ) in ( Some ( v , lam ) , Lvar v ) end ) |> List . split in let body = k args in List . fold_right ( fun binding body -> match binding with | None -> body | Some ( v , lam ) -> Llet ( Strict , Pgenval , v , lam , body ) ) bindings body in fun ~ block_id constr body -> bind_list ~ block_id ~ arg_offset : 0 constr . before @@ fun vbefore -> let arg_offset = List . length constr . before + 1 in bind_list ~ block_id ~ arg_offset constr . after @@ fun vafter -> body { constr with before = vbefore ; after = vafter } end
|
module Dps : sig type ' a dps = tail : bool -> dst : offset destination -> ' a type ' a t val make : lambda dps -> lambda t val run : lambda t -> lambda dps val delay_constructor : Constr . t -> lambda t -> lambda t val lambda : lambda -> lambda t val map : ( ' a -> ' b ) -> ' a t -> ' b t val pair : ' a t -> ' b t -> ( ' a * ' b ) t val unit : unit t type ' a dps = tail : bool -> dst : offset destination -> ' a type ' a t = { code : delayed : Constr . t list -> ' a dps ; delayed_use_count : int ; } let dstx = x ( ) :: Placeholder in dst . i <- dstx ; let dsty = y ( ) :: Placeholder in dstx . 1 <- dsty ; tmc dsty . 1 call ] } Instead of binding the whole newly - created destination , we can simply let - bind the non - placeholder arguments ( in order to preserve execution order ) , and keep track of a list of blocks to be created along with the current destination . Instead of seeing a DPS fragment as writing to a destination , we see it as a term with shape [ dst . i <- C . ] where [ C . ] is a linear context consisting only of constructor applications . { [ let vx = x ( ) in let vy = y ( ) in let dsty = vy :: Placeholder in dst . i <- vx :: dsty ; tmc dsty . 1 call ] } The [ delayed ] argument represents the context [ C ] as a list of reified constructors , to allow both to build the final holey block ( [ vy :: Placeholder ] ) at the recursive call site , and the delayed constructor applications ( [ vx :: dsty ] ) . In practice , it is not desirable to perform this simplification when there are multiple TMC calls ( e . g . in different branches of an [ if ] block ) , because it would cause duplication of the nested constructor applications . The [ delayed_use_count ] field keeps track of this information , it counts the number of syntactic use sites of the delayed constructors , if any , in the generated code . ) * let write_to_dst dst delayed t = assign_to_dst dst @@ List . fold_left ( fun t constr -> Constr . apply constr t ) t delayed let lambda ( v : lambda ) : lambda t = { code = ( fun ~ delayed ~ tail : _ ~ dst -> write_to_dst dst delayed v ) ; delayed_use_count = 1 ; } let unit : unit t = { code = ( fun ~ delayed : _ ~ tail : _ ~ dst : _ -> ( ) ) ; delayed_use_count = 0 ; } let map ( f : ' a -> ' b ) ( d : ' a t ) : ' b t = { code = ( fun ~ delayed ~ tail ~ dst -> f @@ d . code ~ delayed ~ tail ~ dst ) ; delayed_use_count = d . delayed_use_count ; } let pair ( da : ' a t ) ( db : ' b t ) : ( ' a * ' b ) t = { code = ( fun ~ delayed ~ tail ~ dst -> ( da . code ~ delayed ~ tail ~ dst , db . code ~ delayed ~ tail ~ dst ) ) ; delayed_use_count = da . delayed_use_count + db . delayed_use_count ; } let run ( d : ' a t ) : ' a dps = fun ~ tail ~ dst -> d . code ~ tail ~ dst ~ delayed [ ] : let reify_delay ( dps : lambda dps ) : lambda t = { code = ( fun ~ delayed ~ tail ~ dst -> match delayed with | [ ] -> dps ~ tail ~ dst | x :: xs -> Constr . with_placeholder x @@ fun new_dst -> Lsequence ( write_to_dst dst xs ( Lvar new_dst . var ) , dps ~ tail ~ dst : new_dst ) ) ; delayed_use_count = 1 ; } let ensures_affine ( d : lambda t ) : lambda t = if d . delayed_use_count <= 1 then d else reify_delay ( run d ) let make ( dps : ' a dps ) : ' a t = reify_delay dps let delay_constructor constr d = let d = ensures_affine d in { code = ( fun ~ delayed ~ tail ~ dst -> let block_id = List . length delayed in Constr . delay_impure ~ block_id constr @@ fun constr -> d . code ~ tail ~ dst ~ delayed ( : constr :: delayed ) ) ; delayed_use_count = d . delayed_use_count ; } end
|
module Choice = struct type ' a t = { dps : ' a Dps . t ; direct : unit -> ' a ; tmc_calls : tmc_call_information list ; benefits_from_dps : bool ; explicit_tailcall_request : bool ; } let lambda ( v : lambda ) : lambda t = { dps = Dps . lambda v ; direct = ( fun ( ) -> v ) ; tmc_calls = [ ] ; benefits_from_dps = false ; explicit_tailcall_request = false ; } let map f s = { dps = Dps . map f s . dps ; direct = ( fun ( ) -> f ( s . direct ( ) ) ) ; tmc_calls = s . tmc_calls ; benefits_from_dps = s . benefits_from_dps ; explicit_tailcall_request = s . explicit_tailcall_request ; } let direct ( c : ' a t ) : ' a = c . direct ( ) let dps ( c : lambda t ) ~ tail ~ dst = Dps . run c . dps ~ tail ~ dst let pair ( ( c1 , c2 ) : ' a t * ' b t ) : ( ' a * ' b ) t = { dps = Dps . pair c1 . dps c2 . dps ; direct = ( fun ( ) -> ( c1 . direct ( ) , c2 . direct ( ) ) ) ; tmc_calls = c1 . tmc_calls @ c2 . tmc_calls ; benefits_from_dps = c1 . benefits_from_dps || c2 . benefits_from_dps ; explicit_tailcall_request = c1 . explicit_tailcall_request || c2 . explicit_tailcall_request ; } let unit = { dps = Dps . unit ; direct = ( fun ( ) -> ( ) ) ; tmc_calls = [ ] ; benefits_from_dps = false ; explicit_tailcall_request = false ; } module Syntax = struct let ( let ) + a f = map f a let ( and ) + a1 a2 = pair ( a1 , a2 ) end open Syntax let option ( c : ' a t option ) : ' a option t = match c with | None -> let + ( ) = unit in None | Some c -> let + v = c in Some v let rec list ( c : ' a t list ) : ' a list t = match c with | [ ] -> let + ( ) = unit in [ ] | c :: cs -> let + v = c and + vs = list cs in v :: vs type ' a tmc_call_search = | No_tmc_call of ' a list | Nonambiguous of ' a zipper | Ambiguous of { explicit : bool ; subterms : ' a t list ; } and ' a zipper = { rev_before : ' a list ; choice : ' a t ; after : ' a list } let find_nonambiguous_tmc_call choices = let has_tmc_calls c = c . tmc_calls <> [ ] in let is_explicit s = s . explicit_tailcall_request in let nonambiguous ~ only_explicit_calls choices = let rec split rev_before : ' a t list -> ' a zipper = function | [ ] -> assert false | c :: rest -> if has_tmc_calls c && ( not only_explicit_calls || is_explicit c ) then { rev_before ; choice = c ; after = List . map direct rest } else split ( direct c :: rev_before ) rest in split [ ] choices in let tmc_call_subterms = List . filter ( fun c -> has_tmc_calls c ) choices in match tmc_call_subterms with | [ ] -> No_tmc_call ( List . map direct choices ) | [ _one ] -> Nonambiguous ( nonambiguous ~ only_explicit_calls : false choices ) | several_subterms -> let explicit_subterms = List . filter is_explicit several_subterms in begin match explicit_subterms with | [ ] -> Ambiguous { explicit = false ; subterms = several_subterms ; } | [ _one ] -> Nonambiguous ( nonambiguous ~ only_explicit_calls : true choices ) | several_explicit_subterms -> Ambiguous { explicit = true ; subterms = several_explicit_subterms ; } end end
|
type context = { specialized : specialized Ident . Map . t ; } arity : int ; dps_id : Ident . t ; direct_kind : function_kind ; }
|
let llets lk vk bindings body = List . fold_right ( fun ( var , def ) body -> Llet ( lk , vk , var , def , body ) ) bindings body
|
let find_candidate = function | Lfunction lfun when lfun . attr . tmc_candidate -> Some lfun | _ -> None
|
let declare_binding ctx ( var , def ) = match find_candidate def with | None -> ctx | Some lfun -> let arity = List . length lfun . params in let dps_id = Ident . create_local ( Ident . name var ^ " _dps " ) in let direct_kind = lfun . kind in let cand = { arity ; dps_id ; direct_kind ; } in { specialized = Ident . Map . add var cand ctx . specialized }
|
let rec choice ctx t = let rec choice ctx ~ tail t = match t with | ( Lvar _ | Lmutvar _ | Lconst _ | Lfunction _ | Lsend _ | Lassign _ | Lfor _ | Lwhile _ ) -> let t = traverse ctx t in Choice . lambda t | Lprim ( prim , primargs , loc ) -> choice_prim ctx ~ tail prim primargs loc | Lapply apply -> choice_apply ctx ~ tail apply | Lsequence ( l1 , l2 ) -> let l1 = traverse ctx l1 in let + l2 = choice ctx ~ tail l2 in Lsequence ( l1 , l2 ) | Lifthenelse ( l1 , l2 , l3 ) -> let l1 = traverse ctx l1 in let + ( l2 , l3 ) = choice_pair ctx ~ tail ( l2 , l3 ) in Lifthenelse ( l1 , l2 , l3 ) | Lmutlet ( vk , var , def , body ) -> let def = traverse ctx def in let + body = choice ctx ~ tail body in Lmutlet ( vk , var , def , body ) | Llet ( lk , vk , var , def , body ) -> let ctx , bindings = traverse_let ctx var def in let + body = choice ctx ~ tail body in llets lk vk bindings body | Lletrec ( bindings , body ) -> let ctx , bindings = traverse_letrec ctx bindings in let + body = choice ctx ~ tail body in Lletrec ( bindings , body ) | Lswitch ( l1 , sw , loc ) -> let consts_lhs , consts_rhs = List . split sw . sw_consts in let blocks_lhs , blocks_rhs = List . split sw . sw_blocks in let l1 = traverse ctx l1 in let + consts_rhs = choice_list ctx ~ tail consts_rhs and + blocks_rhs = choice_list ctx ~ tail blocks_rhs and + sw_failaction = choice_option ctx ~ tail sw . sw_failaction in let sw_consts = List . combine consts_lhs consts_rhs in let sw_blocks = List . combine blocks_lhs blocks_rhs in let sw = { sw with sw_consts ; sw_blocks ; sw_failaction ; } in Lswitch ( l1 , sw , loc ) | Lstringswitch ( l1 , cases , fail , loc ) -> let cases_lhs , cases_rhs = List . split cases in let l1 = traverse ctx l1 in let + cases_rhs = choice_list ctx ~ tail cases_rhs and + fail = choice_option ctx ~ tail fail in let cases = List . combine cases_lhs cases_rhs in Lstringswitch ( l1 , cases , fail , loc ) | Lstaticraise ( id , ls ) -> let ls = traverse_list ctx ls in Choice . lambda ( Lstaticraise ( id , ls ) ) | Ltrywith ( l1 , id , l2 ) -> let l1 = traverse ctx l1 in let + l2 = choice ctx ~ tail l2 in Ltrywith ( l1 , id , l2 ) | Lstaticcatch ( l1 , ids , l2 ) -> let + l1 = choice ctx ~ tail l1 and + l2 = choice ctx ~ tail l2 in Lstaticcatch ( l1 , ids , l2 ) | Levent ( lam , lev ) -> let + lam = choice ctx ~ tail lam in Levent ( lam , lev ) | Lifused ( x , lam ) -> let + lam = choice ctx ~ tail lam in Lifused ( x , lam ) and choice_apply ctx ~ tail apply = let exception No_tmc in try let explicit_tailcall_request = match apply . ap_tailcall with | Default_tailcall -> false | Tailcall_expectation true -> true | Tailcall_expectation false -> raise No_tmc in match apply . ap_func with | Lvar f -> let specialized = try Ident . Map . find f ctx . specialized with Not_found -> if tail then Location . prerr_warning ( Debuginfo . Scoped_location . to_location apply . ap_loc ) Warnings . Tmc_breaks_tailcall ; raise No_tmc ; in let args = let kind , arity = specialized . direct_kind , specialized . arity in match Lambda . find_exact_application kind ~ arity apply . ap_args with | None -> raise No_tmc | Some args -> args in let tailcall tail = if tail then Tailcall_expectation true else Default_tailcall in { Choice . dps = Dps . make ( fun ~ tail ~ dst -> Lapply { apply with ap_func = Lvar specialized . dps_id ; ap_args = add_dst_args dst args ; ap_tailcall = tailcall tail ; } ) ; direct = ( fun ( ) -> Lapply { apply with ap_tailcall = tailcall tail } ) ; explicit_tailcall_request ; tmc_calls = [ { loc = apply . ap_loc ; explicit = explicit_tailcall_request ; } ] ; benefits_from_dps = true ; } | _nontail -> raise No_tmc with No_tmc -> let apply_no_bailout = let ap_tailcall = match apply . ap_tailcall with | Tailcall_expectation false when tail -> Default_tailcall | other -> other in { apply with ap_tailcall } in { ( Choice . lambda ( Lapply apply ) ) with direct = ( fun ( ) -> Lapply apply_no_bailout ) ; } and choice_makeblock ctx ~ tail : _ ( tag , flag , shape ) blockargs loc = let choices = List . map ( choice ctx ~ tail : false ) blockargs in match Choice . find_nonambiguous_tmc_call choices with | Choice . No_tmc_call args -> Choice . lambda @@ Lprim ( Pmakeblock ( tag , flag , shape ) , args , loc ) | Choice . Ambiguous { explicit ; subterms = ambiguous_subterms } -> let term_choice = let + args = Choice . list choices in Lprim ( Pmakeblock ( tag , flag , shape ) , args , loc ) in { term_choice with Choice . dps = Dps . make ( fun ~ tail : _ ~ dst : _ -> let arguments = let info ( t : lambda Choice . t ) : subterm_information = { tmc_calls = t . tmc_calls ; } in { explicit ; arguments = List . map info ambiguous_subterms ; } in raise ( Error ( Debuginfo . Scoped_location . to_location loc , Ambiguous_constructor_arguments arguments ) ) ) ; } | Choice . Nonambiguous { Choice . rev_before ; choice ; after } -> let constr = Constr . { tag ; flag ; shape ; before = List . rev rev_before ; after ; loc ; } in assert ( choice . tmc_calls <> [ ] ) ; { Choice . direct = ( fun ( ) -> if not choice . benefits_from_dps then Constr . apply constr ( Choice . direct choice ) else Constr . with_placeholder constr @@ fun new_dst -> Lsequence ( Choice . dps choice ~ tail : false ~ dst : new_dst , Lvar new_dst . var ) ) ; benefits_from_dps = false ; dps = Dps . delay_constructor constr choice . dps ; tmc_calls = choice . tmc_calls ; explicit_tailcall_request = choice . explicit_tailcall_request ; } and choice_prim ctx ~ tail prim primargs loc = match prim with | Pmakeblock ( tag , flag , shape ) -> choice_makeblock ctx ~ tail ( tag , flag , shape ) primargs loc | Popaque -> let l1 = match primargs with | [ l1 ] -> l1 | _ -> invalid_arg " choice_prim " in let + l1 = choice ctx ~ tail l1 in Lprim ( Popaque , [ l1 ] , loc ) | ( Psequand | Psequor ) as shortcutop -> let l1 , l2 = match primargs with | [ l1 ; l2 ] -> l1 , l2 | _ -> invalid_arg " choice_prim " in let l1 = traverse ctx l1 in let + l2 = choice ctx ~ tail l2 in Lprim ( shortcutop , [ l1 ; l2 ] , loc ) | Pbytes_to_string | Pbytes_of_string | Pgetglobal _ | Psetglobal _ | Pfield _ | Pfield_computed | Psetfield _ | Psetfield_computed _ | Pfloatfield _ | Psetfloatfield _ | Pccall _ | Praise _ | Pnot | Pnegint | Paddint | Psubint | Pmulint | Pdivint _ | Pmodint _ | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp _ | Poffsetint _ | Poffsetref _ | Pintoffloat | Pfloatofint | Pnegfloat | Pabsfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Pfloatcomp _ | Pstringlength | Pstringrefu | Pstringrefs | Pbyteslength | Pbytesrefu | Pbytessetu | Pbytesrefs | Pbytessets | Parraylength _ | Parrayrefu _ | Parraysetu _ | Parrayrefs _ | Parraysets _ | Pisint | Pisout | Pignore | Pcompare_ints | Pcompare_floats | Pcompare_bints _ | Prunstack | Pperform | Presume | Preperform | Pdls_get | Patomic_exchange | Patomic_cas | Patomic_fetch_add | Patomic_load _ | ( Pmakearray _ | Pduparray _ ) | Pduprecord _ | Pbintofint _ | Pintofbint _ | Pcvtbint _ | Pnegbint _ | Paddbint _ | Psubbint _ | Pmulbint _ | Pdivbint _ | Pmodbint _ | Pandbint _ | Porbint _ | Pxorbint _ | Plslbint _ | Plsrbint _ | Pasrbint _ | Pbintcomp _ | Pbigarrayref _ | Pbigarrayset _ | Pbigarraydim _ | Pstring_load_16 _ | Pstring_load_32 _ | Pstring_load_64 _ | Pbytes_load_16 _ | Pbytes_load_32 _ | Pbytes_load_64 _ | Pbytes_set_16 _ | Pbytes_set_32 _ | Pbytes_set_64 _ | Pbigstring_load_16 _ | Pbigstring_load_32 _ | Pbigstring_load_64 _ | Pbigstring_set_16 _ | Pbigstring_set_32 _ | Pbigstring_set_64 _ | Pctconst _ | Pbswap16 | Pbbswap _ | Pint_as_pointer -> let primargs = traverse_list ctx primargs in Choice . lambda ( Lprim ( prim , primargs , loc ) ) and choice_list ctx ~ tail terms = Choice . list ( List . map ( choice ctx ~ tail ) terms ) and choice_pair ctx ~ tail ( t1 , t2 ) = Choice . pair ( choice ctx ~ tail t1 , choice ctx ~ tail t2 ) and choice_option ctx ~ tail t = Choice . option ( Option . map ( choice ctx ~ tail ) t ) in choice ctx t | Llet ( lk , vk , var , def , body ) -> let ctx , bindings = traverse_let ctx var def in let body = traverse ctx body in llets lk vk bindings body | Lletrec ( bindings , body ) -> let ctx , bindings = traverse_letrec ctx bindings in Lletrec ( bindings , traverse ctx body ) | lam -> shallow_map ( traverse ctx ) lam let inner_ctx = declare_binding outer_ctx ( var , def ) in let bindings = traverse_binding outer_ctx inner_ctx ( var , def ) in inner_ctx , bindings let ctx = List . fold_left declare_binding ctx bindings in let bindings = List . concat_map ( traverse_binding ctx ctx ) bindings in ctx , bindings match find_candidate def with | None -> [ ( var , traverse outer_ctx def ) ] | Some lfun -> let special = Ident . Map . find var inner_ctx . specialized in let fun_choice = choice outer_ctx ~ tail : true lfun . body in if fun_choice . Choice . tmc_calls = [ ] then Location . prerr_warning ( Debuginfo . Scoped_location . to_location lfun . loc ) Warnings . Unused_tmc_attribute ; let direct = Lfunction { lfun with body = Choice . direct fun_choice } in let dps = let dst_param = { var = Ident . create_local " dst " ; offset = Ident . create_local " offset " ; loc = lfun . loc ; } in let dst = { dst_param with offset = Offset ( Lvar dst_param . offset ) } in Lambda . duplicate @@ Lfunction { lfun with kind = Curried ; params = add_dst_params dst_param lfun . params ; body = Choice . dps ~ tail : true ~ dst : dst fun_choice ; } in let dps_var = special . dps_id in [ ( var , direct ) ; ( dps_var , dps ) ] List . map ( traverse ctx ) terms
|
let rewrite t = let ctx = { specialized = Ident . Map . empty } in traverse ctx t
|
let ( ) = Location . register_error_of_exn ( function | Error ( loc , Ambiguous_constructor_arguments { explicit = false ; arguments } ) -> let print_msg ppf = Format . pp_print_text ppf " [ @ tail_mod_cons ] : this constructor application may be \ TMC - transformed in several different ways . Please \ disambiguate by adding an explicit [ @ tailcall ] \ attribute to the call that should be made \ tail - recursive , or a [ @ tailcall false ] attribute on \ calls that should not be transformed . " in let submgs = let sub ( info : tmc_call_information ) = let loc = Debuginfo . Scoped_location . to_location info . loc in Location . msg ~ loc " This call could be annotated . " in arguments |> List . map ( fun t -> t . tmc_calls ) |> List . flatten |> List . map sub in Some ( Location . errorf ~ loc ~ sub : submgs " % t " print_msg ) | Error ( loc , Ambiguous_constructor_arguments { explicit = true ; arguments } ) -> let print_msg ppf = Format . pp_print_text ppf " [ @ tail_mod_cons ] : this constructor application may be \ TMC - transformed in several different ways . Only one of \ the arguments may become a TMC call , but several \ arguments contain calls that are explicitly marked as \ tail - recursive . Please fix the conflict by reviewing \ and fixing the conflicting annotations . " in let submgs = let sub ( info : tmc_call_information ) = let loc = Debuginfo . Scoped_location . to_location info . loc in Location . msg ~ loc " This call is explicitly annotated . " in arguments |> List . map ( fun t -> t . tmc_calls ) |> List . flatten |> List . filter ( fun ( info : tmc_call_information ) -> info . explicit ) |> List . map sub in Some ( Location . errorf ~ loc ~ sub : submgs " % t " print_msg ) | _ -> None )
|
let type_declarations : type_declaration Hts . t = Hts . create 0
|
module Mstr = Map . Make ( String )
|
type namespace = { ns_ts : tysymbol Mstr . t ; ns_ls : lsymbol Mstr . t ; ns_fd : lsymbol Mstr . t ; ns_xs : xsymbol Mstr . t ; ns_ns : namespace Mstr . t ; ns_tns : namespace Mstr . t ; }
|
let empty_ns = { ns_ts = Mstr . empty ; ns_ls = Mstr . empty ; ns_fd = Mstr . empty ; ns_xs = Mstr . empty ; ns_ns = Mstr . empty ; ns_tns = Mstr . empty ; }
|
let add ~ allow_duplicate ~ equal ~ loc ns s x = if allow_duplicate then Mstr . add s x ns else match Mstr . find s ns with | t when not ( equal t x ) -> W . error ~ loc ( W . Name_clash s ) | _ | ( exception Not_found ) -> Mstr . add s x ns
|
let ns_add_ts ~ allow_duplicate ns s ts = let ns_ts = add ~ allow_duplicate ~ equal : ts_equal ~ loc : ts . ts_ident . id_loc ns . ns_ts s ts in { ns with ns_ts }
|
let ns_add_ls ~ allow_duplicate : _ ns s ls = let ns_ls = add ~ allow_duplicate : true ~ equal : ls_equal ~ loc : ls . ls_name . id_loc ns . ns_ls s ls in { ns with ns_ls }
|
let ns_add_fd ~ allow_duplicate : _ ns s fd = let ns_fd = add ~ allow_duplicate : true ~ equal : ls_equal ~ loc : fd . ls_name . id_loc ns . ns_fd s fd in { ns with ns_fd }
|
let ns_add_xs ~ allow_duplicate ns s xs = let ns_xs = add ~ allow_duplicate ~ equal : xs_equal ~ loc : xs . xs_ident . id_loc ns . ns_xs s xs in { ns with ns_xs }
|
let ns_add_ns ~ allow_duplicate : _ ns s new_ns = { ns with ns_ns = Mstr . add s new_ns ns . ns_ns }
|
let ns_add_tns ~ allow_duplicate : _ ns s tns = { ns with ns_tns = Mstr . add s tns ns . ns_tns }
|
let merge_ns from_ns to_ns = let choose_fst _ x _ = Some x in let union m1 m2 = Mstr . union choose_fst m1 m2 in { ns_ts = union from_ns . ns_ts to_ns . ns_ts ; ns_ls = union from_ns . ns_ls to_ns . ns_ls ; ns_fd = union from_ns . ns_fd to_ns . ns_fd ; ns_xs = union from_ns . ns_xs to_ns . ns_xs ; ns_ns = union from_ns . ns_ns to_ns . ns_ns ; ns_tns = union from_ns . ns_tns to_ns . ns_tns ; }
|
let rec ns_find get_map ns = function | [ ] -> assert false | [ x ] -> Mstr . find x ( get_map ns ) | x :: xs -> ns_find get_map ( Mstr . find x ns . ns_ns ) xs
|
let ns_find_ts ns s = ns_find ( fun ns -> ns . ns_ts ) ns s
|
let ns_find_ls ns s = ns_find ( fun ns -> ns . ns_ls ) ns s
|
let ns_find_fd ns s = ns_find ( fun ns -> ns . ns_fd ) ns s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.