text
stringlengths
12
786k
let get_cached var f = match ! var with | Some x -> x | None -> let x = f ( ) in var := Some x ; x
let visible_modules ( ) = get_cached visible_modules ( fun ( ) -> List . fold_left ( fun acc dir -> try Array . fold_left ( fun acc fname -> if Filename . check_suffix fname " . cmi " then String_set . add ( String . capitalize_ascii ( Filename . chop_suffix fname " . cmi " ) ) acc else acc ) acc ( Sys . readdir ( if dir = " " then Filename . current_dir_name else dir ) ) with Sys_error _ -> acc ) String_set . empty @@ Load_path . get_paths ( ) # else String_set . empty ! Config . load_path # endif )
let field_name { ld_id = id } = Ident . name id
let constructor_name { cd_id = id } = Ident . name id
let add_fields_of_type decl acc = match decl . type_kind with | Type_variant ( constructors , _ ) -> # else | Type_variant constructors -> # endif acc | Type_record ( fields , _ ) -> List . fold_left ( fun acc field -> add ( field_name field ) acc ) acc fields | Type_abstract -> acc | Type_open -> acc
let add_names_of_type decl acc = match decl . type_kind with | Type_variant ( constructors , _ ) -> # else | Type_variant constructors -> # endif List . fold_left ( fun acc cstr -> add ( constructor_name cstr ) acc ) acc constructors | Type_record ( fields , _ ) -> List . fold_left ( fun acc field -> add ( field_name field ) acc ) acc fields | Type_abstract -> acc | Type_open -> acc
let path_of_mty_alias = function | Mty_alias path -> path | _ -> assert false
let path_of_mty_alias = function | Mty_alias ( _ , path ) -> path | _ -> assert false # else
let path_of_mty_alias = function | Mty_alias path -> path | _ -> assert false # endif
let rec names_of_module_type = function | Mty_signature decls -> List . fold_left ( fun acc decl -> match decl with | Sig_value ( id , _ , _ ) | Sig_typext ( id , _ , _ , _ ) | Sig_module ( id , _ , _ , _ , _ ) | Sig_modtype ( id , _ , _ ) | Sig_class ( id , _ , _ , _ ) | Sig_class_type ( id , _ , _ , _ ) -> # else | Sig_value ( id , _ ) | Sig_typext ( id , _ , _ ) | Sig_module ( id , _ , _ ) | Sig_modtype ( id , _ ) | Sig_class ( id , _ , _ ) | Sig_class_type ( id , _ , _ ) -> # endif add ( Ident . name id ) acc | Sig_type ( id , decl , _ , _ ) -> # else | Sig_type ( id , decl , _ ) -> # endif add_names_of_type decl ( add ( Ident . name id ) acc ) ) String_set . empty decls | Mty_ident path -> begin match lookup_env Env . find_modtype path ! Toploop . toplevel_env with | Some { mtd_type = None } -> String_set . empty | Some { mtd_type = Some module_type } -> names_of_module_type module_type | None -> String_set . empty end | Mty_alias _ as mty_alias -> begin let path = path_of_mty_alias mty_alias in match lookup_env Env . find_module path ! Toploop . toplevel_env with | None -> String_set . empty | Some { md_type = module_type } -> names_of_module_type module_type end | _ -> String_set . empty
let rec fields_of_module_type = function | Mty_signature decls -> List . fold_left ( fun acc decl -> match decl with | Sig_value _ | Sig_typext _ | Sig_module _ | Sig_modtype _ | Sig_class _ | Sig_class_type _ -> acc | Sig_type ( _ , decl , _ , _ ) -> # else | Sig_type ( _ , decl , _ ) -> # endif add_fields_of_type decl acc ) String_set . empty decls | Mty_ident path -> begin match lookup_env Env . find_modtype path ! Toploop . toplevel_env with | Some { mtd_type = None } -> String_set . empty | Some { mtd_type = Some module_type } -> fields_of_module_type module_type | None -> String_set . empty end | Mty_alias _ as mty_alias -> begin let path = path_of_mty_alias mty_alias in match lookup_env Env . find_module path ! Toploop . toplevel_env with | None -> String_set . empty | Some { md_type = module_type } -> fields_of_module_type module_type end | _ -> String_set . empty
let lookup_module id env = let path , decl = Env . find_module_by_name id env in ( path , decl . md_type ) # else let path = Env . lookup_module id env ~ load : true in ( path , ( Env . find_module path env ) . md_type ) # endif
let find_module path env = ( Env . find_module path env ) . md_type
let names_of_module longident = try Longident_map . find longident ! local_names_by_longident with Not_found -> match lookup_env lookup_module longident ! Toploop . toplevel_env with | Some ( path , module_type ) -> let names = names_of_module_type module_type in local_names_by_path := Path_map . add path names ! local_names_by_path ; local_names_by_longident := Longident_map . add longident names ! local_names_by_longident ; names | None -> local_names_by_longident := Longident_map . add longident String_set . empty ! local_names_by_longident ; String_set . empty
let fields_of_module longident = try Longident_map . find longident ! local_fields_by_longident with Not_found -> match lookup_env lookup_module longident ! Toploop . toplevel_env with | Some ( path , module_type ) -> let fields = fields_of_module_type module_type in local_fields_by_path := Path_map . add path fields ! local_fields_by_path ; local_fields_by_longident := Longident_map . add longident fields ! local_fields_by_longident ; fields | None -> local_fields_by_longident := Longident_map . add longident String_set . empty ! local_fields_by_longident ; String_set . empty
let list_global_names ( ) = let rec loop acc = function | Env . Env_empty -> acc | Env . Env_value_unbound _ -> acc | Env . Env_module_unbound _ -> acc # endif | Env . Env_value ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_type ( summary , id , decl ) -> loop ( add_names_of_type decl ( add ( Ident . name id ) acc ) ) summary | Env . Env_extension ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_module ( summary , id , _ , _ ) -> # else | Env . Env_module ( summary , id , _ ) -> # endif loop ( add ( Ident . name id ) acc ) summary | Env . Env_modtype ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_class ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_cltype ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_functor_arg ( summary , id ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_persistent ( summary , id ) -> loop ( add ( Ident . name id ) acc ) summary # endif | Env . Env_constraints ( summary , _ ) -> loop acc summary # endif | Env . Env_copy_types summary -> loop acc summary | Env . Env_copy_types ( summary , _ ) -> loop acc summary # endif | Env . Env_open ( summary , path ) -> | Env . Env_open ( summary , _ , path ) -> # else | Env . Env_open ( summary , path ) -> # endif match try Some ( Path_map . find path ! local_names_by_path ) with Not_found -> None with | Some names -> loop ( String_set . union acc names ) summary | None -> match lookup_env find_module path ! Toploop . toplevel_env with | Some module_type -> let names = names_of_module_type module_type in local_names_by_path := Path_map . add path names ! local_names_by_path ; loop ( String_set . union acc names ) summary | None -> local_names_by_path := Path_map . add path String_set . empty ! local_names_by_path ; loop acc summary in let acc = loop String_set . empty ( Env . summary ! Toploop . toplevel_env ) in String_set . union acc ( visible_modules ( ) )
let global_names ( ) = get_cached global_names list_global_names
let replace x y set = if String_set . mem x set then String_set . add y ( String_set . remove x set ) else set
let list_global_fields ( ) = let rec loop acc = function | Env . Env_empty -> acc | Env . Env_value_unbound _ -> acc | Env . Env_module_unbound _ -> acc # endif | Env . Env_value ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_type ( summary , id , decl ) -> loop ( add_fields_of_type decl ( add ( Ident . name id ) acc ) ) summary | Env . Env_extension ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_module ( summary , id , _ , _ ) -> # else | Env . Env_module ( summary , id , _ ) -> # endif loop ( add ( Ident . name id ) acc ) summary | Env . Env_functor_arg ( summary , id ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_modtype ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_class ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_cltype ( summary , id , _ ) -> loop ( add ( Ident . name id ) acc ) summary | Env . Env_persistent ( summary , id ) -> loop ( add ( Ident . name id ) acc ) summary # endif | Env . Env_constraints ( summary , _ ) -> loop acc summary # endif | Env . Env_copy_types summary -> loop acc summary | Env . Env_copy_types ( summary , _ ) -> loop acc summary # endif # if OCAML_VERSION >= ( 4 , 08 , 0 ) | Env . Env_open ( summary , path ) -> # else | Env . Env_open ( summary , _ , path ) -> # endif # else | Env . Env_open ( summary , path ) -> # endif match try Some ( Path_map . find path ! local_fields_by_path ) with Not_found -> None with | Some fields -> loop ( String_set . union acc fields ) summary | None -> match lookup_env find_module path ! Toploop . toplevel_env with | Some module_type -> let fields = fields_of_module_type module_type in local_fields_by_path := Path_map . add path fields ! local_fields_by_path ; loop ( String_set . union acc fields ) summary | None -> local_fields_by_path := Path_map . add path String_set . empty ! local_fields_by_path ; loop acc summary in let acc = loop String_set . empty ( Env . summary ! Toploop . toplevel_env ) in String_set . union acc ( visible_modules ( ) )
let global_fields ( ) = get_cached global_fields list_global_fields
let rec find_method meth type_expr = match get_desc type_expr with | Tlink type_expr -> find_method meth type_expr | Tobject ( type_expr , _ ) -> find_method meth type_expr | Tfield ( name , _ , type_expr , rest ) -> if name = meth then Some type_expr else find_method meth rest | Tpoly ( type_expr , _ ) -> find_method meth type_expr | Tconstr ( path , _ , _ ) -> begin match lookup_env Env . find_type path ! Toploop . toplevel_env with | None | Some { type_manifest = None } -> None | Some { type_manifest = Some type_expr } -> find_method meth type_expr end | _ -> None
let rec methods_of_type acc type_expr = match get_desc type_expr with | Tlink type_expr -> methods_of_type acc type_expr | Tobject ( type_expr , _ ) -> methods_of_type acc type_expr | Tfield ( name , _ , _ , rest ) -> methods_of_type ( add name acc ) rest | Tpoly ( type_expr , _ ) -> methods_of_type acc type_expr | Tconstr ( path , _ , _ ) -> begin match lookup_env Env . find_type path ! Toploop . toplevel_env with | None | Some { type_manifest = None } -> acc | Some { type_manifest = Some type_expr } -> methods_of_type acc type_expr end | _ -> acc
let rec find_object meths type_expr = match meths with | [ ] -> Some type_expr | meth :: meths -> match find_method meth type_expr with | Some type_expr -> find_object meths type_expr | None -> None
let methods_of_object longident meths = let lookup_value = Env . find_value_by_name # else Env . lookup_value # endif in match lookup_env lookup_value longident ! Toploop . toplevel_env with | None -> [ ] | Some ( path , { val_type = type_expr } ) -> match find_object meths type_expr with | None -> [ ] | Some type_expr -> String_set . elements ( methods_of_type String_set . empty type_expr )
let rec labels_of_type acc type_expr = match get_desc type_expr with | Tlink te -> labels_of_type acc te | Tpoly ( te , _ ) -> labels_of_type acc te | Tarrow ( label , _ , te , _ ) -> if label = " " then labels_of_type acc te else if label . [ 0 ] = ' ' ? then labels_of_type ( String_map . add ( String . sub label 1 ( String . length label - 1 ) ) Optional acc ) te else labels_of_type ( String_map . add label Required acc ) te # else ( match label with | Nolabel -> labels_of_type acc te | Optional label -> labels_of_type ( String_map . add label Optional acc ) te | Labelled label -> labels_of_type ( String_map . add label Required acc ) te ) # endif | Tconstr ( path , _ , _ ) -> begin match lookup_env Env . find_type path ! Toploop . toplevel_env with | None | Some { type_manifest = None } -> String_map . bindings acc | Some { type_manifest = Some type_expr } -> labels_of_type acc type_expr end | _ -> String_map . bindings acc
let labels_of_function longident meths = let lookup_value = Env . find_value_by_name # else Env . lookup_value # endif in match lookup_env lookup_value longident ! Toploop . toplevel_env with | None -> [ ] | Some ( path , { val_type = type_expr } ) -> match find_object meths type_expr with | None -> [ ] | Some type_expr -> labels_of_type String_map . empty type_expr
let labels_of_newclass longident = let lookup_class = Env . find_class_by_name # else Env . lookup_class # endif in match lookup_env lookup_class longident ! Toploop . toplevel_env with | None -> [ ] | Some ( path , { cty_new = None } ) -> [ ] | Some ( path , { cty_new = Some type_expr } ) -> labels_of_type String_map . empty type_expr
let filter tokens = let rec aux acc = function | [ ] -> acc | [ ( ( Blanks | Comment ( _ , true ) ) , loc ) ] -> ( Blanks , loc ) :: acc | ( ( Blanks | Comment ( _ , true ) ) , _ ) :: rest -> aux acc rest | x :: rest -> aux ( x :: acc ) rest in List . rev ( aux [ ] tokens )
let rec rev_filter acc tokens = match tokens with | [ ] -> acc | [ ( ( Blanks | Comment ( _ , true ) ) , loc ) ] -> ( Blanks , loc ) :: acc | ( ( Blanks | Comment ( _ , true ) ) , _ ) :: rest -> rev_filter acc rest | x :: rest -> rev_filter ( x :: acc ) rest
let rec find_context tokens = function | [ ] -> Some ( rev_filter [ ] tokens ) | [ ( Quotation ( items , false ) , _ ) ] -> find_context_in_quotation items | _ :: rest -> find_context tokens rest | [ ] -> None | [ ( Quot_anti { a_closing = None ; a_contents = tokens } , _ ) ] -> find_context tokens tokens | _ :: rest -> find_context_in_quotation rest
let longident_parse str = let lexbuf = Lexing . from_string str in Parse . longident lexbuf # endif
let complete ~ phrase_terminator ~ input = let true_name , false_name = ( " true " , " false " ) in let tokens = UTop_lexer . lex_string input in let tokens = filter tokens in match tokens with | [ ( Symbol " " , # { idx2 = stop } ) ] | [ ( Symbol " " , # _ ) ; ( Blanks , { idx2 = stop } ) ] -> ( stop , list_directives phrase_terminator ) | [ ( Symbol " " , # _ ) ; ( ( Lident src | Uident src ) , { idx1 = start } ) ] -> ( start , lookup_assoc src ( list_directives phrase_terminator ) ) | [ ( Symbol " " , # _ ) ; ( ( Lident _ | Uident _ ) , _ ) ; ( String ( _ , true ) , { idx2 = stop } ) ] | [ ( Symbol " " , # _ ) ; ( ( Lident _ | Uident _ ) , _ ) ; ( String ( _ , true ) , _ ) ; ( Blanks , { idx2 = stop } ) ] -> ( stop , [ ( phrase_terminator , " " ) ] ) | [ ( Symbol " " , # _ ) ; ( ( Lident _ | Uident _ ) , _ ) ; ( String ( _ , true ) , _ ) ; ( Symbol sym , { idx1 = start } ) ] -> if Zed_utf8 . starts_with phrase_terminator sym then ( start , [ ( phrase_terminator , " " ) ] ) else ( 0 , [ ] ) | [ ( Symbol " " , # _ ) ; ( Lident " require " , _ ) ; ( String ( tlen , false ) , loc ) ] -> let pkg = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in let pkgs = lookup pkg ( Fl_package_base . list_packages ( ) ) in ( loc . idx1 + 1 , List . map ( fun pkg -> ( pkg , " " " \ ^ phrase_terminator ) ) ( List . sort compare pkgs ) ) | [ ( Symbol " " , # _ ) ; ( Lident " typeof " , _ ) ; ( String ( tlen , false ) , loc ) ] -> let prefix = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in begin match longident_parse prefix with | Longident . Ldot ( lident , last_prefix ) -> let set = names_of_module lident in let compls = lookup last_prefix ( String_set . elements set ) in let start = loc . idx1 + 1 + ( String . length prefix - String . length last_prefix ) in ( start , List . map ( fun w -> ( w , " " ) ) compls ) | _ -> let set = global_names ( ) in let compls = lookup prefix ( String_set . elements set ) in ( loc . idx1 + 1 , List . map ( fun w -> ( w , " " ) ) compls ) end | [ ( Symbol " " , # _ ) ; ( Lident ( " load " | " load_rec " ) , _ ) ; ( String ( tlen , false ) , loc ) ] -> let file = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in let filter name = Filename . check_suffix name " . cma " || Filename . check_suffix name " . cmo " in let map = if Filename . is_relative file then let dir = Filename . dirname file in List . fold_left ( fun acc d -> add_files filter acc ( Filename . concat d dir ) ) String_map . empty ( Filename . current_dir_name :: ( Load_path . get_paths ( ) ) # else ! Config . load_path # endif ) else add_files filter String_map . empty ( Filename . dirname file ) in let list = String_map . bindings map in let name = basename file in let result = lookup_assoc name list in ( loc . idx2 - Zed_utf8 . length name , List . map ( function ( w , Directory ) -> ( w , " " ) | ( w , File ) -> ( w , " " " \ ^ phrase_terminator ) ) result ) | [ ( Symbol " " , # _ ) ; ( Lident ( " ppx " ) , _ ) ; ( String ( tlen , false ) , loc ) ] -> let file = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in let filter ~ dir_ok name = try Unix . access name [ Unix . X_OK ] ; let kind = ( Unix . stat name ) . Unix . st_kind in let basename = Filename . basename name in ( kind = Unix . S_REG && String . length basename >= 4 && String . sub basename 0 4 = " ppx_ " ) || ( dir_ok && kind = Unix . S_DIR ) with Unix . Unix_error _ -> false in let map = if Filename . dirname file = " . " && not ( Filename . is_implicit file ) then let dir = Filename . dirname file in add_files ( filter ~ dir_ok : true ) String_map . empty dir else List . fold_left ( fun acc dir -> add_files ( fun name -> filter ~ dir_ok : false ( Filename . concat dir name ) ) acc dir ) String_map . empty ( path ( ) ) in let list = String_map . bindings map in let name = basename file in let result = lookup_assoc name list in ( loc . idx2 - Zed_utf8 . length name , List . map ( function ( w , Directory ) -> ( w , " " ) | ( w , File ) -> ( w , " " " \ ^ phrase_terminator ) ) result ) | [ ( Symbol " " , # _ ) ; ( Lident " use " , _ ) ; ( String ( tlen , false ) , loc ) ] | [ ( Symbol " " , # _ ) ; ( Lident " mod_use " , _ ) ; ( String ( tlen , false ) , loc ) ] -> let file = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in let filter name = match try Some ( String . rindex name ' . ' ) with Not_found -> None with | None -> true | Some idx -> let ext = String . sub name ( idx + 1 ) ( String . length name - ( idx + 1 ) ) in ext = " ml " in let map = if Filename . is_relative file then let dir = Filename . dirname file in List . fold_left ( fun acc d -> add_files filter acc ( Filename . concat d dir ) ) String_map . empty ( Filename . current_dir_name :: ( Load_path . get_paths ( ) ) # else ! Config . load_path # endif ) else add_files filter String_map . empty ( Filename . dirname file ) in let list = String_map . bindings map in let name = basename file in let result = lookup_assoc name list in ( loc . idx2 - Zed_utf8 . length name , List . map ( function ( w , Directory ) -> ( w , " " ) | ( w , File ) -> ( w , " " " \ ^ phrase_terminator ) ) result ) | [ ( Symbol " " , # _ ) ; ( Lident ( " cd " | " directory " ) , _ ) ; ( String ( tlen , false ) , loc ) ] -> let file = String . sub input ( loc . ofs1 + tlen ) ( String . length input - loc . ofs1 - tlen ) in let list = list_directories ( Filename . dirname file ) in let name = basename file in let result = lookup name list in ( loc . idx2 - Zed_utf8 . length name , List . map ( function dir -> ( dir , " " ) ) result ) | [ ( Symbol " " , # _ ) ; ( ( Lident dir | Uident dir ) , _ ) ; ( Blanks , { idx2 = stop } ) ] -> ( stop , match toploop_get_directive dir with | Some ( Toploop . Directive_none _ ) -> [ ( phrase_terminator , " " ) ] | Some ( Toploop . Directive_string _ ) -> [ ( " " " , \ " " ) ] | Some ( Toploop . Directive_bool _ ) -> [ ( true_name , phrase_terminator ) ; ( false_name , phrase_terminator ) ] | Some ( Toploop . Directive_int _ ) -> [ ] | Some ( Toploop . Directive_ident _ ) -> List . map ( fun w -> ( w , " " ) ) ( String_set . elements ( global_names ( ) ) ) | None -> [ ] ) | ( Symbol " " , # _ ) :: ( ( Lident dir | Uident dir ) , _ ) :: tokens -> begin match toploop_get_directive dir with | Some ( Toploop . Directive_none _ ) -> ( 0 , [ ] ) | Some ( Toploop . Directive_string _ ) -> ( 0 , [ ] ) | Some ( Toploop . Directive_bool _ ) -> begin match tokens with | [ ( Lident id , { idx1 = start } ) ] -> ( start , lookup_assoc id [ ( true_name , phrase_terminator ) ; ( false_name , phrase_terminator ) ] ) | _ -> ( 0 , [ ] ) end | Some ( Toploop . Directive_int _ ) -> ( 0 , [ ] ) | Some ( Toploop . Directive_ident _ ) -> begin match parse_longident ( List . rev tokens ) with | Some ( Value , None , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( global_names ( ) ) ) ) ) | Some ( Value , Some longident , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( names_of_module longident ) ) ) ) | _ -> ( 0 , [ ] ) end | None -> ( 0 , [ ] ) end | _ -> match find_context tokens tokens with | None -> ( 0 , [ ] ) | Some [ ] -> ( 0 , List . map ( fun w -> ( w , " " ) ) ( String_set . elements ( String_set . union ! UTop . keywords ( global_names ( ) ) ) ) ) | Some tokens -> match parse_method tokens with | Some ( longident , meths , start , meth ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup meth ( methods_of_object longident meths ) ) ) | None -> match parse_label tokens with | Some ( Fun , longident , meths , Optional , start , label ) -> ( start , List . map ( fun ( w , kind ) -> ( w , " " ) ) : ( lookup_assoc label ( List . filter ( function ( w , Optional ) -> true | ( w , Required ) -> false ) ( labels_of_function longident meths ) ) ) ) | Some ( Fun , longident , meths , Required , start , label ) -> ( start , List . map ( fun ( w , kind ) -> ( w , " " ) ) : ( lookup_assoc label ( labels_of_function longident meths ) ) ) | Some ( New , longident , meths , Optional , start , label ) -> ( start , List . map ( fun ( w , kind ) -> ( w , " " ) ) : ( lookup_assoc label ( List . filter ( function ( w , Optional ) -> true | ( w , Required ) -> false ) ( labels_of_newclass longident ) ) ) ) | Some ( New , longident , meths , Required , start , label ) -> ( start , List . map ( fun ( w , kind ) -> ( w , " " ) ) : ( lookup_assoc label ( labels_of_newclass longident ) ) ) | None -> match parse_longident tokens with | None -> ( 0 , [ ] ) | Some ( Value , None , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( String_set . union ! UTop . keywords ( global_names ( ) ) ) ) ) ) | Some ( Value , Some longident , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( names_of_module longident ) ) ) ) | Some ( Field , None , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( global_fields ( ) ) ) ) ) | Some ( Field , Some longident , start , id ) -> ( start , List . map ( fun w -> ( w , " " ) ) ( lookup id ( String_set . elements ( fields_of_module longident ) ) ) )
let complete ~ phrase_terminator ~ input = try ( complete ~ phrase_terminator ~ input : int * ( string * string ) list ) with Cmi_format . Error _ -> ( 0 , [ ] )
type entry = | Input of string | Output of string | Error of string | Warnings of string | Bad_input of string
let create ( ) : t = ref [ ]
let contents ( t : t ) = ! t
let strip_colors s = let len = String . length s in let find_escape offset = try let i = String . index_from s offset ' \ 027 ' in if i = len - 1 || s . [ i + 1 ] <> ' [ ' then None else Some i with | Not_found -> None in let find_color_escapes offset = let rec aux acc offset = match find_escape offset with | None -> ( offset , len ) :: acc | Some esc_offset -> try let i = String . index_from s esc_offset ' m ' in aux ( ( offset , esc_offset ) :: acc ) ( i + 1 ) with | Not_found -> ( offset , len ) :: acc in aux [ ] offset in find_color_escapes 0 |> List . rev_map ( fun ( i , j ) -> String . sub s i ( j - i ) ) |> String . concat " "
let add history v = history := v :: ! history
let add_input history input = add history @@ Input ( String . trim input )
let add_output history output = let output = String . trim output in if output <> " " then add history @@ Output output
let add_error history error = add history @@ Error ( strip_colors @@ String . trim error )
let add_bad_input history input = add history @@ Bad_input ( String . trim input )
let add_warnings history warnings = let warnings = String . trim warnings in if warnings <> " " then add history @@ Warnings warnings
let get_desc x = Types . get_desc x # else x . Types . desc # endif
let toploop_use_silently fmt name = Toploop . use_silently fmt ( File name ) # else Toploop . use_silently fmt name # endif
let return , ( ) >>= = Lwt . return , Lwt . ( ) >>=
let save_history ( ) = match ! UTop . history_file_name with | None -> return ( ) | Some fn -> Lwt . catch ( fun ( ) -> LTerm_history . save UTop . history ? max_size :! UTop . history_file_max_size ? max_entries :! UTop . history_file_max_entries fn ) ( function | Unix . Unix_error ( error , func , arg ) -> Lwt_log . error_f " cannot save history to % S : % s : % s " fn func ( Unix . error_message error ) | exn -> Lwt . fail exn )
let init_history ( ) = Lwt_main . at_exit save_history ; match ! UTop . history_file_name with | None -> return ( ) | Some fn -> Lwt . catch ( fun ( ) -> LTerm_history . load UTop . history fn ) ( function | Unix . Unix_error ( error , func , arg ) -> Lwt_log . error_f " cannot load history from % S : % s : % s " fn func ( Unix . error_message error ) | exn -> Lwt . fail exn )
let index_of_offset src ofs = let rec aux idx ofs ' = if ofs ' = ofs then idx else if ofs ' > ofs then idx - 1 else if ofs ' = String . length src then - 1 else aux ( idx + 1 ) ( Zed_utf8 . unsafe_next src ofs ' ) in aux 0 0
let convert_loc str ( a , b ) = ( index_of_offset str a , index_of_offset str b )
let convert_locs str locs = List . map ( fun ( a , b ) -> convert_loc str ( a , b ) ) locs
let get_line src line = let rec aux line ' ofs skipped = if ofs >= String . length src then ( " " , 0 ) else if line ' = line then ( String . sub src ofs ( String . length src - ofs ) , skipped ) else let ch , next_ofs = Zed_utf8 . unsafe_extract_next src ofs in if Zed_utf8 . escaped_char ch = " \\ n " then aux ( line ' + 1 ) next_ofs ( skipped + 1 ) else aux line ' next_ofs ( skipped + 1 ) in aux 1 0 0
let convert_one_line str line ofs = let selected , skipped = get_line str line in index_of_offset selected ofs + skipped
let convert_line str ( start_ofs , end_ofs ) lines = ( convert_one_line str lines . start start_ofs , convert_one_line str lines . stop end_ofs )
let convert_loc_line input locs lines = List . map2 ( fun loc line -> match line with | None -> convert_loc input loc | Some line -> convert_line input loc line ) locs lines
let ast_impl_kind = Pparse . Structure # else
let ast_impl_kind = Config . ast_impl_magic_number # endif
let preprocess input = match input with | Parsetree . Ptop_def pstr -> Parsetree . Ptop_def ( Pparse . apply_rewriters ~ tool_name " : ocaml " ast_impl_kind pstr ) | _ -> input
let parse_input_multi input = let buf = Buffer . create 32 in let result = UTop . collect_formatters buf [ Format . err_formatter ] ( fun ( ) -> match ! UTop . parse_use_file input false with | UTop . Error ( locs , msg ) -> UTop . Error ( convert_locs input locs , " Error : " ^ msg ^ " \ n " ) | UTop . Value phrases -> try UTop . Value ( List . map preprocess phrases ) with Pparse . Error error -> Pparse . report_error Format . str_formatter error ; UTop . Error ( [ ] , " Error : " ^ Format . flush_str_formatter ( ) ^ " \ n " ) ) in ( result , Buffer . contents buf )
let parse_and_check input eos_is_error = let buf = Buffer . create 32 in let result = UTop . collect_formatters buf [ Format . err_formatter ] ( fun ( ) -> match ! UTop . parse_toplevel_phrase input eos_is_error with | UTop . Error ( locs , msg ) -> UTop . Error ( convert_locs input locs , " Error : " ^ msg ^ " \ n " ) | UTop . Value phrase -> try let phrase = preprocess phrase in match UTop . check_phrase phrase with | None -> UTop . Value phrase | Some ( locs , msg , lines ) -> UTop . Error ( convert_loc_line input locs lines , msg ) with Pparse . Error error -> Pparse . report_error Format . str_formatter error ; UTop . Error ( [ ] , " Error : " ^ Format . flush_str_formatter ( ) ^ " \ n " ) ) in ( result , Buffer . contents buf )
let add_terminator s = let terminator = UTop . get_phrase_terminator ( ) |> Zed_string . unsafe_of_utf8 in if Zed_string . ends_with s ~ suffix : terminator then s else Zed_string . append s terminator
let is_accept : LTerm_read_line . action -> bool = function | Accept -> true | action -> action == UTop . end_and_accept_current_phrase inherit [ Parsetree . toplevel_phrase UTop . result * string ] LTerm_read_line . engine ~ history ( : LTerm_history . contents UTop . history ) ( ) as super inherit [ Parsetree . toplevel_phrase UTop . result * string ] LTerm_read_line . term term as super_term method create_temporary_file_for_external_editor = Filename . temp_file " utop " " . ml " method external_editor = UTop . get_external_editor ( ) val mutable return_value = None method eval = match return_value with | Some x -> x | None -> assert false method ! send_action action = let action : LTerm_read_line . action = if is_accept action && S . value self # mode <> LTerm_read_line . Edition then Accept else action in super # send_action action method ! exec ( ? keys [ ] ) = = function | action :: actions when S . value self # mode = LTerm_read_line . Edition && is_accept action -> begin Zed_macro . add self # macro action ; let input = Zed_rope . to_string ( Zed_edit . text self # edit ) in let input = if action == UTop . end_and_accept_current_phrase then add_terminator input else input in let input_utf8 = Zed_string . to_utf8 input in Location . reset ( ) ; let eos_is_error = not ! UTop . smart_accept in try let result = parse_and_check input_utf8 eos_is_error in return_value <- Some result ; LTerm_history . add UTop . history input ; let out , warnings = result in begin match out with | UTop . Value _ -> UTop_history . add_input UTop . stashable_session_history input_utf8 ; UTop_history . add_warnings UTop . stashable_session_history warnings ; | ( UTop . Error ( _ , msg ) ) -> UTop_history . add_bad_input UTop . stashable_session_history input_utf8 ; UTop_history . add_warnings UTop . stashable_session_history warnings ; UTop_history . add_error UTop . stashable_session_history msg ; end ; return ( LTerm_read_line . Result result ) with UTop . Need_more -> self # insert ( UChar . of_char ' \ n ' ) ; self # exec ~ keys actions end | actions -> super_term # exec actions method ! stylise last = let styled , position = super # stylise last in let stylise loc token_style = for i = loc . idx1 to loc . idx2 - 1 do let ch , style = styled . ( i ) in styled . ( i ) <- ( ch , LTerm_style . merge token_style style ) done in UTop_styles . stylise stylise ( UTop_lexer . lex_string ( Zed_string . to_utf8 ( LTerm_text . to_string styled ) ) ) ; if not last then LTerm_text . stylise_parenthesis styled position styles . style_paren else begin match return_value with | Some ( UTop . Error ( locs , _ ) , _ ) -> List . iter ( fun ( start , stop ) -> for i = max 0 start to min ( Array . length styled ) stop - 1 do let ch , style = styled . ( i ) in styled . ( i ) <- ( ch , { style with LTerm_style . underline = Some true } ) done ) locs | _ -> ( ) end ; ( styled , position ) method ! completion = let pos , words = UTop_complete . complete ~ phrase_terminator ( : UTop . get_phrase_terminator ( ) ) ~ input ( : Zed_string . to_utf8 ( Zed_rope . to_string self # input_prev ) ) in let words = words |> List . map ( fun ( k , v ) -> ( Zed_string . unsafe_of_utf8 k , Zed_string . unsafe_of_utf8 v ) ) in self # set_completion pos words method ! show_box = S . value self # mode <> LTerm_read_line . Edition || UTop . get_show_box ( ) initializer UTop_private . set_size self # size ; UTop_private . set_key_sequence self # key_sequence ; self # set_prompt ! UTop . prompt end
let fix_string str = let len = String . length str in let ofs , _ , _ = Zed_utf8 . next_error str 0 in if ofs = len then str else begin let buf = Buffer . create ( len + 128 ) in if ofs > 0 then Buffer . add_substring buf str 0 ofs ; let rec loop ofs = Zed_utf8 . add buf ( UChar . of_char str . [ ofs ] ) ; let ofs1 = ofs + 1 in let ofs2 , _ , _ = Zed_utf8 . next_error str ofs1 in if ofs1 < ofs2 then Buffer . add_substring buf str ofs1 ( ofs2 - ofs1 ) ; if ofs2 < len then loop ofs2 else Buffer . contents buf in loop ofs end
let render_out_phrase term string = if String . length string >= 100 * 1024 then LTerm . fprint term string else begin let string = fix_string string in let styled = LTerm_text . of_utf8 string in let stylise loc token_style = for i = loc . idx1 to loc . idx2 - 1 do let ch , style = styled . ( i ) in styled . ( i ) <- ( ch , LTerm_style . merge token_style style ) done in UTop_styles . stylise stylise ( UTop_lexer . lex_string string ) ; LTerm . fprints term styled end
let is_implicit_name name = name <> " " && name . [ 0 ] = ' _ ' && try let _ = int_of_string @@ String . sub name 1 ( String . length name - 1 ) in true with Failure _ -> false
let map_items unwrap wrap items = let rec aux acc = function | [ ] -> acc | item :: items -> let sig_item , _ = unwrap item in let name , rec_status = match sig_item with | Outcometree . Osig_class ( _ , name , _ , _ , rs ) | Outcometree . Osig_class_type ( _ , name , _ , _ , rs ) | Outcometree . Osig_module ( name , _ , rs ) | Outcometree . Osig_type ( { Outcometree . otype_name = name } , rs ) -> ( name , rs ) | Outcometree . Osig_typext ( { Outcometree . oext_name = name } , _ ) | Outcometree . Osig_modtype ( name , _ ) | Outcometree . Osig_value ( name , _ , _ ) -> ( name , Outcometree . Orec_not ) # else | Outcometree . Osig_value { oval_name = name ; _ } -> ( name , Outcometree . Orec_not ) | Outcometree . Osig_ellipsis -> ( " " , Outcometree . Orec_not ) # endif in let keep = name = " " || name . [ 0 ] <> ' _ ' || ( UTop . get_create_implicits ( ) && is_implicit_name name ) in if keep then aux ( item :: acc ) items else let items = match items with | [ ] -> [ ] | item :: items ' -> let sig_item , extra = unwrap item in match sig_item with | Outcometree . Osig_class ( a , name , b , c , rs ) -> if rs = Outcometree . Orec_next then wrap ( Outcometree . Osig_class ( a , name , b , c , Outcometree . Orec_first ) ) extra :: items ' else items | Outcometree . Osig_class_type ( a , name , b , c , rs ) -> if rs = Outcometree . Orec_next then wrap ( Outcometree . Osig_class_type ( a , name , b , c , Outcometree . Orec_first ) ) extra :: items ' else items | Outcometree . Osig_module ( name , a , rs ) -> if rs = Outcometree . Orec_next then wrap ( Outcometree . Osig_module ( name , a , Outcometree . Orec_first ) ) extra :: items ' else items | Outcometree . Osig_type ( oty , rs ) -> if rs = Outcometree . Orec_next then wrap ( Outcometree . Osig_type ( oty , Outcometree . Orec_first ) ) extra :: items ' else items | Outcometree . Osig_typext _ | Outcometree . Osig_ellipsis # endif | Outcometree . Osig_modtype _ | Outcometree . Osig_value _ -> items in aux acc items in List . rev ( aux [ ] items )
let print_out_signature pp items = if UTop . get_hide_reserved ( ) then orig_print_out_signature pp ( map_items ( fun x -> ( x , ( ) ) ) ( fun x ( ) -> x ) items ) else orig_print_out_signature pp items
let print_out_phrase pp phrase = if UTop . get_hide_reserved ( ) then let phrase = match phrase with | Outcometree . Ophr_eval _ | Outcometree . Ophr_exception _ -> phrase | Outcometree . Ophr_signature items -> Outcometree . Ophr_signature ( map_items ( fun x -> x ) ( fun x y -> ( x , y ) ) items ) in orig_print_out_phrase pp phrase else orig_print_out_phrase pp phrase
let ( ) = Toploop . print_out_signature := print_out_signature ; Toploop . print_out_phrase := print_out_phrase
let with_loc loc str = { Location . txt = str ; Location . loc = loc ; }
type rewrite_rule = { type_to_rewrite : Longident . t ; mutable path_to_rewrite : Path . t option ; required_values : Longident . t list ; rewrite : Location . t -> Parsetree . expression -> Parsetree . expression ; enabled : bool React . signal ; }
let longident_parse str = let lexbuf = Lexing . from_string str in Parse . longident lexbuf # endif
let longident_lwt_main_run = Longident . Ldot ( Longident . Lident " Lwt_main " , " run " )
let longident_async_thread_safe_block_on_async_exn = Longident . ( Ldot ( Ldot ( Lident " Async " , " Thread_safe " ) , " block_on_async_exn " ) )
let longident_unit = Longident . Lident " ( ) "
let nolabel = Asttypes . Nolabel # else
let nolabel = " " # endif
let rewrite_rules = [ { type_to_rewrite = Longident . ( Ldot ( Lident " Lwt " , " t " ) ) ; path_to_rewrite = None ; required_values = [ longident_lwt_main_run ] ; rewrite = ( fun loc e -> let open Ast_helper in with_default_loc loc ( fun ( ) -> Exp . apply ( Exp . ident ( with_loc loc longident_lwt_main_run ) ) [ ( nolabel , e ) ] ) ) ; enabled = UTop . auto_run_lwt ; } ; { type_to_rewrite = Longident . ( Ldot ( Ldot ( Lident " Async " , " Deferred " ) , " t " ) ) ; path_to_rewrite = None ; required_values = [ longident_async_thread_safe_block_on_async_exn ] ; rewrite = ( fun loc e -> let open Ast_helper in let punit = Pat . construct ( with_loc loc ( Longident . Lident " ( ) " ) ) None in with_default_loc loc ( fun ( ) -> Exp . apply ( Exp . ident ( with_loc loc longident_async_thread_safe_block_on_async_exn ) ) [ ( nolabel , Exp . fun_ nolabel None punit e ) ] ) ) ; enabled = UTop . auto_run_async ; } ]
let lookup_type longident env = Env . find_type_by_name longident env
let lookup_type longident env = let path = Env . lookup_type longident env in ( path , Env . find_type path env ) # else
let lookup_type = Env . lookup_type # endif
let rule_path rule = match rule . path_to_rewrite with | Some _ as x -> x | None -> try let env = ! Toploop . toplevel_env in let path = match lookup_type rule . type_to_rewrite env with | path , { Types . type_kind = Types . Type_abstract ; Types . type_private = Asttypes . Public ; Types . type_manifest = Some ty } -> begin match get_desc ( Ctype . expand_head env ty ) with | Types . Tconstr ( path , _ , _ ) -> path | _ -> path end | path , _ -> path in let opt = Some path in rule . path_to_rewrite <- opt ; opt with _ -> None
let rec is_persistent_path = function | Path . Pident id -> Ident . persistent id | Path . Pdot ( p , _ ) -> is_persistent_path p # else | Path . Pdot ( p , _ , _ ) -> is_persistent_path p # endif | Path . Papply ( _ , p ) -> is_persistent_path p
let is_persistent_in_env longident = let lookup_value = Env . find_value_by_name # else Env . lookup_value # endif in try is_persistent_path ( fst ( lookup_value longident ! Toploop . toplevel_env ) ) with Not_found -> false
let rule_matches rule path = React . S . value rule . enabled && ( match rule_path rule with | None -> false | Some path ' -> Path . same path path ' ) && List . for_all is_persistent_in_env rule . required_values
let is_eval = function | { Parsetree . pstr_desc = Parsetree . Pstr_eval _ } -> true | _ -> false
let rule_of_type typ = match get_desc ( Ctype . expand_head ! Toploop . toplevel_env typ ) with | Types . Tconstr ( path , _ , _ ) -> begin try Some ( List . find ( fun rule -> rule_matches rule path ) rewrite_rules ) with _ -> None end | _ -> None
let rewrite_str_item pstr_item tstr_item = match pstr_item , tstr_item . Typedtree . str_desc with | ( { Parsetree . pstr_desc = Parsetree . Pstr_eval ( e , _ ) ; Parsetree . pstr_loc = loc } , Typedtree . Tstr_eval ( { Typedtree . exp_type = typ } , _ ) ) -> begin match rule_of_type typ with | Some rule -> { Parsetree . pstr_desc = Parsetree . Pstr_eval ( rule . rewrite loc e , [ ] ) ; Parsetree . pstr_loc = loc } | None -> pstr_item end | _ -> pstr_item
let type_structure env pstr = let tstr , _ , _ , _ , _ = Typemod . type_structure env pstr in let tstr , _ , _ , _ = Typemod . type_structure env pstr in let tstr , _ , _ , _ = Typemod . type_structure env pstr Location . none in # else let tstr , _ , _ = Typemod . type_structure env pstr Location . none in # endif tstr
let rewrite phrase = match phrase with | Parsetree . Ptop_def pstr -> if ( UTop . get_auto_run_lwt ( ) || UTop . get_auto_run_async ( ) ) && List . exists is_eval pstr then let tstr = type_structure ! Toploop . toplevel_env pstr in Parsetree . Ptop_def ( List . map2 rewrite_str_item pstr tstr . Typedtree . str_items ) else phrase | Parsetree . Ptop_dir _ -> phrase
let add_let binding_name def = let open Parsetree in match def with | { pstr_desc = Pstr_eval ( expr , attr ) ; pstr_loc } -> { pstr_loc ; pstr_desc = Pstr_value ( Asttypes . Nonrecursive , [ { pvb_pat = { ppat_desc = Ppat_var { txt = binding_name ; loc = pstr_loc ; } ; ppat_loc_stack = [ ] ; # endif ppat_loc = pstr_loc ; ppat_attributes = [ ] ; } ; pvb_expr = expr ; pvb_attributes = attr ; pvb_loc = pstr_loc ; } ] ) ; } | _ -> def
let bind_expressions name phrase = match phrase with | Parsetree . Ptop_def pstr -> Parsetree . Ptop_def ( List . map ( add_let name ) pstr ) | Parsetree . Ptop_dir _ -> phrase module Persistent_signature = Persistent_env . Persistent_signature # else module Persistent_signature = Env . Persistent_signature # endif
let execute_phrase = let new_cmis = ref [ ] in let default_load = ! Persistent_signature . load in let load ~ unit_name = let res = default_load ~ unit_name in ( match res with None -> ( ) | Some x -> new_cmis := x . cmi :: ! new_cmis ) ; res in Persistent_signature . load := load ; let rec collect_printers path signature acc = List . fold_left ( fun acc item -> match ( item : Types . signature_item ) with | Sig_module ( id , _ , { md_type = Mty_signature s ; _ } , _ , _ ) -> # else | Sig_module ( id , { md_type = Mty_signature s ; _ } , _ ) -> # endif collect_printers ( Longident . Ldot ( path , Ident . name id ) ) s acc | Sig_value ( id , vd , _ ) -> # else | Sig_value ( id , vd ) -> # endif if List . exists ( fun attr -> let open Parsetree in match attr . attr_name with | { Asttypes . txt = " toplevel_printer " | " ocaml . toplevel_printer " ; _ } -> # else if List . exists ( function | { Asttypes . txt = " toplevel_printer " | " ocaml . toplevel_printer " ; _ } , _ -> # endif true | _ -> false ) vd . val_attributes then Longident . Ldot ( path , Ident . name id ) :: acc else acc | _ -> acc ) acc signature in let acknowledge_new_cmis ( ) = let l = ! new_cmis in new_cmis := [ ] ; let printers = List . fold_left ( fun acc ( cmi : Cmi_format . cmi_infos ) -> collect_printers ( Longident . Lident cmi . cmi_name ) cmi . cmi_sign acc ) [ ] l in List . iter ( Topdirs . dir_install_printer Format . err_formatter ) printers in fun b pp phrase -> acknowledge_new_cmis ( ) ; let res = Toploop . execute_phrase b pp phrase in acknowledge_new_cmis ( ) ; res # else
let execute_phrase = Toploop . execute_phrase # endif
let rec read_phrase term = Lwt . catch ( fun ( ) -> let read_line = new read_phrase ~ term in ( match ! UTop . edit_mode with | LTerm_editor . Default -> ( ) | LTerm_editor . Vi as mode -> read_line # set_editor_mode mode ) ; let vi_state = read_line # vi_state in vi_state # set_registers ! registers ; read_line # run >>= fun result -> registers := vi_state # get_registers ; return result ) ( function | Sys . Break -> LTerm . fprintl term " Interrupted . " >>= fun ( ) -> read_phrase term | exn -> Lwt . fail exn )
let print_error term msg = LTerm . set_style term styles . style_error >>= fun ( ) -> Lwt_io . print msg >>= fun ( ) -> LTerm . set_style term LTerm_style . none >>= fun ( ) -> LTerm . flush term
let rec loop term = UTop_complete . reset ( ) ; UTop_private . set_count ( S . value UTop_private . count + 1 ) ; LTerm_dlist . iter_l ( fun f -> f ( ) ) UTop . new_command_hooks ; let phrase_opt = Lwt_main . run ( Lwt . finalize ( fun ( ) -> read_phrase term >>= fun ( result , warnings ) -> Lwt_io . print warnings >>= fun ( ) -> match result with | UTop . Value phrase -> return ( Some phrase ) | UTop . Error ( locs , msg ) -> print_error term msg >>= fun ( ) -> return None ) ( fun ( ) -> LTerm . flush term ) ) in match phrase_opt with | Some phrase -> let count = S . value UTop_private . count in let phrase = rewrite phrase in let phrase = if UTop . get_create_implicits ( ) then let binding_name = Printf . sprintf " _ % d " count in bind_expressions binding_name phrase else phrase in UTop_private . set_margin Format . std_formatter ; UTop_private . set_margin Format . err_formatter ; let buffer = Buffer . create 1024 in let pp = Format . formatter_of_buffer buffer in UTop_private . set_margin pp ; ( try Env . reset_cache_toplevel ( ) ; if ! Clflags . dump_parsetree then Printast . top_phrase pp phrase ; if ! Clflags . dump_source then Pprintast . top_phrase pp phrase ; ignore ( execute_phrase true pp phrase ) ; Format . pp_print_flush Format . std_formatter ( ) ; Format . pp_print_flush Format . err_formatter ( ) ; flush stdout ; flush stderr ; Format . pp_print_flush pp ( ) ; let string = Buffer . contents buffer in UTop_history . add_output UTop . stashable_session_history string ; match phrase with | Parsetree . Ptop_def _ -> Lwt_main . run ( render_out_phrase term string ) | Parsetree . Ptop_dir _ -> Lwt_main . run ( print_error term string ) with exn -> let msg = UTop . get_message Errors . report_error exn in let msg = try let idx = String . index msg ' \ n ' + 1 in String . sub msg idx ( String . length msg - idx ) with Not_found -> msg in Lwt_main . run ( print_error term msg ) ) ; loop term | None -> loop term
let welcome term = let size = LTerm . size term in let size = { rows = 3 ; cols = size . cols } in let matrix = LTerm_draw . make_matrix size in let ctx = LTerm_draw . context matrix size in let message = Printf . sprintf " Welcome to utop version % s ( using OCaml version % s ) " ! UTop . version Sys . ocaml_version in LTerm_draw . fill_style ctx LTerm_style . ( { none with foreground = Some lcyan } ) ; LTerm_draw . draw_hline ctx 0 0 size . cols LTerm_draw . Light ; LTerm_draw . draw_frame ctx { row1 = 0 ; row2 = 3 ; col1 = ( size . cols - ( String . length message + 4 ) ) / 2 ; col2 = ( size . cols + ( String . length message + 4 ) ) / 2 ; } LTerm_draw . Light ; LTerm_draw . draw_styled ctx 1 ( ( size . cols - String . length message ) / 2 ) ( eval [ B_fg LTerm_style . yellow ; S message ] ) ; LTerm . print_box term matrix >>= fun ( ) -> LTerm . fprint term " \ n " >>= fun ( ) -> LTerm . flush term
let read_input_classic prompt buffer len = let rec loop i = if i = len then return ( i , false ) else Lwt_io . read_char_opt Lwt_io . stdin >>= function | Some c -> Bytes . set buffer i c ; if c = ' \ n ' then return ( i + 1 , false ) else loop ( i + 1 ) | None -> return ( i , true ) in Lwt_main . run ( Lwt_io . write Lwt_io . stdout prompt >>= fun ( ) -> loop 0 )
module Emacs ( M : sig end ) = struct let command_oc = Unix . out_channel_of_descr ( Unix . dup Unix . stdout ) let split_at ( ? trim = false ) ch str = let rec aux acc i j = if j = String . length str then if trim && i = j then acc else ( String . sub str i ( j - i ) ) :: acc else if str . [ j ] = ch then aux ( String . sub str i ( j - i ) :: acc ) ( j + 1 ) ( j + 1 ) else aux acc i ( j + 1 ) in List . rev ( aux [ ] 0 0 ) let command_mutex = Mutex . create ( ) let send command argument = Mutex . lock command_mutex ; output_string command_oc command ; output_char command_oc ' ' ; : output_string command_oc argument ; output_char command_oc ' \ n ' ; flush command_oc ; Mutex . unlock command_mutex let ( ) = S . keep ( S . map ( send " phrase - terminator " ) UTop . phrase_terminator ) let rec copy_output which ic = let line = input_line ic in send which line ; copy_output which ic let redirect which fd = let fdr , fdw = Unix . pipe ( ) in Unix . dup2 fdw fd ; Unix . close fdw ; Thread . create ( copy_output which ) ( Unix . in_channel_of_descr fdr ) let _ = redirect " stdout " Unix . stdout let _ = redirect " stderr " Unix . stderr let read_line ( ) = let behavior = Sys . signal Sys . sigint Sys . Signal_ignore in try let line = Lwt_main . run ( Lwt_io . read_line_opt Lwt_io . stdin ) in Sys . set_signal Sys . sigint behavior ; line with exn -> Sys . set_signal Sys . sigint behavior ; raise exn let read_command ( ) = match read_line ( ) with | None -> None | Some line -> match try Some ( String . index line ' ' ) : with Not_found -> None with | None -> send " stderr " " ' ' : missing " ; ! exit 1 | Some idx -> Some ( String . sub line 0 idx , String . sub line ( idx + 1 ) ( String . length line - ( idx + 1 ) ) ) let read_data ( ) = let buf = Buffer . create 1024 in let rec loop first = match read_command ( ) with | None -> send " stderr " " ' end ' command missing " ; ! exit 1 | Some ( " data " , data ) -> if not first then Buffer . add_char buf ' \ n ' ; Buffer . add_string buf data ; loop false | Some ( " end " , _ ) -> Buffer . contents buf | Some ( command , argument ) -> Printf . ksprintf ( send " stderr " ) " ' data ' or ' end ' command expected , got % S " ! command ; exit 1 in loop true let process_checked_phrase phrase = let phrase = rewrite phrase in try Env . reset_cache_toplevel ( ) ; ignore ( execute_phrase true Format . std_formatter phrase ) ; true with exn -> let msg = UTop . get_message Errors . report_error exn in let msg = try let idx = String . index msg ' \ n ' + 1 in String . sub msg idx ( String . length msg - idx ) with Not_found -> msg in List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' msg ) ; false let process_input add_to_history eos_is_error = let input = read_data ( ) in let input_zed = Zed_string . unsafe_of_utf8 input in let result , warnings = parse_and_check input eos_is_error in match result with | UTop . Value phrase -> send " accept " " " ; List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' warnings ) ; if add_to_history then LTerm_history . add UTop . history input_zed ; ignore ( process_checked_phrase phrase ) | UTop . Error ( locs , msg ) -> send " accept " ( String . concat " , " ( List . map ( fun ( a , b ) -> Printf . sprintf " % d , % d " a b ) locs ) ) ; List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' warnings ) ; if add_to_history then LTerm_history . add UTop . history input_zed ; List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' msg ) let send_error locs msg warnings = send " accept " ( String . concat " , " ( List . map ( fun ( a , b ) -> Printf . sprintf " % d , % d " a b ) locs ) ) ; match warnings with | Some warnings -> List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' warnings ) | None -> ( ) ; List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' msg ) let process_input_multi ( ) = let input = read_data ( ) in let result , warnings = parse_input_multi input in let typecheck phrase = match UTop . check_phrase phrase with | None -> None | Some ( locs , msg , lines ) -> Some ( convert_loc_line input locs lines , msg ) in match result with | UTop . Value phrases -> send " accept " " " ; List . iter ( send " stderr " ) ( split_at ~ trim : true ' \ n ' warnings ) ; let rec loop = function | ( phrase :: more_phrases ) -> begin match typecheck phrase with | Some ( locs , msg ) -> send_error locs msg None | None -> let success = process_checked_phrase phrase in if success then loop more_phrases else ( ) end | [ ] -> ( ) in loop phrases | UTop . Error ( locs , msg ) -> send_error locs msg ( Some warnings ) let rec loop ( ) = UTop_complete . reset ( ) ; UTop_private . set_count ( S . value UTop_private . count + 1 ) ; LTerm_dlist . iter_l ( fun f -> f ( ) ) UTop . new_command_hooks ; send " prompt " " " ; loop_commands ( LTerm_history . contents UTop . history ) [ ] and loop_commands history_prev history_next = match read_command ( ) with | None -> ( ) | Some ( " input " , arg ) -> let args = split_at ' , ' arg in let allow_incomplete = List . mem " allow - incomplete " args and add_to_history = List . mem " add - to - history " args in let continue = try process_input add_to_history ( not allow_incomplete ) ; false with UTop . Need_more -> send " continue " " " ; true in if continue then loop_commands history_prev history_next else loop ( ) | Some ( " input - multi " , _ ) -> let continue = try process_input_multi ( ) ; false with UTop . Need_more -> send " continue " " " ; true in if continue then loop_commands history_prev history_next else loop ( ) | Some ( " complete - company " , _ ) -> let input = read_data ( ) in let _ , words = UTop_complete . complete ~ phrase_terminator ( : UTop . get_phrase_terminator ( ) ) ~ input in send " completion - start " " " ; List . iter ( fun ( w , _ ) -> send " completion " w ) words ; send " completion - stop " " " ; loop_commands history_prev history_next | Some ( " complete " , _ ) -> let input = read_data ( ) in let start , words = UTop_complete . complete ~ phrase_terminator ( : UTop . get_phrase_terminator ( ) ) ~ input in let words = List . map fst words in let prefix = LTerm_read_line . common_prefix words in let index = String . length input - start in let suffix = if index > 0 && index <= String . length prefix then String . sub prefix index ( String . length prefix - index ) else " " in if suffix = " " then begin send " completion - start " " " ; List . iter ( send " completion " ) words ; send " completion - stop " " " ; end else send " completion - word " suffix ; loop_commands history_prev history_next | Some ( " history - prev " , _ ) -> begin let input = read_data ( ) in match history_prev with | [ ] -> send " history - bound " " " ; loop_commands history_prev history_next | entry :: history_prev -> List . iter ( send " history - data " ) ( split_at ' \ n ' ( Zed_string . to_utf8 entry ) ) ; send " history - end " " " ; loop_commands history_prev ( input :: history_next ) end | Some ( " history - next " , _ ) -> begin let input = read_data ( ) in match history_next with | [ ] -> send " history - bound " " " ; loop_commands history_prev history_next | entry :: history_next -> List . iter ( send " history - data " ) ( split_at ' \ n ' entry ) ; send " history - end " " " ; loop_commands ( ( Zed_string . unsafe_of_utf8 input ) :: history_prev ) history_next end | Some ( " exit " , code ) -> exit ( int_of_string code ) | Some ( " save - history " , code ) -> Lwt_main . run ( save_history ( ) ) ; loop_commands history_prev history_next | Some ( " require " , package ) -> begin try Topfind . load_deeply [ package ] with Fl_package_base . No_such_package ( pkg , reason ) -> send " no - such - package " pkg end ; loop_commands history_prev history_next | Some ( command , _ ) -> Printf . ksprintf ( send " stderr " ) " unrecognized command % S " ! command ; exit 1 end