text
stringlengths
12
786k
let check_abbrev env sdecl ( id , decl ) = check_coherence env sdecl . ptype_loc ( Path . Pident id ) decl
let check_well_founded env loc path to_check ty = let visited = ref TypeMap . empty in let rec check ty0 parents ty = let ty = Btype . repr ty in if TypeSet . mem ty parents then begin if match ty0 . desc with | Tconstr ( p , _ , _ ) -> Path . same p path | _ -> false then raise ( Error ( loc , Recursive_abbrev ( Path . name path ) ) ) else raise ( Error ( loc , Cycle_in_def ( Path . name path , ty0 ) ) ) end ; let ( fini , parents ) = try let prev = TypeMap . find ty ! visited in if TypeSet . subset parents prev then ( true , parents ) else ( false , TypeSet . union parents prev ) with Not_found -> ( false , parents ) in if fini then ( ) else let rec_ok = match ty . desc with Tconstr ( p , _ , _ ) -> ! Clflags . recursive_types && Ctype . is_contractive env p | Tobject _ | Tvariant _ -> true | _ -> ! Clflags . recursive_types in let visited ' = TypeMap . add ty parents ! visited in let arg_exn = try visited := visited ' ; let parents = if rec_ok then TypeSet . empty else TypeSet . add ty parents in Btype . iter_type_expr ( check ty0 parents ) ty ; None with e -> visited := visited ' ; Some e in match ty . desc with | Tconstr ( p , _ , _ ) when arg_exn <> None || to_check p -> if to_check p then Option . iter raise arg_exn else Btype . iter_type_expr ( check ty0 TypeSet . empty ) ty ; begin try let ty ' = Ctype . try_expand_once_opt env ty in let ty0 = if TypeSet . is_empty parents then ty else ty0 in check ty0 ( TypeSet . add ty parents ) ty ' with Ctype . Cannot_expand -> Option . iter raise arg_exn end | _ -> Option . iter raise arg_exn in let snap = Btype . snapshot ( ) in try Ctype . wrap_trace_gadt_instances env ( check ty TypeSet . empty ) ty with Ctype . Unify _ -> Btype . backtrack snap
let check_well_founded_manifest env loc path decl = if decl . type_manifest = None then ( ) else let args = List . map ( fun _ -> Ctype . newvar ( ) ) decl . type_params in check_well_founded env loc path ( Path . same path ) ( Ctype . newconstr path args )
let check_well_founded_decl env loc path decl to_check = let open Btype in let it = { type_iterators with it_type_expr = ( fun _ -> check_well_founded env loc path to_check ) } in it . it_type_declaration it ( Ctype . generic_instance_declaration decl )
let check_recursion env loc path decl to_check = if decl . type_params = [ ] then ( ) else let visited = ref [ ] in let rec check_regular cpath args prev_exp ty = let ty = Ctype . repr ty in if not ( List . memq ty ! visited ) then begin visited := ty :: ! visited ; match ty . desc with | Tconstr ( path ' , args ' , _ ) -> if Path . same path path ' then begin if not ( Ctype . equal env false args args ' ) then raise ( Error ( loc , Parameters_differ ( cpath , ty , Ctype . newconstr path args ) ) ) end else if to_check path ' && not ( List . mem path ' prev_exp ) then begin try let ( params0 , body0 , _ ) = Env . find_type_expansion path ' env in let ( params , body ) = Ctype . instance_parameterized_type params0 body0 in begin try List . iter2 ( Ctype . unify env ) params args ' with Ctype . Unify _ -> raise ( Error ( loc , Constraint_failed ( ty , Ctype . newconstr path ' params0 ) ) ) ; end ; check_regular path ' args ( path ' :: prev_exp ) body with Not_found -> ( ) end ; List . iter ( check_regular cpath args prev_exp ) args ' | Tpoly ( ty , tl ) -> let ( _ , ty ) = Ctype . instance_poly ~ keep_names : true false tl ty in check_regular cpath args prev_exp ty | _ -> Btype . iter_type_expr ( check_regular cpath args prev_exp ) ty end in Option . iter ( fun body -> let ( args , body ) = Ctype . instance_parameterized_type ~ keep_names : true decl . type_params body in check_regular path args [ ] body ) decl . type_manifest
let check_abbrev_recursion env id_loc_list to_check tdecl = let decl = tdecl . typ_type in let id = tdecl . typ_id in check_recursion env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl to_check
let check_duplicates sdecl_list = let labels = Hashtbl . create 7 and constrs = Hashtbl . create 7 in List . iter ( fun sdecl -> match sdecl . ptype_kind with Ptype_variant cl -> List . iter ( fun pcd -> try let name ' = Hashtbl . find constrs pcd . pcd_name . txt in Location . prerr_warning pcd . pcd_loc ( Warnings . Duplicate_definitions ( " constructor " , pcd . pcd_name . txt , name ' , sdecl . ptype_name . txt ) ) with Not_found -> Hashtbl . add constrs pcd . pcd_name . txt sdecl . ptype_name . txt ) cl | Ptype_record fl -> List . iter ( fun { pld_name = cname ; pld_loc = loc } -> try let name ' = Hashtbl . find labels cname . txt in Location . prerr_warning loc ( Warnings . Duplicate_definitions ( " label " , cname . txt , name ' , sdecl . ptype_name . txt ) ) with Not_found -> Hashtbl . add labels cname . txt sdecl . ptype_name . txt ) fl | Ptype_abstract -> ( ) | Ptype_open -> ( ) ) sdecl_list
let name_recursion sdecl id decl = match decl with | { type_kind = Type_abstract ; type_manifest = Some ty ; type_private = Private ; } when is_fixed_type sdecl -> let ty = Ctype . repr ty in let ty ' = Btype . newty2 ty . level ty . desc in if Ctype . deep_occur ty ty ' then let td = Tconstr ( Path . Pident id , decl . type_params , ref Mnil ) in Btype . link_type ty ( Btype . newty2 ty . level td ) ; { decl with type_manifest = Some ty ' } else decl | _ -> decl
let name_recursion_decls sdecls decls = List . map2 ( fun sdecl ( id , decl ) -> ( id , name_recursion sdecl id decl ) ) sdecls decls
let check_redefined_unit ( td : Parsetree . type_declaration ) = let open Parsetree in let is_unit_constructor cd = cd . pcd_name . txt = " ( ) " in match td with | { ptype_name = { txt = name } ; ptype_manifest = None ; ptype_kind = Ptype_variant [ cd ] } when is_unit_constructor cd -> Location . prerr_warning td . ptype_loc ( Warnings . Redefining_unit name ) | _ -> ( )
let add_types_to_env decls env = List . fold_right ( fun ( id , decl ) env -> add_type ~ check : true id decl env ) decls env
let transl_type_decl env rec_flag sdecl_list = List . iter check_redefined_unit sdecl_list ; let fixed_types = List . filter is_fixed_type sdecl_list in let sdecl_list = List . map ( fun sdecl -> let ptype_name = let loc = { sdecl . ptype_name . loc with Location . loc_ghost = true } in mkloc ( sdecl . ptype_name . txt " ^# row " ) loc in let ptype_kind = Ptype_abstract in let ptype_manifest = None in let ptype_loc = { sdecl . ptype_loc with Location . loc_ghost = true } in { sdecl with ptype_name ; ptype_kind ; ptype_manifest ; ptype_loc } ) fixed_types @ sdecl_list in let scope = Ctype . create_scope ( ) in let id_list = List . map ( fun sdecl -> Ident . create_scoped ~ scope sdecl . ptype_name . txt ) sdecl_list in Ctype . begin_def ( ) ; let temp_env = List . fold_left2 ( enter_type rec_flag ) env sdecl_list id_list in let current_slot = ref None in let warn_unused = Warnings . is_active ( Warnings . Unused_type_declaration " " ) in let id_slots id = match rec_flag with | Asttypes . Recursive when warn_unused -> let slot = ref [ ] in let td = Env . find_type ( Path . Pident id ) temp_env in let name = Ident . name id in Env . set_type_used_callback name td ( fun old_callback -> match ! current_slot with | Some slot -> slot := ( name , td ) :: ! slot | None -> List . iter ( fun ( name , d ) -> Env . mark_type_used name d ) ( get_ref slot ) ; old_callback ( ) ) ; id , Some slot | Asttypes . Recursive | Asttypes . Nonrecursive -> id , None in let transl_declaration name_sdecl ( id , slot ) = current_slot := slot ; Builtin_attributes . warning_scope name_sdecl . ptype_attributes ( fun ( ) -> transl_declaration temp_env name_sdecl id ) in let tdecls = List . map2 transl_declaration sdecl_list ( List . map id_slots id_list ) in let decls = List . map ( fun tdecl -> ( tdecl . typ_id , tdecl . typ_type ) ) tdecls in current_slot := None ; check_duplicates sdecl_list ; let new_env = add_types_to_env decls env in begin match rec_flag with | Asttypes . Nonrecursive -> ( ) | Asttypes . Recursive -> List . iter2 ( fun id sdecl -> update_type temp_env new_env id sdecl . ptype_loc ) id_list sdecl_list end ; Ctype . end_def ( ) ; List . iter ( fun ( _ , decl ) -> generalize_decl decl ) decls ; let id_loc_list = List . map2 ( fun id sdecl -> ( id , sdecl . ptype_loc ) ) id_list sdecl_list in List . iter ( fun ( id , decl ) -> check_well_founded_manifest new_env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl ) decls ; let to_check = function Path . Pident id -> List . mem_assoc id id_loc_list | _ -> false in List . iter ( fun ( id , decl ) -> check_well_founded_decl new_env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl to_check ) decls ; List . iter ( check_abbrev_recursion new_env id_loc_list to_check ) tdecls ; List . iter2 ( fun sdecl tdecl -> let decl = tdecl . typ_type in match Ctype . closed_type_decl decl with Some ty -> raise ( Error ( sdecl . ptype_loc , Unbound_type_var ( ty , decl ) ) ) | None -> ( ) ) sdecl_list tdecls ; List . iter2 ( check_constraints new_env ) sdecl_list decls ; let decls = try decls |> name_recursion_decls sdecl_list |> Typedecl_variance . update_decls env sdecl_list |> Typedecl_immediacy . update_decls env with | Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) | Typedecl_immediacy . Error ( loc , err ) -> raise ( Error ( loc , Immediacy err ) ) in let final_env = add_types_to_env decls env in List . iter2 ( check_abbrev final_env ) sdecl_list decls ; let final_decls = List . map2 ( fun tdecl ( _id2 , decl ) -> { tdecl with typ_type = decl } ) tdecls decls in ( final_decls , final_env )
let transl_extension_constructor env type_path type_params typext_params priv sext = let scope = Ctype . create_scope ( ) in let id = Ident . create_scoped ~ scope sext . pext_name . txt in let args , ret_type , kind = match sext . pext_kind with Pext_decl ( sargs , sret_type ) -> let targs , tret_type , args , ret_type , _ = make_constructor env type_path typext_params sargs sret_type in args , ret_type , Text_decl ( targs , tret_type ) | Pext_rebind lid -> let usage = if priv = Public then Env . Positive else Env . Privatize in let cdescr = Env . lookup_constructor ~ loc : lid . loc usage lid . txt env in let ( args , cstr_res ) = Ctype . instance_constructor cdescr in let res , ret_type = if cdescr . cstr_generalized then let params = Ctype . instance_list type_params in let res = Ctype . newconstr type_path params in let ret_type = Some ( Ctype . newconstr type_path params ) in res , ret_type else ( Ctype . newconstr type_path typext_params ) , None in begin try Ctype . unify env cstr_res res with Ctype . Unify trace -> raise ( Error ( lid . loc , Rebind_wrong_type ( lid . txt , env , trace ) ) ) end ; if not cdescr . cstr_generalized then begin let vars = Ctype . free_variables ( Btype . newgenty ( Ttuple args ) ) in List . iter ( function { desc = Tvar ( Some " _ " ) } as ty -> if List . memq ty vars then ty . desc <- Tvar None | _ -> ( ) ) typext_params end ; let cstr_type_path , cstr_type_params = match cdescr . cstr_res . desc with Tconstr ( p , _ , _ ) -> let decl = Env . find_type p env in p , decl . type_params | _ -> assert false in let cstr_types = ( Btype . newgenty ( Tconstr ( cstr_type_path , cstr_type_params , ref Mnil ) ) ) :: cstr_type_params in let ext_types = ( Btype . newgenty ( Tconstr ( type_path , type_params , ref Mnil ) ) ) :: type_params in if not ( Ctype . equal env true cstr_types ext_types ) then raise ( Error ( lid . loc , Rebind_mismatch ( lid . txt , cstr_type_path , type_path ) ) ) ; begin match cdescr . cstr_private , priv with Private , Public -> raise ( Error ( lid . loc , Rebind_private lid . txt ) ) | _ -> ( ) end ; let path = match cdescr . cstr_tag with Cstr_extension ( path , _ ) -> path | _ -> assert false in let args = match cdescr . cstr_inlined with | None -> Types . Cstr_tuple args | Some decl -> let tl = match args with | [ { desc = Tconstr ( _ , tl , _ ) } ] -> tl | _ -> assert false in let decl = Ctype . instance_declaration decl in assert ( List . length decl . type_params = List . length tl ) ; List . iter2 ( Ctype . unify env ) decl . type_params tl ; let lbls = match decl . type_kind with | Type_record ( lbls , Record_extension _ ) -> lbls | _ -> assert false in Types . Cstr_record lbls in args , ret_type , Text_rebind ( path , lid ) in let ext = { ext_type_path = type_path ; ext_type_params = typext_params ; ext_args = args ; ext_ret_type = ret_type ; ext_private = priv ; Types . ext_loc = sext . pext_loc ; Types . ext_attributes = sext . pext_attributes ; } in { ext_id = id ; ext_name = sext . pext_name ; ext_type = ext ; ext_kind = kind ; Typedtree . ext_loc = sext . pext_loc ; Typedtree . ext_attributes = sext . pext_attributes ; }
let transl_extension_constructor env type_path type_params typext_params priv sext = Builtin_attributes . warning_scope sext . pext_attributes ( fun ( ) -> transl_extension_constructor env type_path type_params typext_params priv sext )
let transl_type_extension extend env loc styext = reset_type_variables ( ) ; Ctype . begin_def ( ) ; let type_path , type_decl = let lid = styext . ptyext_path in Env . lookup_type ~ loc : lid . loc lid . txt env in begin match type_decl . type_kind with | Type_open -> begin match type_decl . type_private with | Private when extend -> begin match List . find ( function { pext_kind = Pext_decl _ } -> true | { pext_kind = Pext_rebind _ } -> false ) styext . ptyext_constructors with | { pext_loc } -> raise ( Error ( pext_loc , Cannot_extend_private_type type_path ) ) | exception Not_found -> ( ) end | _ -> ( ) end | _ -> raise ( Error ( loc , Not_extensible_type type_path ) ) end ; let type_variance = List . map ( fun v -> let ( co , cn ) = Variance . get_upper v in ( not cn , not co , false ) ) type_decl . type_variance in let err = if type_decl . type_arity <> List . length styext . ptyext_params then Some Includecore . Arity else if List . for_all2 ( fun ( c1 , n1 , _ ) ( c2 , n2 , _ ) -> ( not c2 || c1 ) && ( not n2 || n1 ) ) type_variance ( Typedecl_variance . variance_of_params styext . ptyext_params ) then None else Some Includecore . Variance in begin match err with | None -> ( ) | Some err -> raise ( Error ( loc , Extension_mismatch ( type_path , err ) ) ) end ; let ttype_params = make_params env styext . ptyext_params in let type_params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) ttype_params in List . iter2 ( Ctype . unify_var env ) ( Ctype . instance_list type_decl . type_params ) type_params ; let constructors = List . map ( transl_extension_constructor env type_path type_decl . type_params type_params styext . ptyext_private ) styext . ptyext_constructors in Ctype . end_def ( ) ; List . iter Ctype . generalize type_params ; List . iter ( fun ext -> Btype . iter_type_expr_cstr_args Ctype . generalize ext . ext_type . ext_args ; Option . iter Ctype . generalize ext . ext_type . ext_ret_type ) constructors ; List . iter ( fun ext -> match Ctype . closed_extension_constructor ext . ext_type with Some ty -> raise ( Error ( ext . ext_loc , Unbound_type_var_ext ( ty , ext . ext_type ) ) ) | None -> ( ) ) constructors ; List . iter ( fun ext -> try Typedecl_variance . check_variance_extension env type_decl ext ( type_variance , loc ) with Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) ) constructors ; let newenv = List . fold_left ( fun env ext -> Env . add_extension ~ check : true ext . ext_id ext . ext_type env ) env constructors in let tyext = { tyext_path = type_path ; tyext_txt = styext . ptyext_path ; tyext_params = ttype_params ; tyext_constructors = constructors ; tyext_private = styext . ptyext_private ; tyext_loc = styext . ptyext_loc ; tyext_attributes = styext . ptyext_attributes ; } in ( tyext , newenv )
let transl_type_extension extend env loc styext = Builtin_attributes . warning_scope styext . ptyext_attributes ( fun ( ) -> transl_type_extension extend env loc styext )
let transl_exception env sext = reset_type_variables ( ) ; Ctype . begin_def ( ) ; let ext = transl_extension_constructor env Predef . path_exn [ ] [ ] Asttypes . Public sext in Ctype . end_def ( ) ; Btype . iter_type_expr_cstr_args Ctype . generalize ext . ext_type . ext_args ; Option . iter Ctype . generalize ext . ext_type . ext_ret_type ; begin match Ctype . closed_extension_constructor ext . ext_type with Some ty -> raise ( Error ( ext . ext_loc , Unbound_type_var_ext ( ty , ext . ext_type ) ) ) | None -> ( ) end ; let newenv = Env . add_extension ~ check : true ext . ext_id ext . ext_type env in ext , newenv
let transl_type_exception env t = Builtin_attributes . check_no_alert t . ptyexn_attributes ; let contructor , newenv = Builtin_attributes . warning_scope t . ptyexn_attributes ( fun ( ) -> transl_exception env t . ptyexn_constructor ) in { tyexn_constructor = contructor ; tyexn_loc = t . ptyexn_loc ; tyexn_attributes = t . ptyexn_attributes } , newenv
type native_repr_attribute = | Native_repr_attr_absent | Native_repr_attr_present of native_repr_kind
let get_native_repr_attribute attrs ~ global_repr = match Attr_helper . get_no_payload_attribute [ " unboxed " ; " ocaml . unboxed " ] attrs , Attr_helper . get_no_payload_attribute [ " untagged " ; " ocaml . untagged " ] attrs , global_repr with | None , None , None -> Native_repr_attr_absent | None , None , Some repr -> Native_repr_attr_present repr | Some _ , None , None -> Native_repr_attr_present Unboxed | None , Some _ , None -> Native_repr_attr_present Untagged | Some { Location . loc } , _ , _ | _ , Some { Location . loc } , _ -> raise ( Error ( loc , Multiple_native_repr_attributes ) )
let native_repr_of_type env kind ty = match kind , ( Ctype . expand_head_opt env ty ) . desc with | Untagged , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int -> Some Untagged_int | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_float -> Some Unboxed_float | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int32 -> Some ( Unboxed_integer Pint32 ) | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int64 -> Some ( Unboxed_integer Pint64 ) | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_nativeint -> Some ( Unboxed_integer Pnativeint ) | _ -> None
let error_if_has_deep_native_repr_attributes core_type = let open Ast_iterator in let this_iterator = { default_iterator with typ = fun iterator core_type -> begin match get_native_repr_attribute core_type . ptyp_attributes ~ global_repr : None with | Native_repr_attr_present kind -> raise ( Error ( core_type . ptyp_loc , Deep_unbox_or_untag_attribute kind ) ) | Native_repr_attr_absent -> ( ) end ; default_iterator . typ iterator core_type } in default_iterator . typ this_iterator core_type
let make_native_repr env core_type ty ~ global_repr = error_if_has_deep_native_repr_attributes core_type ; match get_native_repr_attribute core_type . ptyp_attributes ~ global_repr with | Native_repr_attr_absent -> Same_as_ocaml_repr | Native_repr_attr_present kind -> begin match native_repr_of_type env kind ty with | None -> raise ( Error ( core_type . ptyp_loc , Cannot_unbox_or_untag_type kind ) ) | Some repr -> repr end
let rec parse_native_repr_attributes env core_type ty ~ global_repr = match core_type . ptyp_desc , ( Ctype . repr ty ) . desc , get_native_repr_attribute core_type . ptyp_attributes ~ global_repr : None with | Ptyp_arrow _ , Tarrow _ , Native_repr_attr_present kind -> raise ( Error ( core_type . ptyp_loc , Cannot_unbox_or_untag_type kind ) ) | Ptyp_arrow ( _ , ct1 , ct2 ) , Tarrow ( _ , t1 , t2 , _ ) , _ -> let repr_arg = make_native_repr env ct1 t1 ~ global_repr in let repr_args , repr_res = parse_native_repr_attributes env ct2 t2 ~ global_repr in ( repr_arg :: repr_args , repr_res ) | Ptyp_arrow _ , _ , _ | _ , Tarrow _ , _ -> assert false | _ -> ( [ ] , make_native_repr env core_type ty ~ global_repr )
let check_unboxable env loc ty = let check_type acc ty : Path . Set . t = let ty = Ctype . repr ( Ctype . expand_head_opt env ty ) in try match ty . desc with | Tconstr ( p , _ , _ ) -> let tydecl = Env . find_type p env in if tydecl . type_unboxed . default then Path . Set . add p acc else acc | _ -> acc with Not_found -> acc in let all_unboxable_types = Btype . fold_type_expr check_type Path . Set . empty ty in Path . Set . fold ( fun p ( ) -> Location . prerr_warning loc ( Warnings . Unboxable_type_in_prim_decl ( Path . name p ) ) ) all_unboxable_types ( )
let transl_value_decl env loc valdecl = let cty = Typetexp . transl_type_scheme env valdecl . pval_type in let ty = cty . ctyp_type in let v = match valdecl . pval_prim with [ ] when Env . is_in_signature env -> { val_type = ty ; val_kind = Val_reg ; Types . val_loc = loc ; val_attributes = valdecl . pval_attributes } | [ ] -> raise ( Error ( valdecl . pval_loc , Val_in_structure ) ) | _ -> let global_repr = match get_native_repr_attribute valdecl . pval_attributes ~ global_repr : None with | Native_repr_attr_present repr -> Some repr | Native_repr_attr_absent -> None in let native_repr_args , native_repr_res = parse_native_repr_attributes env valdecl . pval_type ty ~ global_repr in let prim = Primitive . parse_declaration valdecl ~ native_repr_args ~ native_repr_res in if prim . prim_arity = 0 && ( prim . prim_name = " " || prim . prim_name . [ 0 ] <> ' ' ) % then raise ( Error ( valdecl . pval_type . ptyp_loc , Null_arity_external ) ) ; if ! Clflags . native_code && prim . prim_arity > 5 && prim . prim_native_name = " " then raise ( Error ( valdecl . pval_type . ptyp_loc , Missing_native_external ) ) ; check_unboxable env loc ty ; { val_type = ty ; val_kind = Val_prim prim ; Types . val_loc = loc ; val_attributes = valdecl . pval_attributes } in let ( id , newenv ) = Env . enter_value valdecl . pval_name . txt v env ~ check ( : fun s -> Warnings . Unused_value_declaration s ) in let desc = { val_id = id ; val_name = valdecl . pval_name ; val_desc = cty ; val_val = v ; val_prim = valdecl . pval_prim ; val_loc = valdecl . pval_loc ; val_attributes = valdecl . pval_attributes ; } in desc , newenv
let transl_value_decl env loc valdecl = Builtin_attributes . warning_scope valdecl . pval_attributes ( fun ( ) -> transl_value_decl env loc valdecl )
let transl_with_constraint env id row_path orig_decl sdecl = Env . mark_type_used ( Ident . name id ) orig_decl ; reset_type_variables ( ) ; Ctype . begin_def ( ) ; let tparams = make_params env sdecl . ptype_params in let params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) tparams in let orig_decl = Ctype . instance_declaration orig_decl in let arity_ok = List . length params = orig_decl . type_arity in if arity_ok then List . iter2 ( Ctype . unify_var env ) params orig_decl . type_params ; let constraints = List . map ( function ( ty , ty ' , loc ) -> try let cty = transl_simple_type env false ty in let cty ' = transl_simple_type env false ty ' in let ty = cty . ctyp_type in let ty ' = cty ' . ctyp_type in Ctype . unify env ty ty ' ; ( cty , cty ' , loc ) with Ctype . Unify tr -> raise ( Error ( loc , Inconsistent_constraint ( env , tr ) ) ) ) sdecl . ptype_cstrs in let no_row = not ( is_fixed_type sdecl ) in let ( tman , man ) = match sdecl . ptype_manifest with None -> None , None | Some sty -> let cty = transl_simple_type env no_row sty in Some cty , Some cty . ctyp_type in let priv = if sdecl . ptype_private = Private then Private else if arity_ok && orig_decl . type_kind <> Type_abstract then orig_decl . type_private else sdecl . ptype_private in if arity_ok && orig_decl . type_kind <> Type_abstract && sdecl . ptype_private = Private then Location . deprecated sdecl . ptype_loc " spurious use of private " ; let type_kind , type_unboxed = if arity_ok && man <> None then orig_decl . type_kind , orig_decl . type_unboxed else Type_abstract , unboxed_false_default_false in let decl = { type_params = params ; type_arity = List . length params ; type_kind ; type_private = priv ; type_manifest = man ; type_variance = [ ] ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = sdecl . ptype_loc ; type_attributes = sdecl . ptype_attributes ; type_immediate = Unknown ; type_unboxed ; } in begin match row_path with None -> ( ) | Some p -> set_fixed_row env sdecl . ptype_loc p decl end ; begin match Ctype . closed_type_decl decl with None -> ( ) | Some ty -> raise ( Error ( sdecl . ptype_loc , Unbound_type_var ( ty , decl ) ) ) end ; let decl = name_recursion sdecl id decl in let type_variance = try Typedecl_variance . compute_decl env ~ check : true decl ( Typedecl_variance . variance_of_sdecl sdecl ) with Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) in let type_immediate = Typedecl_immediacy . compute_decl env decl in let decl = { decl with type_variance ; type_immediate } in Ctype . end_def ( ) ; generalize_decl decl ; { typ_id = id ; typ_name = sdecl . ptype_name ; typ_params = tparams ; typ_type = decl ; typ_cstrs = constraints ; typ_loc = sdecl . ptype_loc ; typ_manifest = tman ; typ_kind = Ttype_abstract ; typ_private = sdecl . ptype_private ; typ_attributes = sdecl . ptype_attributes ; }
let abstract_type_decl arity = let rec make_params n = if n <= 0 then [ ] else Ctype . newvar ( ) :: make_params ( n - 1 ) in Ctype . begin_def ( ) ; let decl = { type_params = make_params arity ; type_arity = arity ; type_kind = Type_abstract ; type_private = Public ; type_manifest = None ; type_variance = replicate_list Variance . full arity ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = Location . none ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } in Ctype . end_def ( ) ; generalize_decl decl ; decl
let approx_type_decl sdecl_list = let scope = Ctype . create_scope ( ) in List . map ( fun sdecl -> ( Ident . create_scoped ~ scope sdecl . ptype_name . txt , abstract_type_decl ( List . length sdecl . ptype_params ) ) ) sdecl_list
let check_recmod_typedecl env loc recmod_ids path decl = let to_check path = Path . exists_free recmod_ids path in check_well_founded_decl env loc path decl to_check ; check_recursion env loc path decl to_check ; check_coherence env loc path decl
let explain_unbound_gen ppf tv tl typ kwd pr = try let ti = List . find ( fun ti -> Ctype . deep_occur tv ( typ ti ) ) tl in let ty0 = Btype . newgenty ( Tobject ( tv , ref None ) ) in Printtyp . reset_and_mark_loops_list [ typ ti ; ty0 ] ; fprintf ppf " . . [ @@< hov2 > In % s @ % a ; @< 1 - 2 > the variable % a is unbound ] " @ kwd pr ti Printtyp . marked_type_expr tv with Not_found -> ( )
let explain_unbound ppf tv tl typ kwd lab = explain_unbound_gen ppf tv tl typ kwd ( fun ppf ti -> fprintf ppf " % s % a " ( lab ti ) Printtyp . marked_type_expr ( typ ti ) )
let explain_unbound_single ppf tv ty = let trivial ty = explain_unbound ppf tv [ ty ] ( fun t -> t ) " type " ( fun _ -> " " ) in match ( Ctype . repr ty ) . desc with Tobject ( fi , _ ) -> let ( tl , rv ) = Ctype . flatten_fields fi in if rv == tv then trivial ty else explain_unbound ppf tv tl ( fun ( _ , _ , t ) -> t ) " method " ( fun ( lab , _ , _ ) -> lab ^ " : " ) | Tvariant row -> let row = Btype . row_repr row in if row . row_more == tv then trivial ty else explain_unbound ppf tv row . row_fields ( fun ( _l , f ) -> match Btype . row_field_repr f with Rpresent ( Some t ) -> t | Reither ( _ , [ t ] , _ , _ ) -> t | Reither ( _ , tl , _ , _ ) -> Btype . newgenty ( Ttuple tl ) | _ -> Btype . newgenty ( Ttuple [ ] ) ) " case " ( fun ( lab , _ ) -> " ` " ^ lab ^ " of " ) | _ -> trivial ty
let tys_of_constr_args = function | Types . Cstr_tuple tl -> tl | Types . Cstr_record lbls -> List . map ( fun l -> l . Types . ld_type ) lbls
let report_error ppf = function | Repeated_parameter -> fprintf ppf " A type parameter occurs several times " | Duplicate_constructor s -> fprintf ppf " Two constructors are named % s " s | Too_many_constructors -> fprintf ppf " [ @ Too many non - constant constructors @ -- maximum is % i % s ] " @ ( Config . max_tag + 1 ) " non - constant constructors " | Duplicate_label s -> fprintf ppf " Two labels are named % s " s | Recursive_abbrev s -> fprintf ppf " The type abbreviation % s is cyclic " s | Cycle_in_def ( s , ty ) -> fprintf ppf " [ @< v > The definition of % s contains a cycle :@ % a ] " @ s Printtyp . type_expr ty | Definition_mismatch ( ty , None ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% a ] ] " @@ " This variant or record definition " " does not match that of type " Printtyp . type_expr ty | Definition_mismatch ( ty , Some err ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% a ] @% a ] " @ " This variant or record definition " " does not match that of type " Printtyp . type_expr ty ( Includecore . report_type_mismatch " the original " " this " " definition " ) err | Constraint_failed ( ty , ty ' ) -> Printtyp . reset_and_mark_loops ty ; Printtyp . mark_loops ty ' ; Printtyp . Naming_context . reset ( ) ; fprintf ppf " [ @% s @ [ @< hv > Type @ % a @ should be an instance of @ % a ] ] " @@ " Constraints are not satisfied in this type . " ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ' ) | Parameters_differ ( path , ty , ty ' ) -> Printtyp . reset_and_mark_loops ty ; Printtyp . mark_loops ty ' ; Printtyp . Naming_context . reset ( ) ; fprintf ppf " [ @< hv > In the definition of % s , type @ % a @ should be @ % a ] " @ ( Path . name path ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ' ) | Inconsistent_constraint ( env , trace ) -> fprintf ppf " The type constraints are not consistent . . " ; @ Printtyp . report_unification_error ppf env trace ( fun ppf -> fprintf ppf " Type " ) ( fun ppf -> fprintf ppf " is not compatible with type " ) | Type_clash ( env , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " This type constructor expands to type " ) ( function ppf -> fprintf ppf " but is used here with type " ) | Null_arity_external -> fprintf ppf " External identifiers must be functions " | Missing_native_external -> fprintf ppf " [ @< hv > An external function with more than 5 arguments \ requires a second stub function @ \ for native - code compilation ] " @ | Unbound_type_var ( ty , decl ) -> fprintf ppf " A type variable is unbound in this type declaration " ; let ty = Ctype . repr ty in begin match decl . type_kind , decl . type_manifest with | Type_variant tl , _ -> explain_unbound_gen ppf ty tl ( fun c -> let tl = tys_of_constr_args c . Types . cd_args in Btype . newgenty ( Ttuple tl ) ) " case " ( fun ppf c -> fprintf ppf " % a of % a " Printtyp . ident c . Types . cd_id Printtyp . constructor_arguments c . Types . cd_args ) | Type_record ( tl , _ ) , _ -> explain_unbound ppf ty tl ( fun l -> l . Types . ld_type ) " field " ( fun l -> Ident . name l . Types . ld_id ^ " : " ) | Type_abstract , Some ty ' -> explain_unbound_single ppf ty ty ' | _ -> ( ) end | Unbound_type_var_ext ( ty , ext ) -> fprintf ppf " A type variable is unbound in this extension constructor " ; let args = tys_of_constr_args ext . ext_args in explain_unbound ppf ty args ( fun c -> c ) " type " ( fun _ -> " " ) | Cannot_extend_private_type path -> fprintf ppf " [ @% s @ % a ] " @ " Cannot extend private type definition " Printtyp . path path | Not_extensible_type path -> fprintf ppf " [ @% s @ % a @ % s ] " @ " Type definition " Printtyp . path path " is not extensible " | Extension_mismatch ( path , err ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% s ] @% a ] " @ " This extension " " does not match the definition of type " ( Path . name path ) ( Includecore . report_type_mismatch " the type " " this extension " " definition " ) err | Rebind_wrong_type ( lid , env , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " The constructor % a @ has type " Printtyp . longident lid ) ( function ppf -> fprintf ppf " but was expected to be of type " ) | Rebind_mismatch ( lid , p , p ' ) -> fprintf ppf " [ @% s @ % a @ % s @ % s @ % s @ % s @ % s ] " @ " The constructor " Printtyp . longident lid " extends type " ( Path . name p ) " whose declaration does not match " " the declaration of type " ( Path . name p ' ) | Rebind_private lid -> fprintf ppf " [ @% s @ % a @ % s ] " @ " The constructor " Printtyp . longident lid " is private " | Variance ( Typedecl_variance . Bad_variance ( n , v1 , v2 ) ) -> let variance ( p , n , i ) = let inj = if i then " injective " else " " in match p , n with true , true -> inj ^ " invariant " | true , false -> inj ^ " covariant " | false , true -> inj ^ " contravariant " | false , false -> if inj = " " then " unrestricted " else inj in let suffix n = let teen = ( n mod 100 ) / 10 = 1 in match n mod 10 with | 1 when not teen -> " st " | 2 when not teen -> " nd " | 3 when not teen -> " rd " | _ -> " th " in ( match n with | Variance_not_reflected -> fprintf ppf " [ @% s @ % s @ It " " In this definition , a type variable has a variance that " " is not reflected by its occurrence in type parameters . " | No_variable -> fprintf ppf " [ @% s @ % s ] " @ " In this definition , a type variable cannot be deduced " " from the type parameters . " | Variance_not_deducible -> fprintf ppf " [ @% s @ % s @ It " " In this definition , a type variable has a variance that " " cannot be deduced from the type parameters . " | Variance_not_satisfied n -> fprintf ppf " [ @% s @ % s @ The % d % s type parameter " " In this definition , expected parameter " " variances are not satisfied . " n ( suffix n ) ) ; ( match n with | No_variable -> ( ) | _ -> fprintf ppf " was expected to be % s , @ but it is % s . ] " @ ( variance v2 ) ( variance v1 ) ) | Unavailable_type_constructor p -> fprintf ppf " The definition of type % a @ is unavailable " Printtyp . path p | Bad_fixed_type r -> fprintf ppf " This fixed type % s " r | Variance Typedecl_variance . Varying_anonymous -> fprintf ppf " [ @% s @ % s @ % s ] " @ " In this GADT definition , " " the variance of some parameter " " cannot be checked " | Val_in_structure -> fprintf ppf " Value declarations are only allowed in signatures " | Multiple_native_repr_attributes -> fprintf ppf " Too many [ @@ unboxed ] [ /@@ untagged ] attributes " | Cannot_unbox_or_untag_type Unboxed -> fprintf ppf " [ @ Don ' t know how to unbox this type . @ \ Only float , int32 , int64 and nativeint can be unboxed . ] " @ | Cannot_unbox_or_untag_type Untagged -> fprintf ppf " [ @ Don ' t know how to untag this type . @ \ Only int can be untagged . ] " @ | Deep_unbox_or_untag_attribute kind -> fprintf ppf " [ @ The attribute ' % s ' should be attached to @ \ a direct argument or result of the primitive , @ \ it should not occur deeply into its type . ] " @ ( match kind with Unboxed -> " @ unboxed " | Untagged -> " @ untagged " ) | Immediacy ( Typedecl_immediacy . Bad_immediacy_attribute violation ) -> fprintf ppf " [ @% a ] " @ Format . pp_print_text ( match violation with | Type_immediacy . Violation . Not_always_immediate -> " Types marked with the immediate attribute must be \ non - pointer types like int or bool . " | Type_immediacy . Violation . Not_always_immediate_on_64bits -> " Types marked with the immediate64 attribute must be \ produced using the Stdlib . Sys . Immediate64 . Make functor . " ) | Bad_unboxed_attribute msg -> fprintf ppf " [ @ This type cannot be unboxed because @ % s . ] " @ msg | Wrong_unboxed_type_float -> fprintf ppf " [ @ This type cannot be unboxed because @ \ it might contain both float and non - float values . @ \ You should annotate it with [ %@%@ ocaml . boxed ] . ] " @ | Boxed_and_unboxed -> fprintf ppf " [ @ A type cannot be boxed and unboxed at the same time . ] " @ | Nonrec_gadt -> fprintf ppf " [ @ GADT case syntax cannot be used in a ' nonrec ' block . ] " @
let ( ) = Location . register_error_of_exn ( function | Error ( loc , err ) -> Some ( Location . error_of_printer ~ loc report_error err ) | _ -> None )
type error = Bad_immediacy_attribute of Type_immediacy . Violation . t
let compute_decl env tdecl = match ( tdecl . type_kind , tdecl . type_manifest ) with | ( Type_variant [ { cd_args = Cstr_tuple [ arg ] ; _ } ] , _ ) | ( Type_variant [ { cd_args = Cstr_record [ { ld_type = arg ; _ } ] ; _ } ] , _ ) | ( Type_record ( [ { ld_type = arg ; _ } ] , _ ) , _ ) when tdecl . type_unboxed . unboxed -> begin match Typedecl_unboxed . get_unboxed_type_representation env arg with | Typedecl_unboxed . Unavailable -> Type_immediacy . Unknown | Typedecl_unboxed . This argrepr -> Ctype . immediacy env argrepr | Typedecl_unboxed . Only_on_64_bits argrepr -> match Ctype . immediacy env argrepr with | Type_immediacy . Always -> Type_immediacy . Always_on_64bits | Type_immediacy . Always_on_64bits | Type_immediacy . Unknown as x -> x end | ( Type_variant ( _ :: _ as cstrs ) , _ ) -> if not ( List . exists ( fun c -> c . Types . cd_args <> Types . Cstr_tuple [ ] ) cstrs ) then Type_immediacy . Always else Type_immediacy . Unknown | ( Type_abstract , Some ( typ ) ) -> Ctype . immediacy env typ | ( Type_abstract , None ) -> Type_immediacy . of_attributes tdecl . type_attributes | _ -> Type_immediacy . Unknown
let property : ( Type_immediacy . t , unit ) Typedecl_properties . property = let open Typedecl_properties in let eq = ( ) = in let merge ~ prop : _ ~ new_prop = new_prop in let default _decl = Type_immediacy . Unknown in let compute env decl ( ) = compute_decl env decl in let update_decl decl immediacy = { decl with type_immediate = immediacy } in let check _env _id decl ( ) = let written_by_user = Type_immediacy . of_attributes decl . type_attributes in match Type_immediacy . coerce decl . type_immediate ~ as_ : written_by_user with | Ok ( ) -> ( ) | Error violation -> raise ( Error ( decl . type_loc , Bad_immediacy_attribute violation ) ) in { eq ; merge ; default ; compute ; update_decl ; check ; }
let update_decls env decls = Typedecl_properties . compute_property_noreq property env decls
type ( ' prop , ' req ) property = { eq : ' prop -> ' prop -> bool ; merge : prop ' : prop -> new_prop ' : prop -> ' prop ; default : decl -> ' prop ; compute : Env . t -> decl -> ' req -> ' prop ; update_decl : decl -> ' prop -> decl ; check : Env . t -> Ident . t -> decl -> ' req -> unit ; }
let add_type ~ check id decl env = let open Types in Builtin_attributes . warning_scope ~ ppwarning : false decl . type_attributes ( fun ( ) -> Env . add_type ~ check id decl env )
let add_types_to_env decls env = List . fold_right ( fun ( id , decl ) env -> add_type ~ check : true id decl env ) decls env
let compute_property ( Ident . t * decl ) list -> ' req list -> ( Ident . t * decl ) list let props = List . map ( fun ( _id , decl ) -> property . default decl ) decls in let rec compute_fixpoint props = let new_decls = List . map2 ( fun ( id , decl ) prop -> ( id , property . update_decl decl prop ) ) decls props in let new_env = add_types_to_env new_decls env in let new_props = List . map2 ( fun ( _id , decl ) ( prop , req ) -> let new_prop = property . compute new_env decl req in property . merge ~ prop ~ new_prop ) new_decls ( List . combine props required ) in if not ( List . for_all2 property . eq props new_props ) then compute_fixpoint new_props else begin List . iter2 ( fun ( id , decl ) req -> property . check new_env id decl req ) new_decls required ; new_decls end in compute_fixpoint props
let compute_property_noreq property env decls = let req = List . map ( fun _ -> ( ) ) decls in compute_property property env decls req
type argument_to_unbox = { kind : parameter_kind ; mutability : Asttypes . mutable_flag ; argument_type : type_expr ; result_type_parameter_instances : type_expr list ; location : Location . t ; } | Record_field | Constructor_parameter | Constructor_field
type ' a multiplicity = | Zero | One of ' a | Several
type arity = argument_to_unbox multiplicity
type branching = arity multiplicity
type type_structure = | Synonym of type_expr | Abstract | Open | Algebraic of branching
let demultiply_list : type a b . a list -> ( a -> b ) -> b multiplicity = fun li f -> match li with | [ ] -> Zero | [ v ] -> One ( f v ) | _ :: _ :: _ -> Several
let structure : type_definition -> type_structure = fun def -> match def . type_kind with | Type_open -> Open | Type_abstract -> begin match def . type_manifest with | None -> Abstract | Some type_expr -> Synonym type_expr end | Type_record ( labels , _ ) -> Algebraic ( One ( demultiply_list labels @@ fun ld -> { location = ld . ld_loc ; kind = Record_field ; mutability = ld . ld_mutable ; argument_type = ld . ld_type ; result_type_parameter_instances = def . type_params ; } ) ) | Type_variant constructors -> Algebraic ( demultiply_list constructors @@ fun cd -> let result_type_parameter_instances = match cd . cd_res with | None -> def . type_params | Some ret_type -> begin match Ctype . repr ret_type with | { desc = Tconstr ( _ , tyl , _ ) } -> List . map Ctype . repr tyl | _ -> assert false end in begin match cd . cd_args with | Cstr_tuple tys -> demultiply_list tys @@ fun argument_type -> { location = cd . cd_loc ; kind = Constructor_parameter ; mutability = Asttypes . Immutable ; argument_type ; result_type_parameter_instances ; } | Cstr_record labels -> demultiply_list labels @@ fun ld -> let argument_type = ld . ld_type in { location = ld . ld_loc ; kind = Constructor_field ; mutability = ld . ld_mutable ; argument_type ; result_type_parameter_instances ; } end )
type error = | Non_separable_evar of string option
type mode = Sep . t = Ind | Sep | Deepsep
let compose : mode -> mode -> mode = fun m1 m2 -> match m1 with | Deepsep -> Deepsep | Sep -> m2 | Ind -> Ind
type type_var = { text : string option ; id : int ; }
module TVarMap = Map . Make ( struct type t = type_var let compare v1 v2 = compare v1 . id v2 . id end )
type context = mode TVarMap . t
let ( ) ++ = TVarMap . union ( fun _ m1 m2 -> Some ( max_mode m1 m2 ) )
let rec immediate_subtypes : type_expr -> type_expr list = fun ty -> match ( Ctype . repr ty ) . desc with | Tarrow ( _ , ty1 , ty2 , _ ) -> [ ty1 ; ty2 ] | Ttuple ( tys ) | Tpackage ( _ , _ , tys ) -> tys | Tobject ( row , class_ty ) -> let class_subtys = match ! class_ty with | None -> [ ] | Some ( _ , tys ) -> tys in immediate_subtypes_object_row class_subtys row | Tvariant ( row ) -> immediate_subtypes_variant_row [ ] row | Tnil | Tfield _ -> immediate_subtypes_object_row [ ] ty | Tlink _ | Tsubst _ -> assert false | Tvar _ | Tunivar _ -> [ ] | Tpoly ( pty , _ ) -> [ pty ] | Tconstr ( _path , tys , _ ) -> tys | Tnil -> acc | Tfield ( _label , _kind , ty , rest ) -> let acc = ty :: acc in immediate_subtypes_object_row acc rest | _ -> ty :: acc let add_subtypes acc = let add_subtype acc ( _l , rf ) = immediate_subtypes_variant_row_field acc rf in List . fold_left add_subtype acc desc . row_fields in let add_row acc = let row = Ctype . repr desc . row_more in match row . desc with | Tvariant more -> immediate_subtypes_variant_row acc more | _ -> row :: acc in add_row ( add_subtypes acc ) | Rpresent ( None ) | Rabsent -> acc | Rpresent ( Some ( ty ) ) -> ty :: acc | Reither ( _ , field_types , _ , r ) -> let acc = List . rev_append field_types acc in begin match ! r with | None -> acc | Some rf -> immediate_subtypes_variant_row_field acc rf end
let free_variables ty = Ctype . free_variables ( Ctype . repr ty ) |> List . map ( fun { desc ; id ; _ } -> match desc with | Tvar text -> { text ; id } | _ -> assert false )
type coinductive_hyps = { safe : ModeSet . t TypeMap . t ; unsafe : ModeSet . t TypeMap . t ; poison : ModeSet . t TypeMap . t ; }
module Hyps : sig type t = coinductive_hyps val empty : t val add : type_expr -> mode -> t -> t val guard : t -> t val poison : t -> t val safe : type_expr -> mode -> t -> bool val unsafe : type_expr -> mode -> t -> bool type t = coinductive_hyps let empty = { safe = TypeMap . empty ; unsafe = TypeMap . empty ; poison = TypeMap . empty ; } let of_opt = function | Some ms -> ms | None -> ModeSet . empty let merge map1 map2 = TypeMap . merge ( fun _k ms1 ms2 -> Some ( ModeSet . union ( of_opt ms1 ) ( of_opt ms2 ) ) ) map1 map2 let guard { safe ; unsafe ; poison ; } = { safe = merge safe unsafe ; unsafe = TypeMap . empty ; poison ; } let poison { safe ; unsafe ; poison ; } = { safe ; unsafe = TypeMap . empty ; poison = merge poison unsafe ; } let add ty m hyps = let m_map = TypeMap . singleton ty ( ModeSet . singleton m ) in { hyps with unsafe = merge m_map hyps . unsafe ; } let find ty map = try TypeMap . find ty map with Not_found -> ModeSet . empty let safe ty m hyps = match ModeSet . max_elt_opt ( find ty hyps . safe ) with | None -> false | Some best_safe -> rank best_safe >= rank m let unsafe ty m { safe = _ ; unsafe ; poison } = let in_map s = ModeSet . mem m ( find ty s ) in List . exists in_map [ unsafe ; poison ] end
let worst_case ty = let add ctx tvar = TVarMap . add tvar Deepsep ctx in List . fold_left add TVarMap . empty ( free_variables ty )
let check_type : Env . t -> type_expr -> mode -> context = fun env ty m -> let rec check_type hyps ty m = let ty = Ctype . repr ty in if Hyps . safe ty m hyps then empty else if Hyps . unsafe ty m hyps then worst_case ty else let hyps = Hyps . add ty m hyps in match ( ty . desc , m ) with | ( Tlink _ , _ ) -> assert false | ( Tsubst ( _ ) , _ ) -> assert false | ( _ , Ind ) -> empty | ( Tvar ( alpha ) , m ) -> TVarMap . singleton { text = alpha ; id = ty . Types . id } m | ( Tarrow _ , Sep ) | ( Ttuple _ , Sep ) | ( Tvariant ( _ ) , Sep ) | ( Tobject ( _ , _ ) , Sep ) | ( ( Tnil | Tfield _ ) , Sep ) | ( Tpackage ( _ , _ , _ ) , Sep ) -> empty | ( Tarrow _ , Deepsep ) | ( Ttuple _ , Deepsep ) | ( Tvariant ( _ ) , Deepsep ) | ( Tobject ( _ , _ ) , Deepsep ) | ( ( Tnil | Tfield _ ) , Deepsep ) | ( Tpackage ( _ , _ , _ ) , Deepsep ) -> let tys = immediate_subtypes ty in let on_subtype context ty = context ++ check_type ( Hyps . guard hyps ) ty Deepsep in List . fold_left on_subtype empty tys | ( Tpoly ( pty , _ ) , m ) -> check_type hyps pty m | ( Tunivar ( _ ) , _ ) -> empty | ( Tconstr ( path , tys , _ ) , m ) -> let msig = ( Env . find_type path env ) . type_separability in let on_param context ( ty , m_param ) = let hyps = match m_param with | Ind -> Hyps . guard hyps | Sep -> hyps | Deepsep -> Hyps . poison hyps in context ++ check_type hyps ty ( compose m m_param ) in List . fold_left on_param empty ( List . combine tys msig ) in check_type Hyps . empty ty m
let best_msig decl = List . map ( fun _ -> Ind ) decl . type_params
let worst_msig decl = List . map ( fun _ -> Deepsep ) decl . type_params
let msig_of_external_type decl = match decl . type_immediate with | Always | Always_on_64bits -> best_msig decl | Unknown -> worst_msig decl
let msig_of_context : decl_loc : Location . t -> parameters : type_expr list -> context -> Sep . signature = fun ~ decl_loc ~ parameters context -> let handle_equation ( acc , context ) param_instance = let param_instance = Ctype . repr param_instance in let get context var = try TVarMap . find var context with Not_found -> Ind in let set_ind context var = TVarMap . add var Ind context in let is_ind context var = match get context var with | Ind -> true | Sep | Deepsep -> false in match param_instance . desc with | Tvar text -> let var = { text ; id = param_instance . Types . id } in ( get context var ) :: acc , ( set_ind context var ) | _ -> let instance_exis = free_variables param_instance in if List . for_all ( is_ind context ) instance_exis then Ind :: acc , context else Deepsep :: acc , List . fold_left set_ind context instance_exis in let mode_signature , context = let ( mode_signature_rev , ctx ) = List . fold_left handle_equation ( [ ] , context ) parameters in ( List . rev mode_signature_rev , ctx ) in let check_existential evar mode = if rank mode > rank Ind then raise ( Error ( decl_loc , Non_separable_evar evar . text ) ) in TVarMap . iter check_existential context ; mode_signature
let check_def : Env . t -> type_definition -> Sep . signature = fun env def -> let boxed = not def . type_unboxed . unboxed in match structure def with | Abstract -> assert boxed ; msig_of_external_type def | Synonym type_expr -> check_type env type_expr Sep |> msig_of_context ~ decl_loc : def . type_loc ~ parameters : def . type_params | Open | Algebraic ( Zero | Several | One ( Zero | Several ) ) -> assert boxed ; best_msig def | Algebraic ( One ( One constructor ) ) -> if boxed then best_msig def else check_type env constructor . argument_type Sep |> msig_of_context ~ decl_loc : def . type_loc ~ parameters : constructor . result_type_parameter_instances
let compute_decl env decl = if Config . flat_float_array then check_def env decl else try check_def env decl with | Error _ -> best_msig decl
let property : ( prop , unit ) Typedecl_properties . property = let open Typedecl_properties in let eq ts1 ts2 = List . length ts1 = List . length ts2 && List . for_all2 Sep . eq ts1 ts2 in let merge ~ prop : _ ~ new_prop = new_prop in let default decl = best_msig decl in let compute env decl ( ) = compute_decl env decl in let update_decl decl type_separability = { decl with type_separability } in let check _env _id _decl ( ) = ( ) in { eq ; merge ; default ; compute ; update_decl ; check ; }
let update_decls env decls = Typedecl_properties . compute_property_noreq property env decls
type t = | Unavailable | This of type_expr | Only_on_64_bits of type_expr
let rec get_unboxed_type_representation env ty fuel = if fuel < 0 then Unavailable else let ty = Ctype . repr ( Ctype . expand_head_opt env ty ) in match ty . desc with | Tconstr ( p , args , _ ) -> begin match Env . find_type p env with | exception Not_found -> This ty | { type_immediate = Always ; _ } -> This Predef . type_int | { type_immediate = Always_on_64bits ; _ } -> Only_on_64_bits Predef . type_int | { type_unboxed = { unboxed = false } } -> This ty | { type_params ; type_kind = Type_record ( [ { ld_type = ty2 ; _ } ] , _ ) | Type_variant [ { cd_args = Cstr_tuple [ ty2 ] ; _ } ] | Type_variant [ { cd_args = Cstr_record [ { ld_type = ty2 ; _ } ] ; _ } ] } -> let ty2 = match ty2 . desc with Tpoly ( t , _ ) -> t | _ -> ty2 in get_unboxed_type_representation env ( Ctype . apply env type_params ty2 args ) ( fuel - 1 ) | { type_kind = Type_abstract } -> Unavailable | _ -> assert false end | _ -> This ty
let get_unboxed_type_representation env ty = get_unboxed_type_representation env ty 100 ; ;
type surface_variance = bool * bool * bool
let get_variance ty visited = try TypeMap . find ty ! visited with Not_found -> Variance . null
let compute_variance env visited vari ty = let rec compute_variance_rec vari ty = let ty = Ctype . repr ty in let vari ' = get_variance ty visited in if Variance . subset vari vari ' then ( ) else let vari = Variance . union vari vari ' in visited := TypeMap . add ty vari ! visited ; let compute_same = compute_variance_rec vari in match ty . desc with Tarrow ( _ , ty1 , ty2 , _ ) -> let open Variance in let v = conjugate vari in let v1 = if mem May_pos v || mem May_neg v then set May_weak true v else v in compute_variance_rec v1 ty1 ; compute_same ty2 | Ttuple tl -> List . iter compute_same tl | Tconstr ( path , tl , _ ) -> let open Variance in if tl = [ ] then ( ) else begin try let decl = Env . find_type path env in let cvari f = mem f vari in List . iter2 ( fun ty v -> let cv f = mem f v in let strict = cvari Inv && cv Inj || ( cvari Pos || cvari Neg ) && cv Inv in if strict then compute_variance_rec full ty else let p1 = inter v vari and n1 = inter v ( conjugate vari ) in let v1 = union ( inter covariant ( union p1 ( conjugate p1 ) ) ) ( inter ( conjugate covariant ) ( union n1 ( conjugate n1 ) ) ) and weak = cvari May_weak && ( cv May_pos || cv May_neg ) || ( cvari May_pos || cvari May_neg ) && cv May_weak in let v2 = set May_weak weak v1 in compute_variance_rec v2 ty ) tl decl . type_variance with Not_found -> List . iter ( compute_variance_rec may_inv ) tl end | Tobject ( ty , _ ) -> compute_same ty | Tfield ( _ , _ , ty1 , ty2 ) -> compute_same ty1 ; compute_same ty2 | Tsubst ty -> compute_same ty | Tvariant row -> let row = Btype . row_repr row in List . iter ( fun ( _ , f ) -> match Btype . row_field_repr f with Rpresent ( Some ty ) -> compute_same ty | Reither ( _ , tyl , _ , _ ) -> let open Variance in let upper = List . fold_left ( fun s f -> set f true s ) null [ May_pos ; May_neg ; May_weak ] in let v = inter vari upper in List . iter ( compute_variance_rec v ) tyl | _ -> ( ) ) row . row_fields ; compute_same row . row_more | Tpoly ( ty , _ ) -> compute_same ty | Tvar _ | Tnil | Tlink _ | Tunivar _ -> ( ) | Tpackage ( _ , _ , tyl ) -> let v = Variance . ( if mem Pos vari || mem Neg vari then full else may_inv ) in List . iter ( compute_variance_rec v ) tyl in compute_variance_rec vari ty
let make p n i = let open Variance in set May_pos p ( set May_neg n ( set May_weak n ( set Inj i null ) ) )
let compute_variance_type env ~ check ( required , loc ) decl tyl = let required = List . map ( fun ( c , n , i ) -> if c || n then ( c , n , i ) else ( true , true , i ) ) required in let params = List . map Btype . repr decl . type_params in let tvl = ref TypeMap . empty in let open Variance in List . iter ( fun ( cn , ty ) -> compute_variance env tvl ( if cn then full else covariant ) ty ) tyl ; if check then begin let pos = ref 0 in List . iter2 ( fun ty ( c , n , i ) -> incr pos ; let var = get_variance ty tvl in let ( co , cn ) = get_upper var and ij = mem Inj var in if Btype . is_Tvar ty && ( co && not c || cn && not n || not ij && i ) then raise ( Error ( loc , Bad_variance ( Variance_not_satisfied ! pos , ( co , cn , ij ) , ( c , n , i ) ) ) ) ) params required ; let args = Btype . newgenty ( Ttuple params ) in let fvl = Ctype . free_variables args in let fvl = List . filter ( fun v -> not ( List . memq v params ) ) fvl in if fvl = [ ] then ( ) else let tvl2 = ref TypeMap . empty in List . iter2 ( fun ty ( p , n , _ ) -> if Btype . is_Tvar ty then ( ) else let v = if p then if n then full else covariant else conjugate covariant in compute_variance env tvl2 v ty ) params required ; let visited = ref TypeSet . empty in let rec check ty = let ty = Ctype . repr ty in if TypeSet . mem ty ! visited then ( ) else let visited ' = TypeSet . add ty ! visited in visited := visited ' ; let v1 = get_variance ty tvl in let snap = Btype . snapshot ( ) in let v2 = TypeMap . fold ( fun t vt v -> if Ctype . equal env false [ ty ] [ t ] then union vt v else v ) ! tvl2 null in Btype . backtrack snap ; let ( c1 , n1 ) = get_upper v1 and ( c2 , n2 , _ , i2 ) = get_lower v2 in if c1 && not c2 || n1 && not n2 then if List . memq ty fvl then let code = if not i2 then No_variable else if c2 || n2 then Variance_not_reflected else Variance_not_deducible in raise ( Error ( loc , Bad_variance ( code , ( c1 , n1 , false ) , ( c2 , n2 , false ) ) ) ) else Btype . iter_type_expr check ty in List . iter ( fun ( _ , ty ) -> check ty ) tyl ; end ; List . map2 ( fun ty ( p , n , i ) -> let v = get_variance ty tvl in let tr = decl . type_private in let concr = decl . type_kind <> Type_abstract in let ( p , n ) = if tr = Private || not ( Btype . is_Tvar ty ) then ( p , n ) else ( false , false ) and i = concr || i && tr = Private in let v = union v ( make p n i ) in let v = if not concr then v else if mem Pos v && mem Neg v then full else if Btype . is_Tvar ty then v else union v ( if p then if n then full else covariant else conjugate covariant ) in if decl . type_kind = Type_abstract && tr = Public then v else set May_weak ( mem May_neg v ) v ) params required
let add_false = List . map ( fun ty -> false , ty )
let constrained vars ty = match ty . desc with | Tvar _ -> List . exists ( fun tl -> List . memq ty tl ) vars | _ -> true
let for_constr = function | Types . Cstr_tuple l -> add_false l | Types . Cstr_record l -> List . map ( fun { Types . ld_mutable ; ld_type } -> ( ld_mutable = Mutable , ld_type ) ) l
let compute_variance_gadt env ~ check ( required , loc as rloc ) decl ( tl , ret_type_opt ) = match ret_type_opt with | None -> compute_variance_type env ~ check rloc { decl with type_private = Private } ( for_constr tl ) | Some ret_type -> match Ctype . repr ret_type with | { desc = Tconstr ( _ , tyl , _ ) } -> let tyl = List . map Ctype . repr tyl in let fvl = List . map ( Ctype . free_variables ? env : None ) tyl in let _ = List . fold_left2 ( fun ( fv1 , fv2 ) ty ( c , n , _ ) -> match fv2 with [ ] -> assert false | fv :: fv2 -> if ( c || n ) && constrained ( fv1 @ fv2 ) ty then raise ( Error ( loc , Varying_anonymous ) ) ; ( fv :: fv1 , fv2 ) ) ( [ ] , fvl ) tyl required in compute_variance_type env ~ check rloc { decl with type_params = tyl ; type_private = Private } ( for_constr tl ) | _ -> assert false
let compute_variance_extension env ~ check decl ext rloc = compute_variance_gadt env ~ check rloc { decl with type_params = ext . ext_type_params } ( ext . ext_args , ext . ext_ret_type )
let compute_variance_decl env ~ check decl ( required , _ as rloc ) = if ( decl . type_kind = Type_abstract || decl . type_kind = Type_open ) && decl . type_manifest = None then List . map ( fun ( c , n , i ) -> make ( not n ) ( not c ) ( decl . type_kind <> Type_abstract || i ) ) required else let mn = match decl . type_manifest with None -> [ ] | Some ty -> [ false , ty ] in match decl . type_kind with Type_abstract | Type_open -> compute_variance_type env ~ check rloc decl mn | Type_variant tll -> if List . for_all ( fun c -> c . Types . cd_res = None ) tll then compute_variance_type env ~ check rloc decl ( mn @ List . flatten ( List . map ( fun c -> for_constr c . Types . cd_args ) tll ) ) else begin let mn = List . map ( fun ( _ , ty ) -> ( Types . Cstr_tuple [ ty ] , None ) ) mn in let tll = mn @ List . map ( fun c -> c . Types . cd_args , c . Types . cd_res ) tll in match List . map ( compute_variance_gadt env ~ check rloc decl ) tll with | vari :: rem -> let varl = List . fold_left ( List . map2 Variance . union ) vari rem in List . map Variance . ( fun v -> if mem Pos v && mem Neg v then full else v ) varl | _ -> assert false end | Type_record ( ftl , _ ) -> compute_variance_type env ~ check rloc decl ( mn @ List . map ( fun { Types . ld_mutable ; ld_type } -> ( ld_mutable = Mutable , ld_type ) ) ftl )
let is_hash id = let s = Ident . name id in String . length s > 0 && s . [ 0 ] = ' ' #
let check_variance_extension env decl ext rloc = ignore ( compute_variance_extension env ~ check : true decl ext . Typedtree . ext_type rloc )
let compute_decl env ~ check decl req = compute_variance_decl env ~ check decl ( req , decl . type_loc )
let check_decl env decl req = ignore ( compute_variance_decl env ~ check : true decl ( req , decl . type_loc ) )
type prop = Variance . t list
type req = surface_variance list
let property : ( prop , req ) Typedecl_properties . property = let open Typedecl_properties in let eq li1 li2 = try List . for_all2 Variance . eq li1 li2 with _ -> false in let merge ~ prop ~ new_prop = List . map2 Variance . union prop new_prop in let default decl = List . map ( fun _ -> Variance . null ) decl . type_params in let compute env decl req = compute_decl env ~ check : false decl req in let update_decl decl variance = { decl with type_variance = variance } in let check env id decl req = if is_hash id then ( ) else check_decl env decl req in { eq ; merge ; default ; compute ; update_decl ; check ; }
let transl_variance : Asttypes . variance -> _ = function | Covariant -> ( true , false , false ) | Contravariant -> ( false , true , false ) | Invariant -> ( false , false , false )
let variance_of_params ptype_params = List . map transl_variance ( List . map snd ptype_params )
let variance_of_sdecl sdecl = variance_of_params sdecl . Parsetree . ptype_params
let update_decls env sdecls decls = let required = List . map variance_of_sdecl sdecls in Typedecl_properties . compute_property property env decls required
let update_class_decls env cldecls = let decls , required = List . fold_right ( fun ( obj_id , obj_abbr , _cl_abbr , _clty , _cltydef , ci ) ( decls , req ) -> ( obj_id , obj_abbr ) :: decls , variance_of_params ci . Typedtree . ci_params :: req ) cldecls ( [ ] , [ ] ) in let decls = Typedecl_properties . compute_property property env decls required in List . map2 ( fun ( _ , decl ) ( _ , _ , cl_abbr , clty , cltydef , _ ) -> let variance = decl . type_variance in ( decl , { cl_abbr with type_variance = variance } , { clty with cty_variance = variance } , { cltydef with clty_variance = variance } ) ) decls cldecls