text
stringlengths
0
601k
let mk ' ~ mode depth type_desc = incr type_id ; Option . iter failure_type_id ~ f ( : fun id -> assert ( ! type_id <> id ) ) ; { type_desc ; type_id = ! type_id ; type_depth = depth ; type_mode = mode ; type_alternate = other_none mode }
let stitch typ typ ' = assert ( equal_mode typ . type_mode ( other_mode typ ' . type_mode ) ) ; assert ( is_invalid typ . type_alternate ) ; assert ( is_invalid typ ' . type_alternate ) ; typ . type_alternate <- typ ' ; typ ' . type_alternate <- typ ; typ
let tri_stitch in_typ ptyp ctyp = assert ( equal_mode in_typ . type_mode Checked ) ; assert ( equal_mode ptyp . type_mode Prover ) ; assert ( equal_mode ctyp . type_mode Checked ) ; assert ( is_invalid in_typ . type_alternate ) ; assert ( is_invalid ptyp . type_alternate ) ; assert ( is_invalid ctyp . type_alternate ) ; in_typ . type_alternate <- ptyp ; ptyp . type_alternate <- ctyp ; ctyp . type_alternate <- ptyp ; in_typ
let are_stitched typ typ ' = ( phys_equal typ typ ' . type_alternate && phys_equal typ ' typ . type_alternate ) || let ctyp , ptyp , modes_match = match ( typ . type_mode , typ ' . type_mode ) with | Checked , Prover -> ( typ , typ ' , true ) | Prover , Checked -> ( typ ' , typ , true ) | _ -> ( typ , typ ' , false ) in modes_match && phys_equal ctyp . type_alternate ptyp && phys_equal ptyp ptyp . type_alternate . type_alternate
let mkvar ~ mode depth name = let typ = mk ' ~ mode depth ( Tvar name ) in let other_typ = mk ' ~ mode ( : other_mode mode ) depth ( Tvar name ) in if equal_mode mode Checked then let tri_typ = mk ' ~ mode depth ( Tvar name ) in tri_stitch typ other_typ tri_typ else stitch typ other_typ
module Mk = struct let var = mkvar let stitch ~ mode depth desc1 desc2 = stitch ( mk ' ~ mode depth desc1 ) ( mk ' ~ mode ( : other_mode mode ) depth desc2 ) let tri_stitch ~ mode depth desc1 desc2 desc3 = assert ( equal_mode mode Checked ) ; tri_stitch ( mk ' ~ mode : Checked depth desc1 ) ( mk ' ~ mode : Prover depth desc2 ) ( mk ' ~ mode : Checked depth desc3 ) let tuple ~ mode depth typs = let error_info ( ) = ( " tuple " , typs ) in let alts = List . map ~ f : type_alternate typs in let alt_alts = List . map ~ f : type_alternate alts in if List . for_all2_exn typs alt_alts ~ f ( : fun typ alt -> check_mode ~ pos : __POS__ ~ error_info mode typ ; check_mode ~ pos : __POS__ ~ error_info mode alt ; assert ( not ( is_poly typ ) ) ; check_valid ~ pos : __POS__ ~ error_info typ ; check_valid ~ pos : __POS__ ~ error_info alt ; phys_equal typ alt ) then stitch ~ mode depth ( Ttuple typs ) ( Ttuple alts ) else tri_stitch ~ mode depth ( Ttuple typs ) ( Ttuple alts ) ( Ttuple alt_alts ) let arrow ~ mode ( ? explicit = Explicit ) ( ? label = Nolabel ) depth typ1 typ2 = let error_info ( ) = ( " arrow " , [ typ1 ; typ2 ] ) in let alt1 = type_alternate typ1 in let alt2 = type_alternate typ2 in let alt_alt1 = type_alternate alt1 in let alt_alt2 = type_alternate alt2 in if List . for_all2_exn [ typ1 ; typ2 ] [ alt_alt1 ; alt_alt2 ] ~ f ( : fun typ alt -> check_mode ~ pos : __POS__ ~ error_info mode typ ; check_mode ~ pos : __POS__ ~ error_info mode alt ; check_valid ~ pos : __POS__ ~ error_info typ ; check_valid ~ pos : __POS__ ~ error_info alt ; assert ( not ( is_poly typ ) ) ; phys_equal typ alt ) then stitch ~ mode depth ( Tarrow ( typ1 , typ2 , explicit , label ) ) ( Tarrow ( alt1 , alt2 , explicit , label ) ) else tri_stitch ~ mode depth ( Tarrow ( typ1 , typ2 , explicit , label ) ) ( Tarrow ( alt1 , alt2 , explicit , label ) ) ( Tarrow ( alt_alt1 , alt_alt2 , explicit , label ) ) let ctor ~ mode depth path ? other_path ? tri_path params = let error_info ( ) = let desc = Format . ( fprintf str_formatter " ctor ( % a ) " Path . debug_print path ) ; Format . flush_str_formatter ( ) in ( desc , params ) in assert ( Option . is_some other_path || Option . is_none tri_path ) ; let other_path = Option . value ~ default : path other_path in let alts = List . map ~ f : type_alternate params in let alt_alts = List . map ~ f : type_alternate alts in if List . for_all2_exn params alt_alts ~ f ( : fun typ alt -> check_mode ~ pos : __POS__ ~ error_info mode typ ; check_mode ~ pos : __POS__ ~ error_info mode alt ; check_valid ~ pos : __POS__ ~ error_info typ ; check_valid ~ pos : __POS__ ~ error_info alt ; assert ( not ( is_poly typ ) ) ; phys_equal typ alt ) && Option . is_none tri_path then stitch ~ mode depth ( Tctor { var_ident = path ; var_params = params } ) ( Tctor { var_ident = other_path ; var_params = alts } ) else let tri_path = Option . value ~ default : path tri_path in tri_stitch ~ mode depth ( Tctor { var_ident = path ; var_params = params } ) ( Tctor { var_ident = other_path ; var_params = alts } ) ( Tctor { var_ident = tri_path ; var_params = alt_alts } ) let poly ~ mode depth vars typ = let error_info ( ) = ( " poly " , typ :: vars ) in check_valid ~ pos : __POS__ ~ error_info typ ; assert ( not ( is_poly typ ) ) ; check_mode ~ pos : __POS__ ~ error_info mode typ ; let alt = type_alternate typ in let alt_alt = type_alternate alt in check_valid ~ pos : __POS__ ~ error_info alt_alt ; let get_alt_var pos mode var = let alt = get_mode mode var in check_valid ~ pos : __POS__ ~ error_info alt ; match alt . type_desc with | Tvar _ -> alt | _ -> check_mode ~ pos ~ error_info Checked var ; assert ( not ( phys_equal alt . type_alternate var ) ) ; var in let alts = List . map ~ f ( : get_alt_var __POS__ ( other_mode mode ) ) vars in let alt_alts = List . map ~ f ( : get_alt_var __POS__ mode ) alts in if equal_mode mode Prover || List . for_all2_exn vars alt_alts ~ f ( : fun typ alt -> ( match ( typ . type_desc , alt . type_desc ) with | Tvar _ , Tvar _ -> ( ) | _ -> assert false ) ; phys_equal typ alt ) && phys_equal typ alt_alt then stitch ~ mode depth ( Tpoly ( vars , typ ) ) ( Tpoly ( vars , alt ) ) else tri_stitch ~ mode depth ( Tpoly ( vars , typ ) ) ( Tpoly ( vars , alt ) ) ( Tpoly ( vars , alt_alt ) ) let conv ~ mode depth typ1 typ2 = let error_info ( ) = ( " conv " , [ typ1 ; typ2 ] ) in check_valid ~ pos : __POS__ ~ error_info typ1 ; check_valid ~ pos : __POS__ ~ error_info typ2 ; assert ( not ( is_poly typ1 ) ) ; assert ( not ( is_poly typ2 ) ) ; check_mode ~ pos : __POS__ ~ error_info Checked typ1 ; check_mode ~ pos : __POS__ ~ error_info Prover typ2 ; let typ_stitched = if are_stitched typ1 typ2 then typ1 else stitch ~ mode : Checked depth typ1 . type_desc typ2 . type_desc in let typ = stitch ~ mode : Checked depth ( Tconv typ_stitched ) ( Tconv typ_stitched ) in get_mode mode typ let opaque ~ mode depth typ = let error_info ( ) = ( " opaque " , [ typ ] ) in check_valid ~ pos : __POS__ ~ error_info typ ; check_valid ~ pos : __POS__ ~ error_info typ . type_alternate . type_alternate ; assert ( not ( is_poly typ ) ) ; check_mode ~ pos : __POS__ ~ error_info Prover typ ; stitch ~ mode depth ( Topaque typ ) ( Topaque typ ) let other_mode ~ mode depth typ = let error_info ( ) = ( " other_mode " , [ typ ] ) in check_valid ~ pos : __POS__ ~ error_info typ ; check_valid ~ pos : __POS__ ~ error_info typ . type_alternate . type_alternate ; assert ( not ( is_poly typ ) ) ; stitch ~ mode depth ( Tother_mode typ ) ( Tother_mode typ ) let row ~ mode depth row = let row_alt = row_alternate row in match mode with | Prover -> let alt = stitch ~ mode : Prover depth ( Trow row ) ( Trow row_alt ) in opaque ~ mode depth alt | Checked -> let row_alt_alt = row_alternate row in let prover = stitch ~ mode : Prover depth ( Trow row_alt ) ( Trow row_alt_alt ) in tri_stitch ~ mode depth ( Trow row ) ( Topaque prover ) ( Topaque prover ) let row_of_ctor ~ mode depth ident args = let row_rest = var ~ mode depth None in let row_tags = Ident . Map . singleton ident ( Path . Pident ident , mk_rp RpPresent , args ) in row ~ mode depth { row_tags ; row_closed = Open ; row_rest ; row_presence_proxy = mk_rp RpPresent } end
type change = | Depth of ( type_expr * int ) | Desc of ( type_expr * type_desc ) | Replace of ( type_expr * type_desc ) | Row_presence of ( row_presence * row_presence_desc ) | Row_replace of ( row_presence * row_presence_desc )
let debug_print_change fmt = function | Depth ( typ , depth ) -> Format . fprintf fmt " depth ( id = % i , % i ) " typ . type_id depth | Desc ( typ , _ ) -> Format . fprintf fmt " desc ( id = % i , _ ) " typ . type_id | Replace ( typ , _ ) -> Format . fprintf fmt " replace ( id = % i , _ ) " typ . type_id | Row_presence ( pres , _ ) -> Format . fprintf fmt " row_presence ( id = % i , _ ) " pres . rp_id | Row_replace ( pres , _ ) -> Format . fprintf fmt " row_replace ( id = % i , _ ) " pres . rp_id
module Snapshot : sig type t val create : unit -> t val add_to_history : change -> unit val backtrack : t -> change list val filtered_backtrack : f ( : change -> bool ) -> t -> change list val debug_print : Format . formatter -> t -> unit val debug_print_latest : Format . formatter -> unit -> unit type node = Change of ( change * t ) | LinkedChange of t | NoChange and t = node ref let current = Weak . create 1 let add_to_history change = match Weak . get current 0 with | Some ptr -> let new_ptr = ref NoChange in ptr := Change ( change , new_ptr ) ; Weak . set current 0 ( Some new_ptr ) | None -> ( ) let create ( ) = match Weak . get current 0 with | Some ptr -> ptr | None -> let new_ptr = ref NoChange in Weak . set current 0 ( Some new_ptr ) ; new_ptr let rec collect snap = match ! snap with | Change ( change , ptr ) -> change :: collect ptr | LinkedChange ptr -> collect ptr | NoChange -> [ ] let debug_print fmt snap = let open Format in pp_print_list ~ pp_sep ( : fun fmt ( ) -> fprintf fmt " , , " ) @ debug_print_change fmt ( collect snap ) let debug_print_latest fmt ( ) = match Weak . get current 0 with | Some snap -> debug_print fmt snap | None -> Format . pp_print_list debug_print_change fmt [ ] let backtrack snap = let current = create ( ) in let rec backtrack changes ptr = match ! ptr with | Change ( change , ptr ' ) -> ptr := LinkedChange current ; backtrack ( change :: changes ) ptr ' | LinkedChange ptr ' -> ptr := LinkedChange current ; backtrack changes ptr ' | NoChange -> changes in backtrack [ ] snap let filtered_backtrack ~ f snap = let rec backtrack changes ptrs_to_clear ptr = match ! ptr with | Change ( change , ptr ' ) when f change -> backtrack ( change :: changes ) ( ptr :: ptrs_to_clear ) ptr ' | Change ( _change , ptr ' ) -> List . iter ptrs_to_clear ~ f ( : fun ptr ' -> ptr ' := LinkedChange ptr ) ; backtrack changes [ ] ptr ' | LinkedChange ptr ' -> backtrack changes ptrs_to_clear ptr ' | NoChange -> let current = create ( ) in List . iter ptrs_to_clear ~ f ( : fun ptr ' -> ptr ' := LinkedChange current ) ; changes in backtrack [ ] [ ] snap end
let revert = function | Depth ( typ , depth ) -> typ . type_depth <- depth ; typ . type_alternate . type_depth <- depth ; typ . type_alternate . type_alternate . type_depth <- depth | Desc ( typ , desc ) -> typ . type_desc <- desc | Replace ( typ , desc ) -> typ . type_desc <- desc | Row_presence ( pres , desc ) | Row_replace ( pres , desc ) -> pres . rp_desc <- desc
let backtrack snap = let changes = Snapshot . backtrack snap in List . iter ~ f : revert changes
let filtered_backtrack ~ f snap = let changes = Snapshot . filtered_backtrack ~ f snap in List . iter ~ f : revert changes
let fold ~ init ~ f typ = match typ . type_desc with | Tvar _ -> init | Ttuple typs -> List . fold ~ init ~ f typs | Tarrow ( typ1 , typ2 , _ , _ ) -> let acc = f init typ1 in f acc typ2 | Tctor variant -> List . fold ~ init ~ f variant . var_params | Tpoly ( typs , typ ) -> let acc = List . fold ~ init ~ f typs in f acc typ | Tref typ -> f init typ | Tconv typ -> f init typ | Topaque typ -> f init typ | Tother_mode typ -> f init typ | Treplace _ -> assert false | Trow { row_tags ; row_closed = _ ; row_rest ; row_presence_proxy = _ } -> let acc = Map . fold row_tags ~ init ~ f ( : fun ~ key : _ ~ data ( : _ , _ , args ) init -> List . fold ~ f ~ init args ) in f acc row_rest
let iter ~ f = fold ~ init ( ) : ~ f ( : fun ( ) -> f )
let rec copy_desc ~ f = function | Tvar _ as typ -> typ | Ttuple typs -> Ttuple ( List . map ~ f typs ) | Tarrow ( typ1 , typ2 , explicitness , label ) -> Tarrow ( f typ1 , f typ2 , explicitness , label ) | Tctor ( { var_params ; _ } as variant ) -> Tctor { variant with var_params = List . map ~ f var_params } | Tpoly ( typs , typ ) -> Tpoly ( List . map ~ f typs , f typ ) | Tref typ -> copy_desc ~ f typ . type_desc | Tconv typ -> Tconv ( f typ ) | Topaque typ -> Topaque ( f typ ) | Tother_mode typ -> Tother_mode ( f typ ) | Treplace _ -> assert false | Trow _ -> assert false
let rec equal_at_depth ~ get_decl ~ depth typ1 typ2 = let equal_at_depth = equal_at_depth ~ get_decl ~ depth in let typ1 = repr typ1 in let typ2 = repr typ2 in if Int . equal typ1 . type_id typ2 . type_id then true else match ( typ1 . type_desc , typ2 . type_desc ) with | Tvar _ , _ when typ1 . type_depth > depth -> true | _ , Tvar _ when typ2 . type_depth > depth -> true | Ttuple typs1 , Ttuple typs2 -> ( match List . for_all2 typs1 typs2 ~ f : equal_at_depth with | Ok b -> b | Unequal_lengths -> false ) | ( Tarrow ( typ1a , typ1b , explicitness1 , label1 ) , Tarrow ( typ2a , typ2b , explicitness2 , label2 ) ) -> equal_explicitness explicitness1 explicitness2 && equal_arg_label label1 label2 && equal_at_depth typ1a typ2a && equal_at_depth typ1b typ2b | ( Tctor ( { var_ident = path1 ; _ } as variant1 ) , Tctor ( { var_ident = path2 ; _ } as variant2 ) ) -> let decl1 = get_decl path1 in let decl2 = get_decl path2 in Int . equal decl1 . tdec_id decl2 . tdec_id && List . for_all2_exn ~ f : equal_at_depth variant1 . var_params variant2 . var_params | Tpoly ( typs1 , typ1 ) , Tpoly ( typs2 , typ2 ) -> ( match List . for_all2 typs1 typs2 ~ f : equal_at_depth with | Ok true -> equal_at_depth typ1 typ2 | _ -> false ) | _ , _ -> false
let set_depth depth typ = Snapshot . add_to_history ( Depth ( typ , typ . type_depth ) ) ; typ . type_depth <- depth ; typ . type_alternate . type_depth <- depth ; typ . type_alternate . type_alternate . type_depth <- depth
let update_depth depth typ = if typ . type_depth > depth then set_depth depth typ
let unify_depths typ1 typ2 = iter ~ f ( : update_depth typ1 . type_depth ) typ2 ; iter ~ f ( : update_depth typ2 . type_depth ) typ1
let set_rp_desc pres desc = Snapshot . add_to_history ( Row_presence ( pres , pres . rp_desc ) ) ; pres . rp_desc <- desc
let ( ) = set_rp_desc_fwd := set_rp_desc
let set_desc typ desc = Snapshot . add_to_history ( Desc ( typ , typ . type_desc ) ) ; typ . type_desc <- desc
let unsafe_set_single_replacement typ typ ' = Snapshot . add_to_history ( Replace ( typ , typ . type_desc ) ) ; typ . type_desc <- Treplace typ '
let set_replacement typ typ ' = let replace_one = unsafe_set_single_replacement in replace_one typ typ ' ; replace_one typ . type_alternate typ ' . type_alternate ; let alt_alt = typ . type_alternate . type_alternate in let alt_alt ' = typ ' . type_alternate . type_alternate in if ( not ( phys_equal typ alt_alt ) ) || not ( phys_equal typ ' alt_alt ' ) then replace_one alt_alt alt_alt '
let backtrack_replace = filtered_backtrack ~ f ( : function | Replace _ | Row_replace _ -> true | _ -> false )
let set_repr typ typ ' = assert ( equal_mode typ . type_mode typ ' . type_mode ) ; assert ( phys_equal typ typ . type_alternate = phys_equal typ ' typ ' . type_alternate ) ; set_desc typ ( Tref typ ' ) ; set_desc typ . type_alternate ( Tref typ ' . type_alternate ) ; set_desc typ . type_alternate . type_alternate ( Tref typ ' . type_alternate . type_alternate )
let rec choose_variable_name typ typ ' = match ( typ . type_desc , typ ' . type_desc ) with | Tvar ( Some name ) , Tvar None -> set_desc typ ' ( Tvar ( Some name ) ) | Tvar ( Some _ ) , Trow row -> let _ , row_rest , _ = row_repr row in choose_variable_name typ row_rest | Tvar _ , _ -> ( ) | _ -> assert false
let add_instance ~ unify typ typ ' = assert ( equal_mode typ . type_mode typ ' . type_mode ) ; assert ( phys_equal typ typ . type_alternate . type_alternate = phys_equal typ ' typ ' . type_alternate . type_alternate ) ; choose_variable_name typ typ ' ; match typ . type_alternate . type_desc with | Tvar _ -> choose_variable_name typ . type_alternate typ ' . type_alternate ; choose_variable_name typ . type_alternate . type_alternate typ ' . type_alternate . type_alternate ; choose_variable_name typ typ ' ; set_repr typ typ ' | _ -> assert ( equal_mode Checked typ . type_mode ) ; set_desc typ ( Tref typ ' ) ; unify typ . type_alternate typ ' . type_alternate ; if not ( phys_equal typ typ . type_alternate . type_alternate ) then unify typ . type_alternate . type_alternate typ ' . type_alternate . type_alternate
let flatten typ = let rec flatten typ = let typ = repr typ in match typ . type_desc with | Treplace typ ' -> ( match typ . type_alternate . type_desc with | Treplace _ -> ( ) | _ -> assert false ) ; typ ' | Tvar _ -> typ | Trow _ -> typ | desc -> ( match typ . type_alternate . type_desc with | Treplace alt -> assert ( not ( phys_equal typ typ . type_alternate . type_alternate ) ) ; assert ( equal_mode typ . type_mode Checked ) ; let typ ' = mk ' ~ mode : typ . type_mode typ . type_depth ( Tvar None ) in typ ' . type_alternate <- alt ; unsafe_set_single_replacement typ typ ' ; typ ' . type_desc <- copy_desc ~ f : flatten desc ; typ ' | Tvar _ -> assert false | _ -> let alt_desc = typ . type_alternate . type_desc in let alt_alt_desc = typ . type_alternate . type_alternate . type_desc in let typ ' = mkvar ~ mode : typ . type_mode typ . type_depth None in let stitched = phys_equal typ typ . type_alternate . type_alternate in if stitched then typ ' . type_alternate . type_alternate <- typ ' ; set_replacement typ typ ' ; typ ' . type_desc <- copy_desc ~ f : flatten desc ; typ ' . type_alternate . type_desc <- copy_desc ~ f : flatten alt_desc ; if not stitched then typ ' . type_alternate . type_alternate . type_desc <- copy_desc ~ f : flatten alt_alt_desc ; typ ' ) in let snap = Snapshot . create ( ) in let typ = flatten typ in backtrack snap ; typ
let type_vars ? depth typ = let deep_enough = match depth with | Some depth -> fun typ -> depth <= typ . type_depth | None -> fun _ -> true in let empty = Typeset . empty in let rec type_vars set typ = match typ . type_desc with | Tvar _ when deep_enough typ -> Set . add set typ | Tpoly ( vars , typ ) -> let poly_vars = List . fold ~ init : empty vars ~ f : type_vars in Set . union set ( Set . diff ( type_vars empty typ ) poly_vars ) | _ -> fold ~ init : set typ ~ f : type_vars in type_vars empty typ
let mk_option : ( Type0 . type_expr -> Type0 . type_expr ) ref = ref ( fun _ -> failwith " mk_option not initialised " )
let rec bubble_label_aux label typ = let { type_depth ; type_mode = mode ; _ } = typ in match ( repr typ ) . type_desc with | Tarrow ( typ1 , typ2 , explicit , arr_label ) when Int . equal ( compare_arg_label label arr_label ) 0 -> ( Some ( typ1 , explicit , arr_label ) , typ2 ) | Tarrow ( typ1 , typ2 , explicit , arr_label ) when match ( label , arr_label ) with | Labelled lbl , Optional arr_lbl -> String . equal lbl arr_lbl | _ -> false -> ( Some ( ! mk_option typ1 , explicit , arr_label ) , typ2 ) | Tarrow ( typ1 , typ2 , explicit , arr_label ) -> ( match bubble_label_aux label typ2 with | None , _ -> ( None , typ ) | res , typ2 -> ( res , Mk . arrow ~ mode ~ explicit ~ label : arr_label type_depth typ1 typ2 ) ) | _ -> ( None , typ )
let bubble_label label typ = let { type_depth ; type_mode = mode ; _ } = typ in match bubble_label_aux label typ with | Some ( typ1 , explicit , label ) , typ2 -> Mk . arrow ~ mode ~ explicit ~ label type_depth typ1 typ2 | None , typ -> typ
let discard_optional_labels typ = let rec go typ ' = let typ ' = repr typ ' in match typ ' . type_desc with | Tarrow ( _ , typ2 , _ , Optional _ ) -> go typ2 | Tarrow ( _ , _ , _ , _ ) -> typ | _ -> typ ' in go typ
let is_arrow typ = match ( repr typ ) . type_desc with | Tarrow _ | Tpoly ( _ , { type_desc = Tarrow _ ; _ } ) -> true | _ -> false
let is_var typ = match ( repr typ ) . type_desc with Tvar _ -> true | _ -> false
let is_replace typ = match ( repr typ ) . type_desc with Treplace _ -> true | _ -> false
let get_replace typ = match ( repr typ ) . type_desc with Treplace typ -> Some typ | _ -> None
let get_rev_arrow_args typ = let rec go args typ = let typ = repr typ in match typ . type_desc with | Tarrow ( typ1 , typ2 , explicit , label ) -> go ( ( typ1 , explicit , label ) :: args ) typ2 | _ -> ( args , typ ) in go [ ] typ
let rec get_rev_implicits acc typ = match typ . type_desc with | Tarrow ( typ1 , typ2 , Implicit , label ) -> get_rev_implicits ( ( label , typ1 ) :: acc ) typ2 | _ -> ( acc , typ )
let get_implicits typ = let implicits , typ = get_rev_implicits [ ] typ in ( List . rev implicits , typ )
let get_rev_implicits typ = get_rev_implicits [ ] typ
let contains typ ~ in_ = let typ = repr typ in let equal in_ = phys_equal typ ( repr in_ ) in let rec contains in_ = let in_ = repr in_ in match in_ . type_desc with | Tvar _ -> false | Ttuple typs -> List . exists ~ f : equal typs || List . exists ~ f : contains typs | Tarrow ( typ1 , typ2 , _explicit , _label ) -> equal typ1 || equal typ2 || contains typ1 || contains typ2 | Tctor variant -> List . exists ~ f : equal variant . var_params || List . exists ~ f : contains variant . var_params | Tpoly ( typs , typ ) -> List . exists ~ f : equal typs || equal typ || List . exists ~ f : contains typs || contains typ | Tconv typ ' -> let typ ' = get_mode typ . type_mode typ ' in equal typ ' || contains typ ' | Topaque typ ' -> equal typ ' || contains typ ' | Tother_mode typ ' -> equal typ ' || contains typ ' | Tref _ -> assert false | Treplace _ -> assert false | Trow { row_tags ; row_closed = _ ; row_rest ; row_presence_proxy = _ } -> Map . exists row_tags ~ f ( : fun ( _ , _ , args ) -> List . exists ~ f : equal args ) || equal row_rest || Map . exists row_tags ~ f ( : fun ( _ , _ , args ) -> List . exists ~ f : contains args ) || contains row_rest in contains in_
let rec get_same_mode typ1 typ2 = let typ1 = repr typ1 in let typ2 = repr typ2 in match ( typ1 . type_desc , typ2 . type_desc ) with | Tother_mode typ1 ' , Tother_mode typ2 ' -> ( match ( typ1 . type_mode , typ2 . type_mode ) with | Checked , Checked | Prover , Prover -> get_same_mode typ1 ' typ2 ' | Checked , Prover -> get_same_mode typ1 typ2 ' | Prover , Checked -> get_same_mode typ1 ' typ2 ) | Tother_mode typ1 , _ when equal_mode typ1 . type_mode typ2 . type_mode -> ( repr typ1 , typ2 ) | _ , Tother_mode typ2 when equal_mode typ1 . type_mode typ2 . type_mode -> ( typ1 , repr typ2 ) | _ -> ( typ1 , typ2 )
let rec remove_opaques typ = let typ = repr typ in match typ . type_desc with Topaque typ -> remove_opaques typ | _ -> typ
let rec remove_mode_changes typ = let typ = repr typ in match typ . type_desc with | Tother_mode typ -> remove_mode_changes typ | _ -> typ
module Decl = struct let decl_id = ref 0 let next_id ( ) = incr decl_id ; ! decl_id let mk ~ name ~ params desc = incr decl_id ; let tdec_ret = Mk . ctor ~ mode ( : Ident . mode name ) 10000 ( Path . Pident name ) params in { tdec_params = params ; tdec_desc = desc ; tdec_id = ! decl_id ; tdec_ret } end
let report_error ppf = function | Mk_wrong_mode ( kind , typs , mode , typ ) -> fprintf ppf " [ @< hov > Internal error : Could not make a type % s from types ; @\ [ @< hov2 >% a ] ; @@\ The type % a was expected to have mode % a . ] " @ kind ( pp_print_list ~ pp_sep : pp_print_newline Debug_print . type_expr ) typs Debug_print . type_expr typ pp_mode mode | Mk_invalid ( kind , typs , typ ) -> fprintf ppf " [ @< hov > Internal error : Could not make a type % s from types ; @\ [ @< hov2 >% a ] ; @@\ The type % a was invalid . ] " @ kind ( pp_print_list ~ pp_sep : pp_print_newline Debug_print . type_expr_alts ) typs Debug_print . type_expr_alts typ
let ( ) = Location . register_error_of_exn ( function | Error ( loc , err ) -> Some ( Location . error_of_printer loc report_error err ) | _ -> None )
let shared_computation = Bonsai_web_ui_typeahead . Typeahead . create ( module Data ) ~ all_options ( : Value . return Data . all ) ~ placeholder " : Select a value " ~ to_string ( : Bonsai . Value . return Data . to_string ) ; ;
let view_computation = let % sub _ , view , _ = shared_computation in return view ; ;
let view_and_inject_computation = let % sub _ , view , inject = shared_computation in return ( Value . both view inject ) ; ;
let view_and_result_computation = let % sub result , view , _ = shared_computation in return ( Value . both view result ) ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; let before = [ % expect . output ] in Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string Data . Option_C ) ; Handle . show handle ; let after = [ % expect . output ] in Expect_test_patdiff . print_patdiff before after ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( module struct type incoming = Data . t option type t = Vdom . Node . t * ( Data . t option -> unit Ui_effect . t ) let view ( vdom , _ ) = let module V = ( val Result_spec . vdom Fn . id ) in V . view vdom ; ; let incoming ( _ , inject ) = inject end ) view_and_inject_computation in Handle . show handle ; let _before = [ % expect . output ] in Handle . do_actions handle [ Some Data . Option_A ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " -| value " " = +| value " = Option A " -| # value " " = +| # value " = Option A " onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] ; | Handle . do_actions handle [ None ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " -| value " = Option A " +| value " " = -| # value " = Option A " +| # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . sexp ( module struct type t = Vdom . Node . t * Data . t option let sexp_of_t ( _view , result ) = [ % sexp_of : Data . t option ] result end ) ) view_and_result_computation in Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : O " ; Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : C " ; Handle . show handle ; [ % expect { | ( Option_C ) } ] | ; ;
let shared_computation = Bonsai_web_ui_typeahead . Typeahead . create_multi ( module Data ) ~ all_options ( : Value . return Data . all ) ~ placeholder " : Select a value " ~ to_string : Data . to_string ~ split ( : String . split ~ on ' , ' ) : ; ;
let view_computation = let % sub _ , vdom , _ = shared_computation in return vdom ; ;
let view_and_set_computation = let % sub _ , vdom , set = shared_computation in return ( Value . both vdom set ) ; ;
let view_and_result_computation = let % sub result , vdom , _ = shared_computation in return ( Value . both vdom result ) ; ;
let input_value handle value = Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string value ) ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . store_view handle ; input_value handle Data . Option_B ; input_value handle Data . Option_C ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in input_value handle Data . Option_B ; input_value handle Data . Option_C ; Handle . store_view handle ; Handle . click_on handle ~ get_vdom : Fn . id ~ selector " [ : data - value = Option B ] " ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > </ datalist > < div class " = bonsai - web - ui - typeahead - pills " > < span tabindex " = 0 " data - value " = Option C " onclick onkeyup > Option C × </ span > </ div > </ div > } ] | ; ; let handle = Handle . create ( module struct type incoming = Data . Set . t type t = Vdom . Node . t * ( Data . Set . t -> unit Ui_effect . t ) let view ( vdom , _ ) = let module V = ( val Result_spec . vdom Fn . id ) in V . view vdom ; ; let incoming ( _ , inject ) = inject end ) view_and_set_computation in Handle . store_view handle ; Handle . do_actions handle [ Data . Set . of_list [ Data . Option_C ] ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . sexp ( module struct type t = Vdom . Node . t * Data . Set . t let sexp_of_t ( _view , result ) = [ % sexp_of : Data . Set . t ] result end ) ) view_and_result_computation in Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : b " ; Handle . show handle ; [ % expect { | ( Option_B ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : C " ; Handle . show handle ; [ % expect { | ( Option_B Option_C ) } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . store_view handle ; Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string Data . Option_A ^ " , " ^ Data . to_string Data . Option_B ) ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > -| < option value " = Option A " > Option A </ option > -| < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > +| < div class " = bonsai - web - ui - typeahead - pills " > +| < span tabindex " = 0 " data - value " = Option A " onclick onkeyup > Option A × </ span > +| < span tabindex " = 0 " data - value " = Option B " onclick onkeyup > Option B × </ span > +| </ div > </ div > } ] | ; ;
let preprocess ~ pp ~ ext text = let sourcefile = Filename . temp_file " caml " ext in begin try let oc = open_out_bin sourcefile in output_string oc text ; flush oc ; close_out oc with _ -> failwith " Preprocessing error " end ; let tmpfile = Filename . temp_file " camlpp " ext in let comm = Printf . sprintf " % s % s > % s " pp sourcefile tmpfile in if Ccomp . command comm <> 0 then begin Sys . remove sourcefile ; Sys . remove tmpfile ; failwith " Preprocessing error " end ; Sys . remove sourcefile ; tmpfile
let parse_pp ~ parse ~ wrap ~ ext text = match ! Clflags . preprocessor with None -> parse ( Lexing . from_string text ) | Some pp -> let tmpfile = preprocess ~ pp ~ ext text in let ast_magic = if ext = " . ml " then Config . ast_impl_magic_number else Config . ast_intf_magic_number in let ic = open_in_bin tmpfile in let ast = try let buffer = String . create ( String . length ast_magic ) in really_input ic buffer 0 ( String . length ast_magic ) ; if buffer = ast_magic then begin ignore ( input_value ic ) ; wrap ( input_value ic ) end else if String . sub buffer 0 9 = String . sub ast_magic 0 9 then raise Outdated_version else raise Exit with Outdated_version -> close_in ic ; Sys . remove tmpfile ; failwith " Ocaml and preprocessor have incompatible versions " | _ -> seek_in ic 0 ; parse ( Lexing . from_channel ic ) in close_in ic ; Sys . remove tmpfile ; ast
let nowarnings = ref false
let f txt = let error_messages = ref [ ] in let text = Jg_text . get_all txt . tw and env = ref ( Env . open_pers_signature " Pervasives " Env . initial ) in let tl , ew , end_message = Jg_message . formatted ~ title " : Warnings " ~ ppf : Format . err_formatter ( ) in Text . tag_remove txt . tw ~ tag " : error " ~ start : tstart ~ stop : tend ; txt . structure <- [ ] ; txt . type_info <- [ ] ; txt . signature <- [ ] ; txt . psignature <- [ ] ; ignore ( Stypes . get_info ( ) ) ; Clflags . annotations := true ; begin try if Filename . check_suffix txt . name " . mli " then let psign = parse_pp text ~ ext " . : mli " ~ parse : Parse . interface ~ wrap ( : fun x -> x ) in txt . psignature <- psign ; txt . signature <- Typemod . transl_signature ! env psign else let psl = parse_pp text ~ ext " . : ml " ~ parse : Parse . use_file ~ wrap ( : fun x -> [ Parsetree . Ptop_def x ] ) in List . iter psl ~ f : begin function Ptop_def pstr -> let str , sign , env ' = Typemod . type_structure ! env pstr Location . none in txt . structure <- txt . structure @ str ; txt . signature <- txt . signature @ sign ; env := env ' | Ptop_dir _ -> ( ) end ; txt . type_info <- Stypes . get_info ( ) ; with Lexer . Error _ | Syntaxerr . Error _ | Typecore . Error _ | Typemod . Error _ | Typeclass . Error _ | Typedecl . Error _ | Typetexp . Error _ | Includemod . Error _ | Env . Error _ | Ctype . Tags _ | Failure _ as exn -> txt . type_info <- Stypes . get_info ( ) ; let et , ew , end_message = Jg_message . formatted ~ title " : Error " ! ( ) in error_messages := et :: ! error_messages ; let range = match exn with Lexer . Error ( err , l ) -> Lexer . report_error Format . std_formatter err ; l | Syntaxerr . Error err -> Syntaxerr . report_error Format . std_formatter err ; begin match err with Syntaxerr . Unclosed ( l , _ , _ , _ ) -> l | Syntaxerr . Other l -> l end | Typecore . Error ( l , err ) -> Typecore . report_error Format . std_formatter err ; l | Typeclass . Error ( l , err ) -> Typeclass . report_error Format . std_formatter err ; l | Typedecl . Error ( l , err ) -> Typedecl . report_error Format . std_formatter err ; l | Typemod . Error ( l , err ) -> Typemod . report_error Format . std_formatter err ; l | Typetexp . Error ( l , err ) -> Typetexp . report_error Format . std_formatter err ; l | Includemod . Error errl -> Includemod . report_error Format . std_formatter errl ; Location . none | Env . Error err -> Env . report_error Format . std_formatter err ; Location . none | Ctype . Tags ( l , l ' ) -> Format . printf " In this program , @ variant constructors @ ` % s and ` % s @ have same hash value . . " @ l l ' ; Location . none | Failure s -> Format . printf " % s . . " @ s ; Location . none | _ -> assert false in end_message ( ) ; let s = range . loc_start . Lexing . pos_cnum in let e = range . loc_end . Lexing . pos_cnum in if s < e then Jg_text . tag_and_see txt . tw ~ start ( : tpos s ) ~ stop ( : tpos e ) ~ tag " : error " end ; end_message ( ) ; if ! nowarnings || Text . index ew ~ index : tend = ` Linechar ( 2 , 0 ) then destroy tl else begin error_messages := tl :: ! error_messages ; Text . configure ew ~ state ` : Disabled ; bind ew ~ events [ ` : Modified ( [ ` Double ] , ` ButtonReleaseDetail 1 ) ] ~ action ( : fun _ -> try let start , ende = Text . tag_nextrange ew ~ tag " : sel " ~ start ( : tpos 0 ) in let s = Text . get ew ~ start ( : start , [ ] ) ~ stop ( : ende , [ ] ) in let n = int_of_string s in Text . mark_set txt . tw ~ index ( : tpos n ) ~ mark " : insert " ; Text . see txt . tw ~ index ( ` : Mark " insert " , [ ] ) with _ -> ( ) ) end ; ! error_messages
type error = [ ` TypeMismatchError of string | ` UnboundRegularVarInsideBoxError of Location . t * string | Env . error ]
type ' e lerror = ( [ > error ] as ' e ) Location . located
let check_equal ty1 ty2 msg = Result . ok_if_true ( [ % equal : Type . t ] ty1 ty2 ) ~ error ( ` : TypeMismatchError msg )
let with_error_location loc r = Result . map_error r ~ f ( : fun e -> Location . locate ~ loc e )
let fail_in loc err = Result . fail @@ Location . locate ~ loc @@ err
let mk_unbound_regular_var_inside_box_error box_expr_loc var_loc var = let var_name = Id . R . to_string var in let msg = [ % string " regular variable " ( \$ var_name ) " \ is accessed in box expression \ ( ( $ Location . pp_column_range box_expr_loc ) ) at \ ( $ Location . pp_column_range var_loc ) " ] in fail_in var_loc @@ ` UnboundRegularVarInsideBoxError ( var_loc , msg )
let rec check_open delta gamma Location . { data = expr ; loc } typ = match expr with | Unit -> let exp_ty = PrettyPrinter . Str . of_type typ in with_error_location loc @@ check_equal typ Type . Unit [ % string " Expected $ exp_ty , but found Unit type " ] | Pair { e1 ; e2 } -> ( match typ with | Type . Prod { ty1 ; ty2 } -> let % map ( ) = check_open delta gamma e1 ty1 and ( ) = check_open delta gamma e2 ty2 in ( ) | _ -> let exp_ty = PrettyPrinter . Str . of_type typ in fail_in loc @@ ` TypeMismatchError [ % string " Expected $ exp_ty , but found product type " ] ) | Fst { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 ; ty2 = _ } -> with_error_location loc @@ check_equal typ ty1 " fst error : inferred type is different from the input one " | _ -> fail_in loc @@ ` TypeMismatchError " fst is applied to a non - product type " ) | Snd { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 = _ ; ty2 } -> with_error_location loc @@ check_equal typ ty2 " snd error : inferred type is different from the input one " | _ -> fail_in loc @@ ` TypeMismatchError " snd is applied to a non - product type " ) | Nat _ -> let exp_ty = PrettyPrinter . Str . of_type typ in with_error_location loc @@ check_equal typ Type . Nat [ % string " Expected $ exp_ty , but found Nat type " ] | BinOp { op = _ ; e1 ; e2 } -> let % map ( ) = check_open delta gamma e1 Type . Nat and ( ) = check_open delta gamma e2 Type . Nat in ( ) | VarR { idr } -> let % bind ty = with_error_location loc @@ Env . R . lookup gamma idr in with_error_location loc @@ check_equal typ ty " Unexpected regular variable type " | VarM { idm } -> let % bind ty = with_error_location loc @@ Env . M . lookup delta idm in with_error_location loc @@ check_equal typ ty " Unexpected modal variable type " | Fun { idr ; ty_id ; body } -> ( match typ with | Type . Arr { dom ; cod } -> let % bind ( ) = with_error_location loc @@ check_equal dom ty_id " Domain of arrow type is not the same as type of function \ parameter " in check_open delta ( Env . R . extend gamma idr dom ) body cod | _ -> fail_in loc @@ ` TypeMismatchError " Arrow type expected " ) | App { fe ; arge } -> ( let % bind ty = infer_open delta gamma fe in match ty with | Type . Arr { dom ; cod } -> let % bind ( ) = check_open delta gamma arge dom in with_error_location loc @@ check_equal typ cod " Unexpected function codomain " | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not an arrow type " ) | Box { e } -> ( match typ with | Type . Box { ty } -> ( match check_open delta Env . R . emp e ty with | Error { data = ` EnvUnboundRegularVarError ( var , _ ) ; loc = var_loc } when Result . is_ok ( Env . R . lookup gamma var ) -> mk_unbound_regular_var_inside_box_error loc var_loc var | x -> x ) | _ -> fail_in loc @@ ` TypeMismatchError " Error : unboxed type " ) | Let { idr ; bound ; body } -> let % bind ty = infer_open delta gamma bound in check_open delta ( Env . R . extend gamma idr ty ) body typ | Letbox { idm ; boxed ; body } -> ( let % bind ty = infer_open delta gamma boxed in match ty with | Type . Box { ty } -> check_open ( Env . M . extend delta idm ty ) gamma body typ | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not a box " ) | Match { matched ; zbranch ; pred ; sbranch } -> let % bind _ = check_open delta gamma matched Type . Nat in let % bind ty_empty = infer_open delta gamma zbranch in check_open delta ( Env . R . extend gamma pred Type . Nat ) sbranch ty_empty match expr with | Unit -> return Type . Unit | Pair { e1 ; e2 } -> let % map ty1 = infer_open delta gamma e1 and ty2 = infer_open delta gamma e2 in Type . Prod { ty1 ; ty2 } | Fst { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 ; ty2 = _ } -> return ty1 | _ -> fail_in loc @@ ` TypeMismatchError " fst is applied to a non - product type " ) | Snd { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 = _ ; ty2 } -> return ty2 | _ -> fail_in loc @@ ` TypeMismatchError " snd is applied to a non - product type " ) | Nat _ -> return Type . Nat | BinOp { op = _ ; e1 ; e2 } -> let % map ( ) = check_open delta gamma e1 Type . Nat and ( ) = check_open delta gamma e2 Type . Nat in Type . Nat | VarR { idr } -> with_error_location loc @@ Env . R . lookup gamma idr | VarM { idm } -> with_error_location loc @@ Env . M . lookup delta idm | Fun { idr ; ty_id ; body } -> let % map ty_body = infer_open delta ( Env . R . extend gamma idr ty_id ) body in Type . Arr { dom = ty_id ; cod = ty_body } | App { fe ; arge } -> ( let % bind ty = infer_open delta gamma fe in match ty with | Type . Arr { dom ; cod } -> let % bind ( ) = check_open delta gamma arge dom in return cod | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not an arrow type " ) | Box { e } -> let % map ty = match infer_open delta Env . R . emp e with | Error { data = ` EnvUnboundRegularVarError ( var , _ ) ; loc = var_loc } when Result . is_ok @@ Env . R . lookup gamma var -> mk_unbound_regular_var_inside_box_error loc var_loc var | x -> x in Type . Box { ty } | Let { idr ; bound ; body } -> let % bind ty = infer_open delta gamma bound in infer_open delta ( Env . R . extend gamma idr ty ) body | Letbox { idm ; boxed ; body } -> ( let % bind tyb = infer_open delta gamma boxed in match tyb with | Type . Box { ty } -> infer_open ( Env . M . extend delta idm ty ) gamma body | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not a box " ) | Match { matched ; zbranch ; pred ; sbranch } -> let % bind _ = check_open delta gamma matched Type . Nat in let % bind ty_zero = infer_open delta gamma zbranch in let % bind ty_succ = infer_open delta ( Env . R . extend gamma pred Type . Nat ) sbranch in let % bind ( ) = with_error_location loc @@ check_equal ty_zero ty_succ " All branches of pattern matching must have the same type " in return ty_zero
let check expr typ = check_open Env . M . emp Env . R . emp expr typ
let infer expr = infer_open Env . M . emp Env . R . emp expr
type method_type = typ list * typ
type method_env = method_type SM . t
type attribute_env = typ SM . t
type class_type = attribute_env * method_env
type class_env = class_type SM . t
type variable_env = typ SM . t
let error ( location : ' a Location . t ) ( msg : string ) = raise ( Error ( sprintf " % s :\ n % s " ( Error . positions ( Location . startpos location ) ( Location . endpos location ) ) msg ) )
let errors ( locations : ' a Location . t list ) ( msg : string ) = raise ( Error ( sprintf " % s % s " ( List . fold_right ( fun location acc -> sprintf " % s :\ n % s " ( Error . positions ( Location . startpos location ) ( Location . endpos location ) ) acc ) locations " " ) msg ) )
let lookup ( msg : string ) ( id : identifier ) ( env : ' a SM . t ) = try SM . find ( Location . content id ) env with Not_found -> error id ( sprintf " % s % s is undefined " msg ( Location . content id ) )
let vlookup : identifier -> variable_env -> typ = lookup " variable "
let mlookup : identifier -> method_env -> method_type = lookup " method "
let alookup : identifier -> attribute_env -> typ = lookup " attribute "
let clookup : identifier -> class_env -> class_type = lookup " class "
let rec compatible ( typ1 : typ ) ( typ2 : typ ) ( instanceof : identifier -> identifier -> bool ) : bool = match typ1 , typ2 with | TypInt , TypInt | TypBool , TypBool | TypIntArray , TypIntArray -> true | Typ t1 , Typ t2 -> instanceof t1 t2 | _ , _ -> false
let rec type_to_string : typ -> string = function | TypInt -> " integer " | TypBool -> " boolean " | TypIntArray -> " int [ ] " | Typ t -> Location . content t
let rec typecheck_call ( cenv : class_env ) ( venv : variable_env ) ( vinit : S . t ) ( instanceof : identifier -> identifier -> bool ) ( o : expression ) ( callee : identifier ) ( expressions : expression list ) : typ = let o_type = typecheck_expression cenv venv vinit instanceof o in match o_type with | Typ t -> begin let _ , method_env = clookup t cenv in let ( formals : typ list ) , ( result : typ ) = mlookup callee method_env in try List . iter2 ( typecheck_expression_expecting cenv venv vinit instanceof ) formals expressions ; result with Invalid_argument _ -> error callee ( sprintf " Invalid function call , expected % d arguments , got % d " ( List . length formals ) ( List . length expressions ) ) end | _ -> error o ( sprintf " A class is expected , got % s " ( type_to_string o_type ) ) ( instanceof : identifier -> identifier -> bool ) ( typ1 : typ ) ( e : expression ) : unit = let typ2 = typecheck_expression cenv venv vinit instanceof e in if not ( compatible typ2 typ1 instanceof ) then error e ( sprintf " Type mismatch , expected % s , got % s " ( type_to_string typ1 ) ( type_to_string typ2 ) ) ( instanceof : identifier -> identifier -> bool ) ( e : expression ) : typ = match Location . content e with | EConst ( ConstBool _ ) -> TypBool | EConst ( ConstInt _ ) -> TypInt | EGetVar v -> let typ = vlookup v venv in let v ' = Location . content v in if not ( S . mem v ' vinit ) then error v ( sprintf " Variable % s has not been initialized " v ' ) ; typ | EUnOp ( op , e ) -> let expected , returned = match op with | UOpNot -> TypBool , TypBool in typecheck_expression_expecting cenv venv vinit instanceof expected e ; returned | EBinOp ( op , e1 , e2 ) -> let expected , returned = match op with | OpAdd | OpSub | OpMul -> TypInt , TypInt | OpLt -> TypInt , TypBool | OpAnd -> TypBool , TypBool in typecheck_expression_expecting cenv venv vinit instanceof expected e1 ; typecheck_expression_expecting cenv venv vinit instanceof expected e2 ; returned | EMethodCall ( o , callee , expressions ) -> typecheck_call cenv venv vinit instanceof o callee expressions | EArrayGet ( earray , eindex ) -> typecheck_expression_expecting cenv venv vinit instanceof TypInt eindex ; typecheck_expression_expecting cenv venv vinit instanceof TypIntArray earray ; TypInt | EArrayAlloc elength -> typecheck_expression_expecting cenv venv vinit instanceof TypInt elength ; TypIntArray | EArrayLength earray -> typecheck_expression_expecting cenv venv vinit instanceof TypIntArray earray ; TypInt | EThis -> vlookup ( Location . make ( Location . startpos e ) ( Location . endpos e ) " this " ) venv | EObjectAlloc id -> clookup id cenv |> ignore ; Typ id
let rec typecheck_instruction ( cenv : class_env ) ( venv : variable_env ) ( vinit : S . t ) ( instanceof : identifier -> identifier -> bool ) ( inst : instruction ) : S . t = match inst with | ISetVar ( v , e ) -> let vinit = S . add ( Location . content v ) vinit in typecheck_expression_expecting cenv venv vinit instanceof ( vlookup v venv ) e ; vinit | IArraySet ( earray , eindex , evalue ) -> typecheck_expression_expecting cenv venv vinit instanceof TypIntArray ( Location . make ( Location . startpos earray ) ( Location . endpos earray ) ( EGetVar earray ) ) ; typecheck_expression_expecting cenv venv vinit instanceof TypInt eindex ; typecheck_expression_expecting cenv venv vinit instanceof TypInt evalue ; vinit | IBlock instructions -> List . fold_left ( fun vinit inst -> typecheck_instruction cenv venv vinit instanceof inst ) vinit instructions | IIf ( cond , ithen , ielse ) -> typecheck_expression_expecting cenv venv vinit instanceof TypBool cond ; let vinit1 = typecheck_instruction cenv venv vinit instanceof ithen in let vinit2 = typecheck_instruction cenv venv vinit instanceof ielse in S . inter vinit1 vinit2 | IWhile ( cond , ibody ) -> typecheck_expression_expecting cenv venv vinit instanceof TypBool cond ; typecheck_instruction cenv venv vinit instanceof ibody | ISyso e -> typecheck_expression_expecting cenv venv vinit instanceof TypInt e ; vinit
let occurrences ( x : string ) ( bindings : ( identifier * ' a ) list ) : identifier list = List . map fst ( List . filter ( fun ( id , _ ) -> x = Location . content id ) bindings )
let map_of_association_list ( entity : string ) ( bindings : ( identifier * ' a ) list ) : ' a SM . t = try SM . of_association_list ( List . map ( fun ( id , data ) -> ( Location . content id , data ) ) bindings ) with SM . Duplicate x -> errors ( occurrences x bindings ) ( sprintf " % s % s is declared more than once " entity x )
let variable_map ( decls : ( identifier * typ ) list ) : variable_env = map_of_association_list " Variable " decls
let method_map ( decls : ( identifier * method_type ) list ) : method_env = map_of_association_list " Method " decls
let typecheck_method ( cenv : class_env ) ( venv : variable_env ) ( instanceof : identifier -> identifier -> bool ) ( m : metho ) : unit = let formals = m . formals and locals = m . locals in let mformals = variable_map formals and mlocals = variable_map locals in begin try let x = StringSet . choose ( StringSet . inter ( SM . domain mformals ) ( SM . domain mlocals ) ) in errors ( occurrences x formals @ occurrences x locals ) " A formal parameter and a local variable cannot carry the same name " with Not_found -> ( ) end ; let venv = SM . addm mformals venv |> SM . addm mlocals in let vinit = S . diff ( SM . domain venv ) ( SM . domain mlocals ) in let vinit = typecheck_instruction cenv venv vinit instanceof ( IBlock m . body ) in typecheck_expression_expecting cenv venv vinit instanceof m . result m . return
let typecheck_class ( cenv : class_env ) ( instanceof : identifier -> identifier -> bool ) ( ( name , c ) : identifier * clas ) : unit = let attribute_env , _ = clookup name cenv in let venv = SM . add " this " ( Typ name ) attribute_env in List . iter ( typecheck_method cenv venv instanceof ) ( List . map snd c . methods )
let extract_method_type ( m : metho ) : method_type = ( List . map snd m . formals , m . result )
let extract_class_type ( c : clas ) : class_type = ( variable_map c . attributes , method_map ( List . map ( fun ( id , m ) -> ( id , extract_method_type m ) ) c . methods ) )
let class_map ( decls : ( identifier * clas ) list ) : clas SM . t = map_of_association_list " Class " decls
let create_instanceof ( cmap : clas SM . t ) : identifier -> identifier -> bool = let rec instanceof id1 id2 = if id1 = id2 then true else try match ( SM . find id1 cmap ) . extends with | None -> false | Some id3 -> instanceof ( Location . content id3 ) id2 with Not_found -> false in fun id1 id2 -> instanceof ( Location . content id1 ) ( Location . content id2 )
let add_method ( cmap : clas SM . t ) ( instanceof : identifier -> identifier -> bool ) : clas SM . t = let test_compatible_signature ( ( name , m ) : identifier * metho ) ( ( name ' , m ' ) : identifier * metho ) : unit = let typecheck_params ( typ : typ ) ( typ ' : typ ) : unit = if not ( compatible typ typ ' ( fun t1 t2 -> Location . content t1 = Location . content t2 ) ) then errors [ name ; name ' ] ( sprintf " Type mismatch in params of overriden method , expected % s , got % s " ( type_to_string typ ) ( type_to_string typ ' ) ) in let typecheck_result ( typ : typ ) ( typ ' : typ ) : unit = if not ( compatible typ ' typ instanceof ) then errors [ name ; name ' ] ( sprintf " Type mismatch in result of overriden method , expected % s , got % s " ( type_to_string typ ) ( type_to_string typ ' ) ) in let formals , result = extract_method_type m and formals ' , result ' = extract_method_type m ' in try List . iter2 typecheck_params formals formals ' ; typecheck_result result result ' with Invalid_argument _ -> errors [ name ; name ' ] ( sprintf " A function that overrides another one must have the same number of parameters " ) in let rec complete ( parent : identifier option ) ( c : clas ) : clas = match parent with | None -> c | Some id -> let c ' = SM . find ( Location . content id ) cmap in complete c ' . extends { c with attributes = ( List . filter ( fun ( name , _ ) -> not ( List . exists ( fun ( name ' , _ ) -> Location . content name = Location . content name ' ) c . attributes ) ) c ' . attributes ) @ c . attributes ; methods = ( List . filter ( fun ( name , m ) -> try List . find ( fun ( name ' , _ ) -> Location . content name = Location . content name ' ) c . methods |> test_compatible_signature ( name , m ) ; false with Not_found -> true ) c ' . methods ) @ c . methods } in SM . map ( fun c -> complete c . extends c ) cmap
let typecheck_program ( p : program ) : unit = let cmap = class_map p . defs in let instanceof = create_instanceof cmap in let cenv = add_method cmap instanceof |> SM . map extract_class_type in List . iter ( typecheck_class cenv instanceof ) p . defs ; let venv = SM . singleton " this " ( Typ p . name ) in typecheck_instruction cenv venv S . empty instanceof p . main |> ignore