text
stringlengths
12
786k
type location = | Parameter of int list | Field of string | Nowhere
module StringMap = Map . Make ( String ) String
type t = location StringMap . t
let make l = List . fold_left ( fun acc ( id , _ ) _ -> if StringMap . mem id acc then acc else StringMap . add id ( Field ( " w " ^ id ) id ) id acc ) acc StringMap . empty l
let size t = StringMap . cardinal t
let mem k t = StringMap . mem k t
let find k t = StringMap . find k t
let add k v t = if not ( StringMap . mem k t ) t then StringMap . add k v t else t
let iter f t = StringMap . iter f t
let fold f t z = StringMap . fold f t z
let add_parameter t s l = t := add s ( Parameter l ) l ! t
let add_field t s f = t := add s ( Field f ) f ! t
let add_nowhere t s = t := add s Nowhere ! t
let rec type_desc ~ mode ( ? bracket = false ) fmt = function | Tvar None -> fprintf fmt " _ " | Tvar ( Some name ) -> fprintf fmt " ' % s " name | Ttuple typs -> fprintf fmt " [ @< 1 >% a ] " @ tuple typs | Tarrow ( typ1 , typ2 , implicitness , label ) -> if bracket then fprintf fmt " ( [ " @ ; ( match implicitness with | Explicit -> fprintf fmt " % a % a " arg_label label type_expr_b typ1 | Implicit -> fprintf fmt " % a { % a } " arg_label label type_expr typ1 ) ; arg_label_box_end fmt label ; fprintf fmt " @ -> % a " type_expr typ2 ; if bracket then fprintf fmt " ] ) " @ | Tctor v -> variant fmt v | Tpoly ( vars , typ ) -> if bracket then fprintf fmt " ( [ " @ ; fprintf fmt " [ /*@% a . ] @*/@ % a " ( type_desc ~ mode ~ bracket : false ) ( Ttuple vars ) type_expr typ ; if bracket then fprintf fmt " ] ) " @ | Tref typ -> let typ = Type1 . repr typ in if bracket then type_expr_b fmt typ else type_expr fmt typ | Treplace _ -> assert false | Tconv typ -> let typ1 = Type1 . get_mode Checked typ in let typ2 = Type1 . get_mode Prover typ in if bracket then fprintf fmt " ( [ " @ ; fprintf fmt " % a @ --> % a " type_expr_b typ1 type_expr typ2 ; if bracket then fprintf fmt " ] ) " @ | Topaque typ -> ( match mode with | Checked -> fprintf fmt " [ @< hv2 > opaque ( , @% a , ) ] " @@ type_expr typ | Prover -> type_expr fmt typ ) | Tother_mode typ -> ( match ( mode , typ . type_mode ) with | Checked , Prover -> fprintf fmt " [ @< hv2 > Prover { , @% a , } ] " @@ type_expr typ | _ -> type_expr fmt typ ) | Trow row -> ( let row_tags , row_rest , row_closed = Type1 . row_repr row in let subtract_tags = Map . fold_right row_tags ~ init [ ] : ~ f ( : fun ~ key ~ data ( : _ , pres , _ ) subtract_tags -> match ( Type1 . rp_repr pres ) . rp_desc with | RpSubtract pres when ( Type1 . rp_strip_subtract pres ) . rp_desc <> RpAbsent -> key :: subtract_tags | _ -> subtract_tags ) in ( match subtract_tags with [ ] -> ( ) | _ -> fprintf fmt " [ [ @< hv1 " ) > ; let needs_lower_bound , needs_as = match row_closed with | Open -> fprintf fmt " ( [ [ >@< hv1 , " >@ ; ( false , true ) | Closed -> let is_fixed = Map . for_all row_tags ~ f ( : fun ( _ , pres , _ ) -> match ( Type1 . rp_strip_subtract pres ) . rp_desc with | RpPresent | RpAbsent | RpAny -> true | RpMaybe -> false | RpRef _ | RpReplace _ | RpSubtract _ -> assert false ) in if is_fixed then fprintf fmt " [ [ @< hv1 , " >@ else fprintf fmt " ( [ [ <@< hv1 , " >@ ; ( not is_fixed , not is_fixed ) in let is_first = ref true in Map . iteri row_tags ~ f ( : fun ~ key : _ ~ data ( : path , pres , args ) -> let print_tag ( ) = if ! is_first then is_first := false else bar_sep fmt ( ) ; if List . is_empty args then Path . pp fmt path else fprintf fmt " % a [ @< hv1 >% a ] " @ Path . pp path tuple args in match ( Type1 . rp_strip_subtract pres ) . rp_desc with | RpPresent | RpMaybe -> print_tag ( ) | RpAbsent | RpAny -> ( ) | RpRef _ | RpReplace _ | RpSubtract _ -> assert false ) ; ( if needs_lower_bound then let is_first = ref true in Map . iteri row_tags ~ f ( : fun ~ key : _ ~ data ( : path , pres , _args ) -> match ( Type1 . rp_strip_subtract pres ) . rp_desc with | RpPresent -> if ! is_first then ( is_first := false ; fprintf fmt " @ > " ) else bar_sep fmt ( ) ; Path . pp fmt path | RpMaybe | RpAbsent | RpAny -> ( ) | RpRef _ | RpReplace _ | RpSubtract _ -> assert false ) ) ; fprintf fmt " , ] ] " @@ ; if needs_as then fprintf fmt " as % a ) " type_expr row_rest ; match subtract_tags with | [ ] -> ( ) | _ -> fprintf fmt " @ - % a ] ] " @ ( pp_print_list ~ pp_sep : bar_sep Ident . pprint ) subtract_tags ) fprintf fmt " ( , @% a , ) " @ ( pp_print_list ~ pp_sep : comma_sep type_expr ) typs type_desc ~ mode : typ . type_mode ~ bracket : true fmt typ . type_desc match v . var_params with | [ ] -> Path . pp fmt v . var_ident | _ -> fprintf fmt " [ @< hv2 >% a % a ] " @ Path . pp v . var_ident tuple v . var_params
let field_decl fmt decl = fprintf fmt " % a :@ [ @< hv >% a ] " @ Ident . pprint decl . fld_ident type_expr decl . fld_type
let ctor_args fmt = function | Ctor_tuple [ ] -> ( ) | Ctor_tuple typs -> tuple fmt typs | Ctor_record { tdec_desc = TRecord fields ; _ } -> fprintf fmt " { [ @< 2 >% a ] } " @ ( pp_print_list ~ pp_sep : comma_sep field_decl ) fields | Ctor_record _ -> assert false
let ctor_decl fmt decl = fprintf fmt " % a % a " Ident . pprint decl . ctor_ident ctor_args decl . ctor_args ; match decl . ctor_ret with | Some typ -> fprintf fmt " @ :@ [ @< hv >% a ] " @ type_expr typ | None -> ( )
let type_decl_desc fmt = function | TAbstract -> ( ) | TAlias typ -> fprintf fmt " @ =@ [ @< hv >% a ] " @ type_expr typ | TRecord fields -> fprintf fmt " @ =@ { [ @< hv2 >% a ] } " @ ( pp_print_list ~ pp_sep : comma_sep field_decl ) fields | TVariant ctors -> fprintf fmt " @ =@ % a " ( pp_print_list ~ pp_sep : bar_sep ctor_decl ) ctors | TOpen -> fprintf fmt " @ =@ . . " | TExtend ( name , ctors ) -> fprintf fmt " @ [ /*@% a +=@ % a ] " @*/ Path . pp name ( pp_print_list ~ pp_sep : bar_sep ctor_decl ) ctors
let type_decl ident fmt decl = fprintf fmt " type % a " Ident . pprint ident ; ( match decl . tdec_params with [ ] -> ( ) | _ -> tuple fmt decl . tdec_params ) ; type_decl_desc fmt decl . tdec_desc
let rec basic_check l current_type expected_type loc = if expected_type <> current_type && not ( is_unknown current_type ) then ( assert ( not debug ) ; raise ( TypeError ( expected_type , current_type , loc ) ) ) ; List . iter ( fun e -> typer e expected_type ) l if body . t <> t && not ( is_unknown body . t ) then ( assert ( not debug ) ; raise ( TypeError ( t , body . t , l ) ) ) else update_type body t ; match l1 , l2 with | [ ] , [ ] -> acc | t1 :: q1 , t2 :: q2 -> equal_sum ( acc && t1 = t2 ) q1 q2 | _ -> false my_eprintf " Equalrec \ n " ; match lct1 , lid1 , lct2 , lid2 with | c1 :: qc1 , i1 :: qi1 , c2 :: qc2 , i2 :: qi2 -> equal_rec ( acc && ( string_of_ctyp c1 ) = ( string_of_ctyp c2 ) && ( string_of_ident i1 ) = ( string_of_ident i2 ) ) qc1 qi1 qc2 qi2 | [ ] , [ ] , [ ] , [ ] -> acc | _ -> false match c1 , c2 with | KSum l1 , KSum l2 -> equal_sum true l1 l2 | KRecord ( c1 , i1 , _ ) , KRecord ( c2 , i2 , _ ) -> equal_rec true c1 i1 c2 i2 | KRecord _ , KSum _ | KSum _ , KRecord _ -> false match t1 , t2 with | Custom ( x , _ ) , Custom ( y , _ ) -> check_custom x y | Custom ( _ , _ ) , _ | _ , Custom ( _ , _ ) -> false | _ -> if t1 = t2 then true else match t1 , t2 with | TArr ( t1_ , _ ) , TArr ( t2_ , _ ) -> equal_types t1_ t2_ | _ -> false if ( not ( equal_types t1 t2 ) ) && ( not ( is_unknown t1 ) ) && ( not ( is_unknown t2 ) ) then ( assert ( not debug ) ; raise ( TypeError ( t1 , t2 , l ) ) ) match t . typ with | KRecord _ -> assert false | KSum l -> begin let rec aux = function | ( c , Some s ) :: q -> let aux2 = function | <: ctyp < int >> | <: ctyp < int32 >> -> TInt32 | a -> Custom ( t . typ , string_of_ctyp a ) in TApp ( ( aux2 s ) , ( Custom ( t . typ , t . name ) ) ) | _ :: q -> aux q | [ ] -> assert false in aux l end my_eprintf ( Printf . sprintf " \ n " %! ( k_expr_to_string body . e ) ( ktyp_to_string t ) ) ; match body . e with | Id ( l , s ) -> ( try ( let var = Hashtbl . find ! current_args ( string_of_ident s ) in my_eprintf ( ( string_of_ident s ) ^ " of type " ( ^ ktyp_to_string t ) " ^\ n " ) ; if not ( is_unknown t ) then if is_unknown var . var_type then ( var . var_type <- t ; retype := true ; update_type body t ) else check var . var_type t l ; tt := var . var_type ) with Not_found -> try let c_const = Hashtbl . find ! intrinsics_const ( string_of_ident s ) in if t = TUnknown then ( update_type body c_const . typ ; ) else if t <> c_const . typ then ( assert ( not debug ) ; raise ( TypeError ( c_const . typ , t , l ) ) ) with Not_found -> try ignore ( Hashtbl . find ! intrinsics_fun ( string_of_ident s ) ) with Not_found -> try let cstr = Hashtbl . find ! constructors ( string_of_ident s ) in my_eprintf ( " Found a constructor : " ( ^ string_of_ident s ) " ^ of type " ^ cstr . name " ^ with " ( ^ string_of_int cstr . nb_args ) " ^ arguments \ n " ) ; tt := if cstr . nb_args <> 0 then gen_app_from_constr cstr s else Custom ( cstr . typ , cstr . name ) ; with | _ -> f ( ) ) | _ -> assert false my_eprintf ( Printf . sprintf " \ n " %! ( k_expr_to_string body . e ) ( ktyp_to_string t ) ) ; ( match body . e with | Id ( l , s ) -> let tt = ref t in typer_id body t tt ( fun ( ) -> raise ( Unbound_value ( string_of_ident s , l ) ) ) ; update_type body ! tt | ArrSet ( l , e1 , e2 ) -> check t TUnit l ; typer e1 e2 . t ; typer e2 e1 . t ; update_type body TUnit | ArrGet ( l , e1 , e2 ) -> typer e1 ( TArr ( t , Shared ) ) ; typer e2 TInt32 ; update_type body ( match e1 . t with | TArr ( tt , _ ) -> tt | _ -> TUnknown ) raise ( TypeError ( TArr ( t , Shared ) , e1 . t , l ) ) ; ) ) * | VecSet ( l , e1 , e2 ) -> check t TUnit l ; typer e1 e2 . t ; typer e2 e1 . t ; update_type body TUnit | VecGet ( l , e1 , e2 ) -> typer e1 ( TVec t ) ; typer e2 TInt32 ; update_type body ( match e1 . t with | TVec tt -> tt | _ -> TUnknown ) | Seq ( l , e1 , e2 ) -> typer e1 TUnit ; typer e2 t ; update_type body e2 . t | Int32 ( l , s ) -> elt_check body TInt32 l | Int64 ( l , s ) -> elt_check body TInt64 l | Float32 ( l , s ) -> elt_check body TFloat32 l | Float64 ( l , s ) -> elt_check body TFloat64 l | Bind ( _loc , var , y , z , is_mutable ) -> ( match var . e with | Id ( _loc , s ) -> ( match y . e with | Fun ( _loc , stri , tt , funv , lifted ) -> my_eprintf ( " ADDDD : " ( ^ string_of_ident s ) " ^\ n " ) ; %! Hashtbl . add ! local_fun ( string_of_ident s ) update_type y tt ; | _ -> try in typer y v . var_type ; | Not_found -> ( incr arg_idx ; my_eprintf ( " AD : " ( ^ string_of_ident s ) " ^ of type " ^ ktyp_to_string y . t " ^ \ n " ) ; %! retype := true ; ) ) ; | _ -> assert false ) ; update_type var y . t ; typer z t ; update_type body z . t ; | Plus32 ( l , e1 , e2 ) | Min32 ( l , e1 , e2 ) | Mul32 ( l , e1 , e2 ) | Div32 ( l , e1 , e2 ) | Mod ( l , e1 , e2 ) -> basic_check [ e1 ; e2 ] t TInt32 l ; update_type body TInt32 ; | PlusF32 ( l , e1 , e2 ) | MinF32 ( l , e1 , e2 ) | MulF32 ( l , e1 , e2 ) | DivF32 ( l , e1 , e2 ) -> basic_check [ e1 ; e2 ] t TFloat32 l ; update_type body TFloat32 ; | If ( l , e1 , e2 ) -> typer e1 TBool ; basic_check [ e1 ] e1 . t TBool l ; typer e2 TUnit ; update_type body TUnit | Ife ( l , e1 , e2 , e3 ) -> typer e1 TBool ; basic_check [ e1 ] e1 . t TBool l ; typer e2 e3 . t ; typer e3 e2 . t ; if e2 . t <> e3 . t then ( assert ( not debug ) ; raise ( TypeError ( e2 . t , e3 . t , l ) ) ) ; update_type body e2 . t | Noop -> if t <> TUnit && t <> TUnknown then assert false else update_type body TUnit | Open ( l , m_ident , e2 ) -> let rec _open = function | IdAcc ( l , a , b ) -> _open a ; _open b | IdUid ( l , s ) -> open_module s l | _ -> assert false and _close = function | IdAcc ( l , a , b ) -> _close a ; _close b | IdUid ( l , s ) -> close_module s | _ -> assert false in _open m_ident ; typer e2 t ; _close m_ident ; update_type body e2 . t ; | While ( l , cond , loop_body ) -> typer cond TBool ; basic_check [ cond ] cond . t TBool l ; basic_check [ loop_body ] t TUnit l ; typer cond TBool ; typer loop_body TUnit ; update_type body TUnit ; | DoLoop ( l , var , y , z , loop_body ) -> ( match var . e with | Id ( _loc , s ) -> ( incr arg_idx ; Hashtbl . add ! current_args ( string_of_ident s ) { n = ! arg_idx ; var_type = TInt32 ; is_mutable = false ; read_only = false ; write_only = false ; is_global = false ; } ) | _ -> assert false ) ; typer var TInt32 ; typer y TInt32 ; typer z TInt32 ; typer loop_body TUnit ; update_type body TUnit ; | App ( l , e1 , e2 ) -> let t = typer_app e1 e2 t in update_type body t | BoolEq32 ( l , e1 , e2 ) | BoolLt32 ( l , e1 , e2 ) | BoolLtE32 ( l , e1 , e2 ) | BoolGt32 ( l , e1 , e2 ) | BoolGtE32 ( l , e1 , e2 ) -> typer e1 TInt32 ; typer e2 TInt32 ; update_type body TBool | BoolEqF32 ( l , e1 , e2 ) | BoolLtF32 ( l , e1 , e2 ) | BoolLtEF32 ( l , e1 , e2 ) | BoolGtF32 ( l , e1 , e2 ) | BoolGtEF32 ( l , e1 , e2 ) -> typer e1 TFloat32 ; typer e2 TFloat32 ; update_type body TBool | BoolOr ( l , e1 , e2 ) | BoolAnd ( l , e1 , e2 ) -> typer e1 TBool ; typer e2 TBool ; update_type body TBool | Ref ( l , ( { e = Id ( ll , s ) ; _ } as e ) ) -> let body = e in let tt = ref t in typer_id e t tt ( fun ( ) -> ( incr arg_idx ; is_mutable = false ; read_only = true ; write_only = false ; is_global = true ; } ; tt := t ; ) ; update_type body ! tt ) ; update_type body e . t ; decr unknown ; | Acc ( l , e1 , e2 ) -> typer e2 TUnknown ; typer e1 TUnknown ; typer e2 e1 . t ; typer e1 e2 . t ; update_type body TUnit | Match ( l , e , mc ) -> let get_patt_typ = function | Constr ( s , of_ ) -> let cstr = my_eprintf ( " --------- type case : " ^ s " ^\ n " ) ; try Hashtbl . find ! constructors s with | _ -> failwith " error in pattern matching " in ( Custom ( cstr . typ , cstr . name ) ) in let type_patt f = let t = get_patt_typ f in typer e t ; check t e . t l ; in ( match mc with | ( _loc , ( Constr ( s , of_ ) as p ) , ee ) :: _ -> ( type_patt p ; ) | _ -> failwith " No match cases in patern matching " ) ; let rec aux = function | ( ll , ( Constr ( s , of_ ) as p ) , ee ) :: q -> check ( get_patt_typ p ) e . t ll ; | Some id -> Hashtbl . replace ! current_args ( string_of_ident id ) Hashtbl . remove ! current_args ( string_of_ident id ) ; | None -> typer ee t ; ) ; check ee . t t l ; aux q | [ ] -> ( ) ; in aux ( mc ) ; let ttt = let ( _ , _ , e ) = List . hd mc in e . t in update_type body ttt | Record ( l , fl ) -> let seed : string list = let ( _loc , id , _ ) = ( List . hd fl ) in try ( Hashtbl . find ! rec_fields ( string_of_ident id ) ) . ctyps with | _ -> ( assert ( not debug ) ; raise ( FieldError ( string_of_ident id , " " " " , \\ _loc ) ) ) in let rec_typ = try Hashtbl . find custom_types ( List . hd seed ) with | _ -> assert false ; in let field_typ_list = match rec_typ with | KRecord ( typ , id , _ ) -> List . combine ( List . map string_of_ident id ) typ | _ -> assert false in let t = let rec aux ( acc : string list ) ( flds : field list ) : string list = match flds with | ( _loc , id , e ) :: q -> let rec_fld : recrd_field = try typer e ( ktyp_of_typ ( List . assoc ( string_of_ident id ) field_typ_list ) ) ; Hashtbl . find ! rec_fields ( string_of_ident id ) with | Not_found -> ( assert ( not debug ) ; raise ( FieldError ( string_of_ident id , List . hd acc , _loc ) ) ) in aux ( let rec aux2 ( res : string list ) ( acc_ : string list ) ( flds_ : string list ) = match acc_ , flds_ with | ( t1 :: q1 ) , ( t2 :: q2 ) -> if t1 = t2 then aux2 ( t1 :: acc_ ) acc q2 else aux2 ( t1 :: acc_ ) q1 ( t2 :: q2 ) | _ , [ ] -> res | [ ] , q -> aux2 res acc q in aux2 [ ] acc rec_fld . ctyps ) q | [ ] -> acc in let r : string list = aux seed fl in List . hd r in let _loc = Loc . ghost in update_type body ( ktyp_of_typ ( TyId ( _loc , IdLid ( _loc , t ) ) ) ) ; my_eprintf ( " record_type : " ( ^ ktyp_to_string body . t " ^\ n " ) ) | RecSet ( l , e1 , e2 ) -> check t TUnit l ; typer e1 e2 . t ; typer e2 e1 . t ; update_type body TUnit | RecGet ( _loc , e1 , e2 ) -> let t = try Hashtbl . find ! rec_fields ( string_of_ident e2 ) with | Not_found -> ( match e1 . e with | Id ( _ , i ) -> assert ( not debug ) ; raise ( FieldError ( ( string_of_ident i ) , ( string_of_ident e2 ) , _loc ) ) | _ -> assert false ) in typer e1 ( Custom ( Hashtbl . find custom_types t . name , t . name ) ) ; let tt = match e1 . t with | TUnknown | TVec TUnknown | TArr ( TUnknown , _ ) -> TUnknown ; | Custom ( KRecord ( l1 , l2 , _ ) , n ) -> let rec aux = function | t1 :: q1 , t2 :: q2 -> if ( string_of_ident t2 ) = ( string_of_ident e2 ) then ( my_eprintf ( string_of_ctyp t1 ) ; ktyp_of_typ t1 ) else ( my_eprintf ( " N : " ( ^ string_of_ctyp t1 ) ) ; aux ( q1 , q2 ) ) | [ ] , [ ] -> ( assert ( not debug ) ; raise ( FieldError ( string_of_ident e2 , n , _loc ) ) ) | _ -> assert false in aux ( l1 , l2 ) | _ -> my_eprintf ( ktyp_to_string e1 . t ) ; assert false in update_type body tt | False _ | True _ -> update_type body TBool | BoolNot ( _loc , e1 ) -> typer e1 TBool ; check e1 . t TBool _loc ; update_type body TBool ; | BoolEq ( _loc , e1 , e2 ) -> typer e1 TInt32 ; typer e2 e1 . t ; check e1 . t e2 . t _loc ; update_type body TBool ; | ModuleAccess ( l , m , e ) -> open_module m l ; typer e t ; close_module m ; update_type body e . t ; | TypeConstraint ( l , x , tc ) -> typer x tc ; check t tc l ; update_type body tc ; | Nat _ -> update_type body t | Pragma ( _ , lopt , expr ) -> typer expr t | _ -> my_eprintf ( ( k_expr_to_string body . e ) " ^\ n " ) ; assert false ) ; if is_unknown body . t then ( my_eprintf ( ( " UNKNOWN : " ^ k_expr_to_string body . e ) " ^\ n " ) ; incr unknown ) match e1 . e , e2 . e with | Id ( _ , <: ident < create_array ) , >> _ -> typer e2 TInt32 ; ( true , t ) | ( App ( _ , { t = _ ; e = App ( _ , { t = _ ; e = Id ( _ , <: ident < map ) ; >> loc = _ } , [ f ] ) ; loc = _ } , [ a ] ) , _ ) -> let fun_typ = ( match f . e with | Id ( _ , s ) -> let ( f , _ , lifted ) = Hashtbl . find ! local_fun ( string_of_ident s ) in my_eprintf ( " fun_type : " ^ ktyp_to_string f . typ " ^\ n " ) ; f . typ | _ -> f . t ) in ( match fun_typ with | TApp ( x , y ) -> typer a ( TVec x ) ; ( match y with | TApp ( ty , _ ) | ty -> typer e2 ( TVec ty ) ) ; | _ -> assert false ) ; ( true , TUnit ) | ( App ( _ , { t = _ ; e = App ( _ , { t = _ ; e = Id ( _ , <: ident < reduce ) ; >> loc = _ } , [ f ] ) ; loc = loc } , [ a ] ) , _ ) -> let fun_typ = ( match f . e with | Id ( _ , s ) -> let ( f , _ , lifted ) = Hashtbl . find ! local_fun ( string_of_ident s ) in my_eprintf ( " fun_type : " ^ ktyp_to_string f . typ " ^\ n " ) ; f . typ | _ -> f . t ) in ( match fun_typ with | TApp ( x , y ) -> typer a ( TVec x ) ; ( match y with | TApp ( ty , tz ) -> check x ty loc ; typer e2 ( TVec tz ) | _ -> assert false ) ; | _ -> my_eprintf ( ( " UNKNOWN : " ^ k_expr_to_string f . e ) " ^\ n " ) ; assert false ) ; ( true , TUnit ) | e , _ -> my_eprintf " Starting NOT MAAAAAP \ n " ; my_eprintf ( ( " UNKNOWN : " ^ k_expr_to_string e ) " ^\ n " ) ; ( false , TUnknown ) my_eprintf ( ( " typer app : " ^ k_expr_to_string e1 . e ) " ^ of expected type " ^ ktyp_to_string t " ^\ n " ) ; let ( is_spec , spec_type ) = is_special e1 ( List . hd e2 ) t in if is_spec then ( spec_type ) else let typ , loc = let rec aux e1 = match e1 . e with | Id ( _l , s ) -> ( try ( Hashtbl . find ! intrinsics_fun ( string_of_ident s ) ) . typ , _l with | Not_found -> ( try ( Hashtbl . find ! global_fun ( string_of_ident s ) ) . typ , _l with | Not_found -> ( try let ( f , _ , lifted ) = ( Hashtbl . find ! local_fun ( string_of_ident s ) ) in f . typ , _l with ( try let cstr = Hashtbl . find ! constructors ( string_of_ident s ) in my_eprintf ( " App : Found a constructor : " ( ^ string_of_ident s ) " ^ of type " ^ cstr . name " ^ with " ( ^ string_of_int cstr . nb_args ) " ^ arguments \ n " ) ; ( if cstr . nb_args <> 0 then gen_app_from_constr cstr s else Custom ( cstr . typ , cstr . name ) ) , _l with | Not_found -> raise ( Unbound_value ( string_of_ident s , _l ) ) ) ) ) ) | ModuleAccess ( _l , s , e ) -> open_module s _l ; let typ , loc = aux e in close_module s ; typ , loc | _ -> typer e1 t ; e1 . t , e1 . loc in aux e1 in let ret = ref TUnit in let aux2 typ expr = match typ , expr with | TApp ( t1 , t2 ) , e [ ] :: -> typer e t1 ; ret := t2 | _ , [ ] -> assert false | _ -> assert false in let aux typ1 e = match typ1 , e with | ( TApp ( t1 , ( TApp ( _ , _ ) as t2 ) ) , App ( l , e1 , ( t ( :: tt :: qq ) as e2 ) ) ) -> aux2 t2 e2 ; typer e1 t1 ; if e1 . t <> t1 then ( assert ( not debug ) ; raise ( TypeError ( t1 , e1 . t , l ) ) ) ; update_type e1 t1 ; | ( ( TApp ( TApp ( t1 , t3 ) as t , t2 ) ) , ( App ( l , e1 , e2 [ ] ) ) ) :: -> assert ( t3 = t2 ) ; ret := t2 ; typer e2 t1 ; if e2 . t <> t1 && e2 . t <> TUnknown then ( raise ( TypeError ( t1 , e2 . t , l ) ) ) ; update_type e2 t1 ; update_type e1 t ; | ( TApp ( t1 , t2 ) , App ( _ , _ , e2 [ ] :: ) ) -> my_eprintf ( Printf . sprintf " \ n " %! ( k_expr_to_string e2 . e ) ( ktyp_to_string e2 . t ) ) ; ret := e2 . t ; typer e2 t1 ; | ( t1 , App ( _ , _ , e2 [ ] :: ) ) -> my_eprintf ( Printf . sprintf " \ n " %! ( k_expr_to_string e2 . e ) ( ktyp_to_string e2 . t ) ) ; ret := t1 ; typer e2 t1 ; | _ -> assert ( not debug ) ; in aux typ ( App ( loc , e1 , e2 ) ) ; let aux typ = match typ with | TApp ( t1 , t2 ) -> t2 | t -> t in my_eprintf ( Printf . sprintf " \ n " %! ( ktyp_to_string typ ) ) ; let t = aux typ in my_eprintf ( Printf . sprintf " \ n " %! ( ktyp_to_string t ) ) ; t
let test_assert_is_none context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | import unittest class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : self . assertIsNotNone ( 2 ) } | [ ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertIsNotNone ( x ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertIsNotNone ( x , ' x should not be None ' ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self , iter : typing . List [ A ] ) -> None : a = None for i in iter : a = i self . assertIsNotNone ( a ) attribute = a . x } | [ ] ; assert_type_errors { | class Foo : def __init__ ( self ) -> None : self . x = 1 def foo ( f : Foo ) -> None : assert f . x is None reveal_type ( f . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` f . x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertTrue ( x is not None ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertTrue ( x is not None , " x should not be None " ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertFalse ( x is None ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) x = a . x self . assertFalse ( x is None , " x should not be None " ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ] ; assert_type_errors { | from dataclasses import dataclass from typing import Optional , Final class NormalClass ( ) : x : Optional [ int ] = None class ClassWithFinalAttribute ( ) : def __init__ ( self , x : Optional [ int ] ) -> None : self . x : Final [ Optional [ int ] ] = x @ dataclass class UnfrozenDataClass ( ) : x : Optional [ int ] @ dataclass ( frozen = True ) class FrozenDataClass ( ) : x : Optional [ int ] class ReadOnlyPropertyClass ( ) : state : bool = True @ property def x ( self ) -> Optional [ int ] : self . state = not self . state if self . state : return None else : return 8 def foo ( ) -> None : normal_class : Final [ NormalClass ] class_with_final_attribute : Final [ ClassWithFinalAttribute ] unfrozen_dataclass : Final [ UnfrozenDataClass ] frozen_dataclass : Final [ FrozenDataClass ] read_only_property_class : Final [ ReadOnlyPropertyClass ] if normal_class . x is not None : reveal_type ( normal_class . x ) if class_with_final_attribute . x is not None : reveal_type ( class_with_final_attribute . x ) if unfrozen_dataclass . x is not None : reveal_type ( unfrozen_dataclass . x ) if frozen_dataclass . x is not None : reveal_type ( frozen_dataclass . x ) if read_only_property_class . x is not None : reveal_type ( read_only_property_class . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` normal_class . x ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` class_with_final_attribute . x ` is ` Optional [ int ] ` \ ( inferred : ` int ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` unfrozen_dataclass . x ` is ` Optional [ int ] ` ( inferred : \ ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` frozen_dataclass . x ` is ` Optional [ int ] ` ( inferred : \ ` int ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` read_only_property_class . x ` is ` Optional [ int ] ` \ ( inferred : ` int ` , final ) . " ; ] ; assert_type_errors { | from dataclasses import dataclass from typing import Optional , Final class NormalClass ( ) : x : Optional [ int ] = None class ClassWithFinalAttribute ( ) : def __init__ ( self , x : Optional [ int ] ) -> None : self . x : Final [ Optional [ int ] ] = x @ dataclass class UnfrozenDataClass ( ) : x : Optional [ int ] @ dataclass ( frozen = True ) class FrozenDataClass ( ) : x : Optional [ int ] class ReadOnlyPropertyClass ( ) : state : bool = True @ property def x ( self ) -> Optional [ int ] : self . state = not self . state if self . state : return None else : return 8 def interleaving_call ( ) -> None : pass def foo ( ) -> None : normal_class : Final [ NormalClass ] = . . . class_with_final_attribute : Final [ ClassWithFinalAttribute ] = . . . unfrozen_dataclass : Final [ UnfrozenDataClass ] = . . . frozen_dataclass : Final [ FrozenDataClass ] = . . . read_only_property_class : Final [ ReadOnlyPropertyClass ] = . . . if normal_class . x is None : interleaving_call ( ) reveal_type ( normal_class . x ) if class_with_final_attribute . x is None : interleaving_call ( ) reveal_type ( class_with_final_attribute . x ) if unfrozen_dataclass . x is None : interleaving_call ( ) reveal_type ( unfrozen_dataclass . x ) if frozen_dataclass . x is None : interleaving_call ( ) reveal_type ( frozen_dataclass . x ) if read_only_property_class . x is None : interleaving_call ( ) reveal_type ( read_only_property_class . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` normal_class . x ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` class_with_final_attribute . x ` is ` None ` . " ; " Revealed type [ - 1 ] : Revealed type for ` unfrozen_dataclass . x ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` frozen_dataclass . x ` is ` None ` . " ; " Revealed type [ - 1 ] : Revealed type for ` read_only_property_class . x ` is ` Optional [ int ] ` \ ( final ) . " ; ] ; assert_type_errors { | from dataclasses import dataclass from typing import Optional , Final class NormalClass ( ) : x : float = 3 . 14 class ClassWithFinalAttribute ( ) : def __init__ ( self , x : float ) -> None : self . x : Final [ float ] = x @ dataclass class UnfrozenDataClass ( ) : x : float @ dataclass ( frozen = True ) class FrozenDataClass ( ) : x : float class ReadOnlyPropertyClass ( ) : state : bool = True @ property def x ( self ) -> float : self . state = not self . state if self . state : return 8 . 2 else : return 8 def interleaving_call ( ) -> None : pass def foo ( ) -> None : normal_class : Final [ NormalClass ] = . . . class_with_final_attribute : Final [ ClassWithFinalAttribute ] = . . . unfrozen_dataclass : Final [ UnfrozenDataClass ] = . . . frozen_dataclass : Final [ FrozenDataClass ] = . . . read_only_property_class : Final [ ReadOnlyPropertyClass ] = . . . if isinstance ( normal_class . x , int ) : interleaving_call ( ) reveal_type ( normal_class . x ) if isinstance ( class_with_final_attribute . x , int ) : interleaving_call ( ) reveal_type ( class_with_final_attribute . x ) if isinstance ( unfrozen_dataclass . x , int ) : interleaving_call ( ) reveal_type ( unfrozen_dataclass . x ) if isinstance ( frozen_dataclass . x , int ) : interleaving_call ( ) reveal_type ( frozen_dataclass . x ) if isinstance ( read_only_property_class . x , int ) : interleaving_call ( ) reveal_type ( read_only_property_class . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` normal_class . x ` is ` float ` . " ; " Revealed type [ - 1 ] : Revealed type for ` class_with_final_attribute . x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` unfrozen_dataclass . x ` is ` float ` . " ; " Revealed type [ - 1 ] : Revealed type for ` frozen_dataclass . x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` read_only_property_class . x ` is ` float ` ( final ) . " ; ] ; assert_type_errors { | from dataclasses import dataclass from typing import Optional , Final @ dataclass ( frozen = True ) class InnerFrozenDataClass ( ) : x : Optional [ int ] @ dataclass ( frozen = True ) class FrozenDataClass ( ) : inner : InnerFrozenDataClass @ dataclass class UnfrozenDataClass ( ) : inner : InnerFrozenDataClass def interleaving_call ( ) -> None : pass def foo ( ) -> None : unfrozen_dataclass : Final [ UnfrozenDataClass ] = . . . frozen_dataclass : Final [ FrozenDataClass ] = . . . if unfrozen_dataclass . inner . x is not None : interleaving_call ( ) reveal_type ( unfrozen_dataclass . inner . x ) if frozen_dataclass . inner . x is not None : interleaving_call ( ) reveal_type ( frozen_dataclass . inner . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` unfrozen_dataclass . inner . x ` is ` Optional [ int ] ` \ ( final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` frozen_dataclass . inner . x ` is ` Optional [ int ] ` \ ( inferred : ` int ` , final ) . " ; ] ; ( )
let test_assert_is context = assert_type_errors ~ context { | from typing import Type class Foo : x : int = 1 def foo ( o : Type [ object ] ) -> None : if ( o is Foo ) : o . x } | [ ] ; ( )
let test_check_global_refinement context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | import typing class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x def call ( ) -> None : pass def foo ( ) -> None : a = A ( 3 ) if a . x : reveal_type ( a . x ) if a . x : call ( ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` typing . Optional [ int ] ` . " ; ] ; assert_type_errors { | import typing import unittest class A : def __init__ ( self , x : typing . Optional [ int ] ) -> None : self . x = x class FakeTest ( unittest . TestCase ) : def foo ( self ) -> None : a = A ( 3 ) self . assertIsNotNone ( a . x ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ] ; assert_type_errors { | import typing MY_GLOBAL : typing . Optional [ int ] = 1 def call ( ) -> None : pass def foo ( ) -> None : if MY_GLOBAL : reveal_type ( MY_GLOBAL ) call ( ) reveal_type ( MY_GLOBAL ) } | [ " Revealed type [ - 1 ] : Revealed type for ` MY_GLOBAL ` is ` typing . Optional [ int ] ` ( inferred : \ ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` MY_GLOBAL ` is ` typing . Optional [ int ] ` . " ; ] ; assert_type_errors { | import typing x : typing . Optional [ int ] = 1 def call ( ) -> None : pass def foo ( ) -> None : global x x = 1 if x is not None : reveal_type ( x ) call ( ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : \ ` typing_extensions . Literal [ 1 ] ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` . " ; ]
let test_check_local_refinement context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | import typing def foo ( x : typing . Optional [ int ] ) -> None : if x : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ] ; assert_type_errors { | import typing def foo ( x : typing . Optional [ int ] ) -> None : if ( y := x ) : reveal_type ( x ) reveal_type ( y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` y ` is ` int ` . " ; ] ; assert_type_errors { | import typing def foo ( x : typing . Optional [ int ] ) -> None : if ( y := x ) is not None : reveal_type ( x ) reveal_type ( y ) if ( y := x ) is None : reveal_type ( x ) reveal_type ( y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` y ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` y ` is ` typing . Optional [ int ] ` . " ; ] ; assert_type_errors { | import typing def foo ( x : typing . Union [ int , str , None ] ) -> None : if x : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Union [ None , int , str ] ` ( inferred : \ ` typing . Union [ int , str ] ` ) . " ; ] ; assert_type_errors { | import typing def foo ( x : typing . Union [ int , str , None ] ) -> None : if x is None : x = 42 reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Union [ None , int , str ] ` ( inferred : \ ` typing . Union [ int , str ] ` ) . " ; ] ; assert_type_errors { | import typing import unittest class FakeTest ( unittest . TestCase ) : def foo ( self , x : typing . Optional [ int ] ) -> None : self . assertIsNotNone ( x ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ] ; assert_type_errors { | import typing x : typing . Optional [ int ] = 1 def foo ( test : bool ) -> None : if test : x = 1 else : x = None if x : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing_extensions . Literal [ 1 ] ` . " ] ; assert_type_errors { | import typing def foo ( ) -> None : x : typing . Optional [ int ] if x is not None : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ] ; assert_type_errors { | import typing def foo ( x : typing . Optional [ str ] ) -> typing . Optional [ str ] : d = { " a " : " a " } if x in d : reveal_type ( x ) return d [ x ] } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ str ] ` ( inferred : ` str ` ) . " ] ; assert_type_errors { | def f ( y ) : while True : if y in ( None , [ ] ) : pass if True : pass } | [ " Missing return annotation [ 3 ] : Return type is not specified . " ; " Missing parameter annotation [ 2 ] : Parameter ` y ` has no type specified . " ; ] ; ( )
let test_check_if_else_clause context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | import typing def foo ( x : typing . Optional [ int ] ) -> None : if x is None : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` None ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ; ] ; assert_type_errors { | import typing def foo ( x : typing . Optional [ int ] ) -> None : if x : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Optional [ int ] ` . " ; ] ; ( )
let test_assert_contains_none context = let assert_type_errors = assert_type_errors ~ context in let assert_default_type_errors = assert_default_type_errors ~ context in assert_type_errors { | import typing def foo ( x : typing . List [ typing . Optional [ int ] ] ) -> None : assert None not in x reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . List [ typing . Optional [ int ] ] ` ( inferred : \ ` typing . List [ int ] ` ) . " ; ] ; assert_type_errors { | import typing def bar ( i : typing . Optional [ int ] ) -> bool : return i is not None def foo ( x : typing . List [ typing . Optional [ int ] ] ) -> None : x = [ 1 , 2 , 3 , 4 , None , 5 ] y = [ i for i in x if bar ( i ) ] assert None not in y reveal_type ( y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` y ` is ` typing . List [ int ] ` . " ] ; assert_type_errors { | def foo ( x : None ) -> None : assert None not in x } | [ " Unsupported operand [ 58 ] : ` not in ` is not supported for right operand type ` None ` . " ] ; assert_type_errors { | def foo ( x : Derp ) -> None : assert None not in x } | [ " Unbound name [ 10 ] : Name ` Derp ` is used but not defined in the current scope . " ] ; assert_default_type_errors { | import typing def foo ( x : typing . Any ) -> None : assert None not in x reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Any ` . " ] ; assert_type_errors { | import typing def foo ( x : typing . List [ Derp ] ) -> None : assert None not in x reveal_type ( x ) } | [ " Unbound name [ 10 ] : Name ` Derp ` is used but not defined in the current scope . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` unknown ` . " ; ] ; assert_default_type_errors { | import typing def foo ( x : typing . List [ typing . Any ] ) -> None : assert None not in x reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . List [ typing . Any ] ` . " ] ; ( )
let test_check_callable context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import Dict , Optional class CallableClass : def __call__ ( self , x : int ) -> str : return " A " def foo ( x : Dict [ int , Optional [ CallableClass ] ] ) -> None : ret = x [ 0 ] if callable ( ret ) : reveal_type ( ret ) } | [ " Revealed type [ - 1 ] : Revealed type for ` ret ` is ` CallableClass ` . " ] ; assert_type_errors { | from typing import Dict , Callable , Optional def foo ( x : Dict [ int , Optional [ Callable [ [ ] , int ] ] ] ) -> None : ret = x [ 0 ] if callable ( ret ) : reveal_type ( ret ) reveal_type ( ret ) } | [ " Revealed type [ - 1 ] : Revealed type for ` ret ` is ` typing . Callable [ [ ] , int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` ret ` is ` Optional [ typing . Callable [ [ ] , int ] ] ` . " ; ] ; assert_type_errors { | from typing import Union , Callable def foo ( x : Union [ Callable [ [ ] , int ] , int ] ) -> None : if callable ( x ) : reveal_type ( x ) reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Callable [ [ ] , int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` Union [ typing . Callable [ [ ] , int ] , int ] ` . " ; ] ; assert_type_errors { | from typing import Union , Type class Constructable : def __init__ ( self , x : int ) -> None : return def foo ( x : Union [ int , Type [ Constructable ] ] ) -> None : if callable ( x ) : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` Type [ Constructable ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ; ] ; assert_type_errors { | from typing import Union , Callable def foo ( x : Union [ Callable [ [ int ] , str ] , int ] ) -> None : if not callable ( x ) : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Callable [ [ int ] , str ] ` . " ; ] ; assert_type_errors { | from typing import Callable def foo ( x : Callable [ [ ] , int ] ) -> None : if callable ( x ) : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Callable [ [ ] , int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Callable [ [ ] , int ] ` . " ; ] ; assert_type_errors { | def foo ( x : int ) -> None : if callable ( x ) : reveal_type ( x ) else : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Callable [ . . . , object ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` int ` . " ; ] ; ( )
let test_check_final_attribute_refinement context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import Final , Optional class Boo : . . . class Baz : z : Final [ Optional [ Boo ] ] = None class Bar : y : Final [ Optional [ Baz ] ] = None class Foo : x : Final [ Optional [ Bar ] ] = None def bar ( foo : Foo ) -> None : assert ( foo . x and foo . x . y and foo . x . y . z ) reveal_type ( foo . x ) reveal_type ( foo . x . y ) reveal_type ( foo . x . y . z ) def bar2 ( foo : Foo ) -> None : # This produces the same underlying Assert as above after normalization . if not foo . x or not foo . x . y : pass else : reveal_type ( foo . x ) reveal_type ( foo . x . y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . x ` is ` Optional [ Bar ] ` ( inferred : ` Bar ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . x . y ` is ` Optional [ Baz ] ` ( inferred : ` Baz ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . x . y . z ` is ` Optional [ Boo ] ` ( inferred : ` Boo ` , \ final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . x ` is ` Optional [ Bar ] ` ( inferred : ` Bar ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . x . y ` is ` Optional [ Baz ] ` ( inferred : ` Baz ` , final ) . " ; ] ; assert_type_errors { | from typing import Optional from dataclasses import dataclass def expects_str ( x : str ) -> None : pass @ dataclass ( frozen = True ) class Actor : name : Optional [ str ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name def foo ( a : Actor ) -> None : if a . name is not None : expects_str ( a . name ) } | [ ] ; assert_type_errors { | from typing import Optional , Final def expects_str ( x : str ) -> None : pass class Actor : name : Final [ Optional [ str ] ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name def foo ( a : Actor ) -> None : if a . name is not None : expects_str ( a . name ) } | [ ] ; assert_type_errors { | from typing import Optional def expects_str ( x : str ) -> None : pass class Actor : name : Optional [ str ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name def foo ( a : Actor ) -> None : if a . name is not None : expects_str ( a . name ) if a . name is not None : expects_str ( " unrelated call " ) expects_str ( a . name ) } | [ " Incompatible parameter type [ 6 ] : In call ` expects_str ` , for 1st positional only parameter \ expected ` str ` but got ` Optional [ str ] ` . " ; ] ; assert_type_errors { | from typing import Optional from dataclasses import dataclass def expects_str ( x : str ) -> None : pass @ dataclass ( frozen = True ) class Actor : name : Optional [ str ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name def foo ( a : Actor ) -> None : if a . name is not None : a = Actor ( None ) expects_str ( a . name ) } | [ " Incompatible parameter type [ 6 ] : In call ` expects_str ` , for 1st positional only parameter \ expected ` str ` but got ` Optional [ str ] ` . " ; ] ; assert_type_errors { | from typing import Optional from dataclasses import dataclass def expects_str ( x : str ) -> None : pass @ dataclass ( frozen = True ) class Actor : name : Optional [ str ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name def foo ( a : Actor ) -> None : if a . name is not None : a = Actor ( None ) if a . name : reveal_type ( a . name ) reveal_type ( a . name ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . name ` is ` Optional [ str ] ` ( inferred : ` str ` , final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a . name ` is ` Optional [ str ] ` ( final ) . " ; ] ; assert_type_errors { | from typing import Optional from dataclasses import dataclass @ dataclass ( frozen = True ) class Base : name : Optional [ str ] def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name @ dataclass ( frozen = True ) class ChildA ( Base ) : name : Optional [ str ] age : int def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name self . age = 0 @ dataclass ( frozen = True ) class ChildB ( Base ) : name : Optional [ str ] year : int def __init__ ( self , name : Optional [ str ] ) -> None : self . name = name self . year = 2020 def expects_non_optional_and_a ( x : str , y : ChildA ) -> None : pass def expects_non_optional_and_b ( x : str , y : ChildB ) -> None : pass def foo ( o : Base ) -> None : if o . name : if isinstance ( o , ChildA ) : expects_non_optional_and_a ( o . name , o ) if isinstance ( o , ChildB ) : expects_non_optional_and_b ( o . name , o ) } | [ ] ; assert_type_errors { | from typing import Union from dataclasses import dataclass def expects_int ( x : int ) -> None : pass @ dataclass ( frozen = True ) class Foo : x : Union [ int , str ] def __init__ ( self , x : Union [ int , str ] ) -> None : self . x = x def f ( a : Foo ) -> None : if isinstance ( a . x , int ) : expects_int ( a . x ) } | [ ] ; assert_type_errors { | from typing import Union from dataclasses import dataclass def expects_int ( x : int ) -> None : pass @ dataclass ( frozen = True ) class Foo : x : Union [ int , str ] def __init__ ( self , x : Union [ int , str ] ) -> None : self . x = x def f ( a : Foo ) -> None : if isinstance ( a . x , int ) : a = Foo ( " bar " ) expects_int ( a . x ) } | [ " Incompatible parameter type [ 6 ] : In call ` expects_int ` , for 1st positional only parameter \ expected ` int ` but got ` Union [ int , str ] ` . " ; ] ; assert_type_errors { | from typing import Union from dataclasses import dataclass def expects_int ( x : int ) -> None : pass @ dataclass ( frozen = True ) class Foo : x : Union [ int , str ] def __init__ ( self , x : Union [ int , str ] ) -> None : self . x = x def f ( a : Foo ) -> None : if type ( a . x ) is int : expects_int ( a . x ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` Union [ int , str ] ` ( final ) . " ] ; assert_type_errors { | from typing import Union , Callable from dataclasses import dataclass def expects_int ( x : int ) -> None : pass @ dataclass ( frozen = True ) class Foo : x : Union [ int , Callable [ [ ] , int ] ] def __init__ ( self , x : Union [ int , Callable [ [ ] , int ] ] ) -> None : self . x = x def f ( a : Foo ) -> None : if callable ( a . x ) : reveal_type ( a . x ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` typing . Callable [ [ ] , int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` Union [ typing . Callable [ [ ] , int ] , int ] ` . " ; ] ; assert_type_errors { | from typing import Union , Callable from dataclasses import dataclass def expects_int ( x : int ) -> None : pass @ dataclass ( frozen = True ) class Foo : x : Union [ int , Callable [ [ ] , int ] ] def __init__ ( self , x : Union [ int , Callable [ [ ] , int ] ] ) -> None : self . x = x def f ( a : Foo ) -> None : if callable ( a . x ) : a = Foo ( 42 ) reveal_type ( a . x ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` Union [ typing . Callable [ [ ] , int ] , int ] ` \ ( final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` Union [ typing . Callable [ [ ] , int ] , int ] ` \ ( final ) . " ; ] ; assert_type_errors { | from typing import NamedTuple , Optional from dataclasses import dataclass class Foo ( NamedTuple ) : value : Optional [ int ] other : int = 1 def f ( ) -> None : foo = Foo ( value = 1 ) reveal_type ( foo . value ) if foo . value : reveal_type ( foo . value ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . value ` is ` Optional [ int ] ` ( final ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . value ` is ` Optional [ int ] ` ( inferred : ` int ` , \ final ) . " ; ] ; ( )
let test_check_temporary_refinement context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | MY_GLOBAL = 1 . 0 def arbitrary_call ( ) -> None : pass def test ( ) -> None : reveal_type ( MY_GLOBAL ) global MY_GLOBAL MY_GLOBAL = 1 reveal_type ( MY_GLOBAL ) arbitrary_call ( ) reveal_type ( MY_GLOBAL ) } | [ " Revealed type [ - 1 ] : Revealed type for ` MY_GLOBAL ` is ` float ` . " ; " Revealed type [ - 1 ] : Revealed type for ` MY_GLOBAL ` is ` float ` ( inferred : \ ` typing_extensions . Literal [ 1 ] ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` MY_GLOBAL ` is ` float ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 def takes_non_optional_int ( input : int ) -> None : pass def test ( foo : Foo ) -> None : reveal_type ( foo . attribute ) foo . attribute = 1 reveal_type ( foo . attribute ) takes_non_optional_int ( foo . attribute ) reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : \ ` typing_extensions . Literal [ 1 ] ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : @ property def attribute ( self ) -> Optional [ int ] : pass @ attribute . setter def attribute ( self , value : Optional [ int ] ) -> None : pass def test ( foo : Foo ) -> None : reveal_type ( foo . attribute ) foo . attribute = 1 reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 def __getattr__ ( self , value : str ) -> int : return 1 def test ( foo : Foo ) -> None : reveal_type ( foo . attribute ) foo . attribute = 1 reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 class Bar : def unrelated_call ( self ) -> None : pass def test ( foo : Foo ) -> None : reveal_type ( foo . attribute ) foo . attribute = 1 reveal_type ( foo . attribute ) bar = Bar ( ) reveal_type ( foo . attribute ) if not foo . attribute : return reveal_type ( foo . attribute ) bar . unrelated_call ( ) reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : \ ` typing_extensions . Literal [ 1 ] ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 def interleaving_call ( ) -> None : pass def test ( foo : Foo ) -> None : reveal_type ( foo . attribute ) if not foo . attribute : return local_copy = foo . attribute interleaving_call ( ) reveal_type ( foo . attribute ) reveal_type ( local_copy ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` local_copy ` is ` int ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 class Bar : foo : Optional [ Foo ] = Foo ( ) def interleaving_call ( ) -> None : pass def test ( bar : Bar ) -> None : if bar . foo . attribute is not None : return reveal_type ( bar . foo ) reveal_type ( bar . foo . attribute ) if bar . foo and bar . foo . attribute : reveal_type ( bar . foo . attribute ) } | [ " Undefined attribute [ 16 ] : ` Optional ` has no attribute ` attribute ` . " ; " Revealed type [ - 1 ] : Revealed type for ` bar . foo ` is ` Optional [ Foo ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` bar . foo . attribute ` is ` unknown ` . " ; " Revealed type [ - 1 ] : Revealed type for ` bar . foo . attribute ` is ` Optional [ int ] ` ( inferred : \ ` int ` ) . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 def interleaving_call ( ) -> None : pass def test ( foo : Foo ) -> None : if not foo . attribute : return interleaving_call ( ) reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 class Bar : attribute : Optional [ int ] = 1 def interleaving_call ( ) -> None : pass def test ( foo : Foo , bar : Bar ) -> None : if not foo . attribute or not bar . attribute : return reveal_type ( foo . attribute ) reveal_type ( bar . attribute ) interleaving_call ( ) if not foo . attribute and not bar . attribute : return reveal_type ( foo . attribute ) reveal_type ( bar . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` bar . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` bar . attribute ` is ` Optional [ int ] ` . " ; ] ; assert_type_errors { | from typing import Optional class Foo : attribute : Optional [ int ] = 1 def interleaving_call ( ) -> None : pass def test ( foo : Foo ) -> None : if not foo . attribute or interleaving_call ( ) : return reveal_type ( foo . attribute ) def test_two ( foo : Foo ) -> None : if interleaving_call ( ) or not foo . attribute : return reveal_type ( foo . attribute ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . attribute ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; ] ; assert_type_errors { | from typing import Optional class Foo : a : Optional [ int ] = 1 b : Optional [ int ] = 1 def interleaving_call ( ) -> None : pass def test ( foo : Foo ) -> None : if not foo . a or not foo . b : return reveal_type ( foo . a ) reveal_type ( foo . b ) interleaving_call ( ) if foo . a is None or foo . b is None : return reveal_type ( foo . a ) reveal_type ( foo . b ) } | [ " Revealed type [ - 1 ] : Revealed type for ` foo . a ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . b ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . a ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` foo . b ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; ] ; assert_type_errors { | from typing import Optional def test ( a : Optional [ int ] , b : Optional [ int ] ) -> None : if not a or not b : return reveal_type ( a ) reveal_type ( b ) def test_two ( a : Optional [ int ] , b : Optional [ int ] ) -> None : if a is None or b is None : return reveal_type ( a ) reveal_type ( b ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` b ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` b ` is ` Optional [ int ] ` ( inferred : ` int ` ) . " ; ] ; assert_type_errors { | from typing import Any def foo ( ) -> None : . . . if isinstance ( Any , int ) : reveal_type ( Any ) # temporary refinement is permitted foo ( ) reveal_type ( Any ) # but it is cleared as it shoudl be } | [ " Revealed type [ - 1 ] : Revealed type for ` typing . Any ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` typing . Any ` is ` object ` . " ; ] ; assert_type_errors { | class A : x : object = " " class B ( A ) : pass def foo ( a : A ) -> None : if isinstance ( a , B ) : if isinstance ( a . x , int ) : reveal_type ( a ) reveal_type ( a . x ) if isinstance ( a . x , int ) : if isinstance ( a , B ) : reveal_type ( a ) reveal_type ( a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a ` is ` B ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a ` is ` B ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a . x ` is ` int ` . " ; ] ; assert_type_errors { | import typing class A : a : typing . Optional [ A ] = None x : object = " " class B ( A ) : pass def f ( a : A ) -> None : b = B ( ) if a . a is not None : if isinstance ( a . a . x , int ) : reveal_type ( a . a . x ) a . a = b reveal_type ( a . a ) reveal_type ( a . a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . a . x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a . a ` is ` typing . Optional [ A ] ` ( inferred : ` B ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a . a . x ` is ` object ` . " ; ] ; assert_type_errors { | import typing class A : a : typing . Optional [ A ] = None x : typing . Final [ object ] = " " class B ( A ) : pass def f ( a : A ) -> None : if a . a is not None : if isinstance ( a . a . x , int ) : reveal_type ( a . a . x ) a . a = B ( ) reveal_type ( a . a ) reveal_type ( a . a . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` a . a . x ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` a . a ` is ` typing . Optional [ A ] ` ( inferred : ` B ` ) . " ; " Revealed type [ - 1 ] : Revealed type for ` a . a . x ` is ` object ` ( final ) . " ; ] ; ( )
let ( ) = " refinement " >::: [ " check_assert_is_none " >:: test_assert_is_none ; " check_assert_is " >:: test_assert_is ; " check_global_refinement " >:: test_check_global_refinement ; " check_local_refinement " >:: test_check_local_refinement ; " check_if_else_clause " >:: test_check_if_else_clause ; " check_assert_contains_none " >:: test_assert_contains_none ; " check_callable " >:: test_check_callable ; " check_final_attribute_refinement " >:: test_check_final_attribute_refinement ; " check_temporary_refinement " >:: test_check_temporary_refinement ; ] |> Test . run
module type S = sig type t val typerep_of_t : t Typerep . t val typename_of_t : t Typename . t end
module type S1 = sig type ' a t val typerep_of_t : ' a Typerep . t -> ' a t Typerep . t val typename_of_t : ' a Typename . t -> ' a t Typename . t end
module type S2 = sig type ( ' a , ' b ) t val typerep_of_t : ' a Typerep . t -> ' b Typerep . t -> ( ' a , ' b ) t Typerep . t val typename_of_t : ' a Typename . t -> ' b Typename . t -> ( ' a , ' b ) t Typename . t end
module type S3 = sig type ( ' a , ' b , ' c ) t val typerep_of_t : ' a Typerep . t -> ' b Typerep . t -> ' c Typerep . t -> ( ' a , ' b , ' c ) t Typerep . t val typename_of_t : ' a Typename . t -> ' b Typename . t -> ' c Typename . t -> ( ' a , ' b , ' c ) t Typename . t end
module type S4 = sig type ( ' a , ' b , ' c , ' d ) t val typerep_of_t : ' a Typerep . t -> ' b Typerep . t -> ' c Typerep . t -> ' d Typerep . t -> ( ' a , ' b , ' c , ' d ) t Typerep . t val typename_of_t : ' a Typename . t -> ' b Typename . t -> ' c Typename . t -> ' d Typename . t -> ( ' a , ' b , ' c , ' d ) t Typename . t end
module type S5 = sig type ( ' a , ' b , ' c , ' d , ' e ) t val typerep_of_t : ' a Typerep . t -> ' b Typerep . t -> ' c Typerep . t -> ' d Typerep . t -> ' e Typerep . t -> ( ' a , ' b , ' c , ' d , ' e ) t Typerep . t val typename_of_t : ' a Typename . t -> ' b Typename . t -> ' c Typename . t -> ' d Typename . t -> ' e Typename . t -> ( ' a , ' b , ' c , ' d , ' e ) t Typename . t end
let repr_of_poly_variant : [ > ] -> int = fun variant -> let obj = Obj . repr variant in if Obj . is_int obj then Obj . obj obj else ( let size = Obj . size obj in assert ( size = 2 ) ; let repr = Obj . field obj 0 in assert ( Obj . is_int repr ) ; Obj . obj repr ) ; ;
let hash_variant s = let accu = ref 0 in for i = 0 to String . length s - 1 do accu := ( 223 * ! accu ) + Char . code s . [ i ] done ; accu := ! accu land ( ( 1 lsl 31 ) - 1 ) ; if ! accu > 0x3FFFFFFF then ! accu - ( 1 lsl 31 ) else ! accu ; ;
let ( ) = assert ( repr_of_poly_variant ` Latency_stats = hash_variant " Latency_stats " )
let ( ) = assert ( repr_of_poly_variant ` zero = hash_variant " zero " )
let double_array_value = Obj . magic 0 .
let has_double_array_tag a = Obj . double_array_tag = Obj . tag ( Obj . repr a )
let ( ) = let module M = struct type double = { a : float ; b : float } type simple = { c : float ; d : int } let double = { a = double_array_value ; b = double_array_value } let simple = { c = double_array_value ; d = double_array_value } end in assert ( has_double_array_tag M . double ) ; assert ( not ( has_double_array_tag M . simple ) ) ; ;
type kind_of_global_ident = Value | Type | Constr | Label
type kind_of_ident = | Current | Initial | Next | Multi | Derivative
type error = | Evar_undefined of Zident . t | Emissing of Zident . t | Eglobal_undefined of kind_of_global_ident * Lident . t | Eglobal_already of kind_of_global_ident * string | Ealready of kind_of_ident * Zident . t | Ealready_with_different_kinds of kind_of_ident * kind_of_ident * Zident . t | Eis_a_value of Zident . t | Ealready_in_forall of Zident . t | Einit_undefined of Zident . t | Elast_forbidden of Zident . t | Eder_forbidden of Zident . t | Enext_forbidden of Zident . t | Eshould_be_a_signal of Zident . t * typ | Ecannot_be_set of bool * Zident . t | Etype_clash of typ * typ | Etype_kind_clash of kind * typ | Earity_clash of int * int | Estate_arity_clash of Zident . t * int * int | Estate_unbound of Zident . t | Estate_initial | Ekind_not_combinatorial | Ekind_clash of kind * kind | Esome_labels_are_missing | Eequation_is_missing of Zident . t | Eglobal_is_a_function of Lident . t | Eapplication_of_non_function | Epattern_not_total | Ecombination_function of Zident . t | Esize_parameter_must_be_a_name | Enot_a_size_expression | Esize_of_vec_is_undetermined | Esize_clash of size * size | Esize_parameter_cannot_be_generalized of Zident . t * typ | Econstr_arity of Lident . t * int * int
let error loc kind = raise ( Error ( loc , kind ) )
type warning = | Wpartial_matching of Zelus . pattern | Wunreachable_state of Zident . t | Wmatch_unused of Zelus . pattern | Wequation_does_not_define_a_name | Wreset_target_state of bool * bool
let kind_of_global_ident k = match k with | Value -> " value " | Type -> " type " | Constr -> " constructor " | Label -> " label "
let kind_of_ident k = match k with | Current -> " value " | Derivative -> " derivative " | Initial -> " initial value " | Multi -> " multi emitted value " | Next -> " next value "
let kind_message kind = match kind with | Tstatic _ -> " static " | Tcont -> " continuous " | Tany -> " combinatorial " | Tdiscrete ( s ) -> if s then " discrete " else " stateless discrete " | Tproba -> " probabilistic "
let message loc kind = begin match kind with | Evar_undefined ( name ) -> eprintf " [ @% aTyping error : The value identifier % s is unbound . . ] " @@ output_location loc ( Zident . source name ) | Emissing ( s ) -> eprintf " [ @% aType error : no equation is given for name % s . . ] " @@ output_location loc ( Zident . source s ) ; | Eglobal_undefined ( k , lname ) -> eprintf " [ @% aType error : the global value identifier % s % s is unbound . . ] " @@ output_location loc ( kind_of_global_ident k ) ( Lident . modname lname ) | Eglobal_already ( k , s ) -> eprintf " [ @% aType error : the % s name % s is already defined . . ] " @@ output_location loc ( kind_of_global_ident k ) s | Ealready ( k , s ) -> let k = kind_of_ident k in eprintf " [ @% aType error : the % s of % s is defined twice in a parallel branch . . ] " @@ output_location loc k ( Zident . source s ) | Ealready_with_different_kinds ( k1 , k2 , s ) -> let k1 = kind_of_ident k1 in let k2 = kind_of_ident k2 in eprintf " [ @% aType error : % s is defined twice in a parallel branch , , @\ once with as a % s , once as a % s . . ] " @@ output_location loc ( Zident . source s ) k1 k2 | Ealready_in_forall ( s ) -> eprintf " [ @% aType error : % s is defined twice in a parallel branch . . ] " @@ output_location loc ( Zident . source s ) | Einit_undefined ( s ) -> eprintf " [ @% aType error : % s must be initialized in every branch . . ] " @@ output_location loc ( Zident . source s ) | Eis_a_value ( s ) -> eprintf " [ @% aType error : last % s is forbidden as % s is a value . . ] " @@ output_location loc ( Zident . source s ) ( Zident . source s ) | Elast_forbidden ( s ) -> eprintf " [ @% aType error : last % s is forbidden . This is either , @\ because % s is not a state variable or next % s is defined . . ] " @@ output_location loc ( Zident . source s ) ( Zident . source s ) ( Zident . source s ) | Eder_forbidden ( s ) -> eprintf " [ @% aType error : der % s is forbidden because \ % s is not a state variable . . ] " @@ output_location loc ( Zident . source s ) ( Zident . source s ) | Enext_forbidden ( s ) -> eprintf " [ @% aType error : next % s is forbidden . This is either , @\ because % s is not a state variable or last % s is used . . ] " @@ output_location loc ( Zident . source s ) ( Zident . source s ) ( Zident . source s ) | Eshould_be_a_signal ( s , expected_ty ) -> eprintf " [ @% aType error : % s is a value of type % a , @ \ but is expected to be a signal , @\ ( maybe a default value or initialization is missing ) . . ] " @@ output_location loc ( Zident . source s ) | Ecannot_be_set ( is_next , s ) -> eprintf " [ @% aType error : the % s value of % s cannot be set . , @\ This is either because the % s value is set or , @\ the last value is used . . ] " @@ output_location loc ( if is_next then " next " else " current " ) | Etype_clash ( actual_ty , expected_ty ) -> eprintf " [ @% aType error : this expression has type @ % a , @ \ but is expected to have type @ % a . . ] " @@ output_location loc Ptypes . output actual_ty Ptypes . output expected_ty | Etype_kind_clash ( k , actual_ty ) -> eprintf " [ @% aType error : this expression has type @ % a , @ \ which does not belong to the % s kind . . ] " @@ output_location loc Ptypes . output actual_ty ( kind_message k ) | Earity_clash ( actual_arit , expected_arit ) -> eprintf " [ @% aType error : the function expects % d arguments , @ \ but is given % d arguments . . ] " @@ output_location loc expected_arit actual_arit | Estate_arity_clash ( name , actual_arit , expected_arit ) -> eprintf " [ @% aType error : the state % s expects % d arguments , @ \ but is given % d arguments . . ] " @@ output_location loc ( Zident . source name ) expected_arit actual_arit | Estate_unbound ( name ) -> eprintf " [ @% aType error : the state % s is unbound in the current automaton . . ] " @@ output_location loc ( Zident . source name ) | Estate_initial -> eprintf " [ @% aType error : the initial state cannot be parameterized . . ] " @@ output_location loc | Ekind_not_combinatorial -> eprintf " [ @% aType error : this expression should be combinatorial . . ] " @@ output_location loc | Ekind_clash ( actual_kind , expected_kind ) -> eprintf " [ @% aType error : this is a % s expression and is expected to be % s . . ] " @@ output_location loc ( kind_message actual_kind ) ( kind_message expected_kind ) | Esome_labels_are_missing -> eprintf " [ @% aType error : some fields are missing . . ] " @@ output_location loc | Eequation_is_missing ( name ) -> eprintf " [ @% aType error : the variable % s must be defined in an equation . . ] " @@ output_location loc ( Zident . source name ) | Eglobal_is_a_function ( lname ) -> eprintf " [ @% aType error : the global name % s must not be a function . . ] " @@ output_location loc ( Lident . modname lname ) | Eapplication_of_non_function -> eprintf " [ @% aType error : this is not a function . . ] " @@ output_location loc | Epattern_not_total -> eprintf " [ @% aType error : this pattern must be total . . ] " @@ output_location loc | Ecombination_function ( n ) -> eprintf " [ @% aType error : a combination function for % s must be given . . ] " @@ output_location loc ( Zident . source n ) | Esize_parameter_must_be_a_name -> eprintf " [ @% aType error : the type of the result depend on some variables \ from this pattern . This pattern must be a variable . . ] " @@ output_location loc | Esize_of_vec_is_undetermined -> eprintf " [ @< hov 0 >% aType error : this expression is either not a vector @ or its \ size cannot be determined at that point . . ] " @@ output_location loc | Enot_a_size_expression -> eprintf " [ @% aType error : this is not a valid size expression . . ] " @@ output_location loc | Esize_clash ( actual_size , expected_size ) -> eprintf " [ @% aType error : this expression is equal to @ % a , @ \ but is expected to have equal to @ % a . . ] " @@ output_location loc Ptypes . output_size actual_size Ptypes . output_size expected_size | Esize_parameter_cannot_be_generalized ( n , ty ) -> eprintf " [ @% aType error : this pattern has type @ % a , @ \ which contains the variable % s that is bounded later or never . . ] " @@ Ptypes . output ty | Econstr_arity ( ln , expected_arity , actual_arity ) -> eprintf " [ @% aType error : the type constructor % a expects % d argument ( s ) , @ \ but is here given % d arguments ( s ) . \ n " output_location loc Printer . longname ln expected_arity actual_arity end ; raise Zmisc . Error
let warning loc w = if not ! Zmisc . no_warning then match w with | Wpartial_matching ( p ) -> Format . eprintf " [ @% aType warning : this pattern - matching is not exhaustive . . ] " @@ Format . eprintf " [ @ Here is an example of a value that is not matched . :@% a . ] " @@ | Wunreachable_state ( s ) -> eprintf " [ @% aType warning : the state % s in this automaton is unreachable . . ] " @@ output_location loc ( Zident . source s ) | Wmatch_unused ( p ) -> Format . eprintf " [ @ Type warning : match case " \% a " \ is unused . . ] " @@ Printer . pattern p | Wequation_does_not_define_a_name -> eprintf " [ @% aType warning : this equation does not define a name . \ This looks like deadcode . . ] " @@ output_location loc | Wreset_target_state ( actual_reset , expected_reset ) -> eprintf " [ @% aType warning : the target state is expected to be % s , , @\ but is entered by % s . . ] " @@ output_location loc ( if expected_reset then " reset " else " on history " ) ( if actual_reset then " reset " else " history " )
let fresh_env ( ) = let initially_opened_module = if ! Clflags . nopervasives then None else Some " Stdlib " in Typemod . initial_env ~ loc ( : Location . in_file " command line " ) ~ safe_string ( : not ! Clflags . unsafe_string ) ~ initially_opened_module ~ open_implicit_modules ( : List . rev ! Clflags . open_modules )
module Rewrite_loc = struct let queue = ref [ ] let update l = if l <> none then match ! queue with | [ ] -> assert false | l ' :: ls -> queue := Location_aux . union l l ' :: ls let enter ( ) = queue := Location . none :: ! queue let leave l0 = match ! queue with | [ ] -> assert false | [ l ] -> queue := [ ] ; Location_aux . extend l0 l | l :: l ' :: ls -> let l = Location_aux . extend l0 l in queue := Location_aux . union l l ' :: ls ; l let start ( ) = assert ( ! queue = [ ] ) ; enter ( ) let exit ( ) = match ! queue with | [ _ ] -> queue := [ ] | _ -> assert false let u_option f = function | None -> None | Some x -> Some ( f x ) let u_loc ( loc : _ Location . loc ) = update loc . loc ; loc let rec u_attribute { attr_name = loc ; attr_payload ; attr_loc } = let loc = if Location_aux . is_relaxed_location loc then loc else u_loc loc in { attr_name = loc ; attr_payload = u_payload attr_payload ; attr_loc } and u_extension ( loc , payload ) = let loc = if Location_aux . is_relaxed_location loc then loc else u_loc loc in ( loc , u_payload payload ) and u_attributes l = List . map ~ f : u_attribute l and u_payload = function | PStr str -> PStr ( u_structure str ) | PSig sg -> PSig ( u_signature sg ) | PTyp ct -> PTyp ( u_core_type ct ) | PPat ( p , eo ) -> PPat ( u_pattern p , u_option u_expression eo ) and u_core_type { ptyp_desc ; ptyp_attributes ; ptyp_loc ; ptyp_loc_stack } = enter ( ) ; let ptyp_desc = u_core_type_desc ptyp_desc in let ptyp_attributes = u_attributes ptyp_attributes in let ptyp_loc = leave ptyp_loc in { ptyp_desc ; ptyp_loc ; ptyp_attributes ; ptyp_loc_stack } and u_core_type_desc = function | Ptyp_any | Ptyp_var _ as desc -> desc | Ptyp_arrow ( l , t1 , t2 ) -> Ptyp_arrow ( l , u_core_type t1 , u_core_type t2 ) | Ptyp_tuple ts -> Ptyp_tuple ( List . map ~ f : u_core_type ts ) | Ptyp_constr ( loc , ts ) -> Ptyp_constr ( u_loc loc , List . map ~ f : u_core_type ts ) | Ptyp_object ( fields , flag ) -> let object_field_desc = function | Otag ( lbl , ct ) -> Otag ( lbl , u_core_type ct ) | Oinherit ct -> Oinherit ( u_core_type ct ) in let object_field { pof_desc ; pof_loc ; pof_attributes } = { pof_desc = object_field_desc pof_desc ; pof_attributes = u_attributes pof_attributes ; pof_loc } in Ptyp_object ( List . map ~ f : object_field fields , flag ) | Ptyp_class ( loc , ts ) -> Ptyp_class ( u_loc loc , List . map ~ f : u_core_type ts ) | Ptyp_alias ( ct , name ) -> Ptyp_alias ( u_core_type ct , name ) | Ptyp_variant ( fields , flag , label ) -> Ptyp_variant ( List . map ~ f : u_row_field fields , flag , label ) | Ptyp_poly ( ss , ct ) -> Ptyp_poly ( ss , u_core_type ct ) | Ptyp_package pt -> Ptyp_package ( u_package_type pt ) | Ptyp_extension ext -> Ptyp_extension ( u_extension ext ) and u_package_type ( loc , cts ) = ( u_loc loc , List . map ~ f ( : fun ( l , ct ) -> u_loc l , u_core_type ct ) cts ) and u_row_field { prf_desc ; prf_loc ; prf_attributes } = let desc = function | Rtag ( l , has_const , cts ) -> Rtag ( l , has_const , List . map ~ f : u_core_type cts ) | Rinherit ct -> Rinherit ( u_core_type ct ) in { prf_desc = desc prf_desc ; prf_loc ; prf_attributes = u_attributes prf_attributes } and u_pattern { ppat_desc ; ppat_loc ; ppat_attributes ; ppat_loc_stack } = enter ( ) ; let ppat_desc = u_pattern_desc ppat_desc in let ppat_attributes = u_attributes ppat_attributes in let ppat_loc = leave ppat_loc in { ppat_desc ; ppat_loc ; ppat_attributes ; ppat_loc_stack } and u_pattern_desc = function | Ppat_any | Ppat_constant _ | Ppat_interval _ as p -> p | Ppat_var l -> Ppat_var ( u_loc l ) | Ppat_alias ( p , l ) -> Ppat_alias ( u_pattern p , u_loc l ) | Ppat_tuple ps -> Ppat_tuple ( List . map ~ f : u_pattern ps ) | Ppat_construct ( loc , po ) -> Ppat_construct ( u_loc loc , u_option u_pattern po ) | Ppat_variant ( lbl , po ) -> Ppat_variant ( lbl , u_option u_pattern po ) | Ppat_record ( fields , flag ) -> Ppat_record ( List . map ~ f ( : fun ( l , p ) -> ( u_loc l , u_pattern p ) ) fields , flag ) | Ppat_array ps -> Ppat_array ( List . map ~ f : u_pattern ps ) | Ppat_or ( p1 , p2 ) -> Ppat_or ( u_pattern p1 , u_pattern p2 ) | Ppat_constraint ( p , ct ) -> Ppat_constraint ( u_pattern p , u_core_type ct ) | Ppat_type loc -> Ppat_type ( u_loc loc ) | Ppat_lazy p -> Ppat_lazy ( u_pattern p ) | Ppat_unpack loc -> Ppat_unpack ( u_loc loc ) | Ppat_exception p -> Ppat_exception ( u_pattern p ) | Ppat_extension ext -> Ppat_extension ( u_extension ext ) | Ppat_open ( l , p ) -> Ppat_open ( u_loc l , u_pattern p ) and u_expression { pexp_desc ; pexp_loc ; pexp_attributes ; pexp_loc_stack } = enter ( ) ; let pexp_desc = u_expression_desc pexp_desc in let pexp_attributes = u_attributes pexp_attributes in let pexp_loc = leave pexp_loc in { pexp_desc ; pexp_loc ; pexp_attributes ; pexp_loc_stack } and u_expression_desc = function | Pexp_ident loc -> Pexp_ident ( u_loc loc ) | Pexp_constant _ as e -> e | Pexp_let ( flag , vs , e ) -> Pexp_let ( flag , List . map ~ f : u_value_binding vs , u_expression e ) | Pexp_function cs -> Pexp_function ( List . map ~ f : u_case cs ) | Pexp_fun ( lbl , eo , pattern , expr ) -> Pexp_fun ( lbl , u_option u_expression eo , u_pattern pattern , u_expression expr ) | Pexp_apply ( e , les ) -> Pexp_apply ( u_expression e , List . map ~ f ( : fun ( l , e ) -> ( l , u_expression e ) ) les ) | Pexp_match ( e , cs ) -> Pexp_match ( u_expression e , List . map ~ f : u_case cs ) | Pexp_try ( e , cs ) -> Pexp_try ( u_expression e , List . map ~ f : u_case cs ) | Pexp_tuple es -> Pexp_tuple ( List . map ~ f : u_expression es ) | Pexp_construct ( loc , eo ) -> Pexp_construct ( u_loc loc , u_option u_expression eo ) | Pexp_variant ( lbl , eo ) -> Pexp_variant ( lbl , u_option u_expression eo ) | Pexp_record ( les , eo ) -> Pexp_record ( List . map ~ f ( : fun ( loc , e ) -> ( u_loc loc , u_expression e ) ) les , u_option u_expression eo ) | Pexp_field ( e , loc ) -> Pexp_field ( u_expression e , u_loc loc ) | Pexp_setfield ( e1 , loc , e2 ) -> Pexp_setfield ( u_expression e1 , u_loc loc , u_expression e2 ) | Pexp_array es -> Pexp_array ( List . map ~ f : u_expression es ) | Pexp_ifthenelse ( e1 , e2 , e3 ) -> Pexp_ifthenelse ( u_expression e1 , u_expression e2 , u_option u_expression e3 ) | Pexp_sequence ( e1 , e2 ) -> Pexp_sequence ( u_expression e1 , u_expression e2 ) | Pexp_while ( e1 , e2 ) -> Pexp_while ( u_expression e1 , u_expression e2 ) | Pexp_for ( p , e1 , e2 , flag , e3 ) -> Pexp_for ( u_pattern p , u_expression e1 , u_expression e2 , flag , u_expression e3 ) | Pexp_constraint ( e , ct ) -> Pexp_constraint ( u_expression e , u_core_type ct ) | Pexp_coerce ( e , cto , ct ) -> Pexp_coerce ( u_expression e , u_option u_core_type cto , u_core_type ct ) | Pexp_send ( e , s ) -> Pexp_send ( u_expression e , s ) | Pexp_new loc -> Pexp_new ( u_loc loc ) | Pexp_setinstvar ( s , e ) -> Pexp_setinstvar ( u_loc s , u_expression e ) | Pexp_override es -> Pexp_override ( List . map ~ f ( : fun ( loc , e ) -> ( u_loc loc , u_expression e ) ) es ) | Pexp_letmodule ( s , me , e ) -> Pexp_letmodule ( u_loc s , u_module_expr me , u_expression e ) | Pexp_letexception ( c , e ) -> Pexp_letexception ( u_extension_constructor c , u_expression e ) | Pexp_assert e -> Pexp_assert ( u_expression e ) | Pexp_lazy e -> Pexp_lazy ( u_expression e ) | Pexp_poly ( e , cto ) -> Pexp_poly ( u_expression e , u_option u_core_type cto ) | Pexp_object cs -> Pexp_object ( u_class_structure cs ) | Pexp_newtype ( s , e ) -> Pexp_newtype ( s , u_expression e ) | Pexp_pack me -> Pexp_pack ( u_module_expr me ) | Pexp_open ( od , e ) -> Pexp_open ( u_open_declaration od , u_expression e ) | Pexp_extension ext -> Pexp_extension ( u_extension ext ) | Pexp_unreachable -> Pexp_unreachable | Pexp_letop { let_ ; ands ; body } -> Pexp_letop { let_ = u_binding_op let_ ; ands = List . map ~ f : u_binding_op ands ; body = u_expression body ; } and u_binding_op { pbop_op ; pbop_pat ; pbop_exp ; pbop_loc } = { pbop_op = u_loc pbop_op ; pbop_pat = u_pattern pbop_pat ; pbop_exp = u_expression pbop_exp ; pbop_loc } and u_case { pc_lhs ; pc_guard ; pc_rhs } = { pc_lhs = u_pattern pc_lhs ; pc_guard = u_option u_expression pc_guard ; pc_rhs = u_expression pc_rhs ; } and u_value_description { pval_name ; pval_type ; pval_prim ; pval_attributes ; pval_loc } = enter ( ) ; let pval_name = u_loc pval_name in let pval_type = u_core_type pval_type in let pval_attributes = u_attributes pval_attributes in let pval_loc = leave pval_loc in { pval_name ; pval_type ; pval_prim ; pval_attributes ; pval_loc } and u_type_declaration { ptype_name ; ptype_params ; ptype_cstrs ; ptype_kind ; ptype_private ; ptype_manifest ; ptype_attributes ; ptype_loc } = enter ( ) ; let ptype_name = u_loc ptype_name and ptype_params = List . map ~ f ( : fun ( ct , v ) -> ( u_core_type ct , v ) ) ptype_params and ptype_cstrs = List . map ~ f ( : fun ( ct1 , ct2 , l ) -> update l ; ( u_core_type ct1 , u_core_type ct2 , l ) ) ptype_cstrs and ptype_kind = u_type_kind ptype_kind and ptype_manifest = u_option u_core_type ptype_manifest and ptype_attributes = u_attributes ptype_attributes in let ptype_loc = leave ptype_loc in { ptype_name ; ptype_params ; ptype_cstrs ; ptype_kind ; ptype_private ; ptype_manifest ; ptype_attributes ; ptype_loc } and u_type_kind = function | Ptype_abstract | Ptype_open as k -> k | Ptype_variant cstrs -> Ptype_variant ( List . map ~ f : u_constructor_declaration cstrs ) | Ptype_record lbls -> Ptype_record ( List . map ~ f : u_label_declaration lbls ) and u_label_declaration { pld_name ; pld_mutable ; pld_type ; pld_loc ; pld_attributes } = enter ( ) ; let pld_name = u_loc pld_name in let pld_type = u_core_type pld_type in let pld_attributes = u_attributes pld_attributes in let pld_loc = leave pld_loc in { pld_name ; pld_mutable ; pld_type ; pld_loc ; pld_attributes } and u_constructor_declaration { pcd_name ; pcd_args ; pcd_res ; pcd_loc ; pcd_attributes } = enter ( ) ; let pcd_name = u_loc pcd_name in let pcd_args = u_constructor_arguments pcd_args in let pcd_res = u_option u_core_type pcd_res in let pcd_attributes = u_attributes pcd_attributes in let pcd_loc = leave pcd_loc in { pcd_name ; pcd_args ; pcd_res ; pcd_loc ; pcd_attributes } and u_constructor_arguments = function | Pcstr_tuple cts -> Pcstr_tuple ( List . map ~ f : u_core_type cts ) | Pcstr_record lbls -> Pcstr_record ( List . map ~ f : u_label_declaration lbls ) and u_type_extension { ptyext_path ; ptyext_params ; ptyext_constructors ; ptyext_private ; ptyext_attributes ; ptyext_loc } = let ptyext_path = u_loc ptyext_path in let ptyext_params = List . map ~ f ( : fun ( ct , v ) -> ( u_core_type ct , v ) ) ptyext_params in let ptyext_constructors = List . map ~ f : u_extension_constructor ptyext_constructors in let ptyext_attributes = u_attributes ptyext_attributes in { ptyext_path ; ptyext_params ; ptyext_constructors ; ptyext_private ; ptyext_attributes ; ptyext_loc } and u_extension_constructor { pext_name ; pext_kind ; pext_loc ; pext_attributes } = enter ( ) ; let pext_name = u_loc pext_name in let pext_kind = u_extension_constructor_kind pext_kind in let pext_attributes = u_attributes pext_attributes in let pext_loc = leave pext_loc in { pext_name ; pext_kind ; pext_loc ; pext_attributes } and u_extension_constructor_kind = function | Pext_decl ( cargs , cto ) -> Pext_decl ( u_constructor_arguments cargs , u_option u_core_type cto ) | Pext_rebind loc -> Pext_rebind ( u_loc loc ) and u_class_type { pcty_desc ; pcty_loc ; pcty_attributes } = enter ( ) ; let pcty_desc = u_class_type_desc pcty_desc in let pcty_attributes = u_attributes pcty_attributes in let pcty_loc = leave pcty_loc in { pcty_desc ; pcty_loc ; pcty_attributes } and u_class_type_desc = function | Pcty_constr ( loc , cts ) -> Pcty_constr ( u_loc loc , List . map ~ f : u_core_type cts ) | Pcty_signature cs -> Pcty_signature ( u_class_signature cs ) | Pcty_arrow ( lbl , ct , clt ) -> Pcty_arrow ( lbl , u_core_type ct , u_class_type clt ) | Pcty_extension ext -> Pcty_extension ( u_extension ext ) | Pcty_open ( od , cty ) -> Pcty_open ( u_open_description od , u_class_type cty ) and u_class_signature { pcsig_self ; pcsig_fields } = let pcsig_self = u_core_type pcsig_self in let pcsig_fields = List . map ~ f : u_class_type_field pcsig_fields in { pcsig_self ; pcsig_fields } and u_class_type_field { pctf_desc ; pctf_loc ; pctf_attributes } = enter ( ) ; let pctf_desc = u_class_type_field_desc pctf_desc in let pctf_attributes = u_attributes pctf_attributes in let pctf_loc = leave pctf_loc in { pctf_desc ; pctf_loc ; pctf_attributes } and u_class_type_field_desc = function | Pctf_inherit clt -> Pctf_inherit ( u_class_type clt ) | Pctf_val ( s , fl1 , fl2 , ct ) -> Pctf_val ( s , fl1 , fl2 , u_core_type ct ) | Pctf_method ( s , fl1 , fl2 , ct ) -> Pctf_method ( s , fl1 , fl2 , u_core_type ct ) | Pctf_constraint ( ct1 , ct2 ) -> Pctf_constraint ( u_core_type ct1 , u_core_type ct2 ) | Pctf_attribute attr -> Pctf_attribute ( u_attribute attr ) | Pctf_extension ext -> Pctf_extension ( u_extension ext ) and u_class_infos : ' a ' b . ( ' a -> ' b ) -> ' a class_infos -> ' b class_infos = fun u_a { pci_virt ; pci_params ; pci_name ; pci_expr ; pci_loc ; pci_attributes } -> enter ( ) ; let pci_params = List . map ~ f ( : fun ( ct , v ) -> ( u_core_type ct , v ) ) pci_params in let pci_name = u_loc pci_name in let pci_expr = u_a pci_expr in let pci_attributes = u_attributes pci_attributes in let pci_loc = leave pci_loc in { pci_virt ; pci_params ; pci_name ; pci_expr ; pci_loc ; pci_attributes } and u_class_description clt = u_class_infos u_class_type clt and u_class_type_declaration clt = u_class_infos u_class_type clt and u_class_expr { pcl_desc ; pcl_loc ; pcl_attributes } = enter ( ) ; let pcl_desc = u_class_expr_desc pcl_desc in let pcl_attributes = u_attributes pcl_attributes in let pcl_loc = leave pcl_loc in { pcl_desc ; pcl_loc ; pcl_attributes } and u_class_expr_desc = function | Pcl_constr ( loc , cts ) -> Pcl_constr ( u_loc loc , List . map ~ f : u_core_type cts ) | Pcl_structure cs -> Pcl_structure ( u_class_structure cs ) | Pcl_fun ( lbl , eo , p , ce ) -> Pcl_fun ( lbl , u_option u_expression eo , u_pattern p , u_class_expr ce ) | Pcl_apply ( ce , les ) -> Pcl_apply ( u_class_expr ce , List . map ~ f ( : fun ( l , e ) -> ( l , u_expression e ) ) les ) | Pcl_let ( rf , vbs , ce ) -> Pcl_let ( rf , List . map ~ f : u_value_binding vbs , u_class_expr ce ) | Pcl_constraint ( ce , ct ) -> Pcl_constraint ( u_class_expr ce , u_class_type ct ) | Pcl_extension ext -> Pcl_extension ( u_extension ext ) | Pcl_open ( od , ce ) -> Pcl_open ( u_open_description od , u_class_expr ce ) and u_class_structure { pcstr_self ; pcstr_fields } = let pcstr_self = u_pattern pcstr_self in let pcstr_fields = List . map ~ f : u_class_field pcstr_fields in { pcstr_self ; pcstr_fields } and u_class_field { pcf_desc ; pcf_loc ; pcf_attributes } = enter ( ) ; let pcf_desc = u_class_field_desc pcf_desc in let pcf_attributes = u_attributes pcf_attributes in let pcf_loc = leave pcf_loc in { pcf_desc ; pcf_loc ; pcf_attributes } and u_class_field_desc = function | Pcf_inherit ( fl , ce , so ) -> Pcf_inherit ( fl , u_class_expr ce , so ) | Pcf_val ( loc , fl , cfk ) -> Pcf_val ( u_loc loc , fl , u_class_field_kind cfk ) | Pcf_method ( loc , fl , cfk ) -> Pcf_method ( u_loc loc , fl , u_class_field_kind cfk ) | Pcf_constraint ( c1 , c2 ) -> Pcf_constraint ( u_core_type c1 , u_core_type c2 ) | Pcf_initializer e -> Pcf_initializer ( u_expression e ) | Pcf_attribute attr -> Pcf_attribute ( u_attribute attr ) | Pcf_extension ext -> Pcf_extension ( u_extension ext ) and u_class_field_kind = function | Cfk_virtual ct -> Cfk_virtual ( u_core_type ct ) | Cfk_concrete ( fl , e ) -> Cfk_concrete ( fl , u_expression e ) and u_class_declaration cd = u_class_infos u_class_expr cd and u_module_type { pmty_desc ; pmty_loc ; pmty_attributes } = enter ( ) ; let pmty_desc = u_module_type_desc pmty_desc in let pmty_attributes = u_attributes pmty_attributes in let pmty_loc = leave pmty_loc in { pmty_desc ; pmty_loc ; pmty_attributes } and u_module_type_desc = function | Pmty_ident loc -> Pmty_ident ( u_loc loc ) | Pmty_signature sg -> Pmty_signature ( u_signature sg ) | Pmty_functor ( fp , mt ) -> Pmty_functor ( u_functor_parameter fp , u_module_type mt ) | Pmty_with ( mt , wts ) -> Pmty_with ( u_module_type mt , List . map ~ f : u_with_constraint wts ) | Pmty_typeof me -> Pmty_typeof ( u_module_expr me ) | Pmty_extension ext -> Pmty_extension ( u_extension ext ) | Pmty_alias loc -> Pmty_alias ( u_loc loc ) and u_functor_parameter = function | Unit -> Unit | Named ( name , mt ) -> Named ( u_loc name , u_module_type mt ) and u_signature l = List . map ~ f : u_signature_item l and u_signature_item { psig_desc ; psig_loc } = enter ( ) ; let psig_desc = u_signature_item_desc psig_desc in let psig_loc = leave psig_loc in { psig_desc ; psig_loc } and u_signature_item_desc = function | Psig_value vd -> Psig_value ( u_value_description vd ) | Psig_type ( fl , tds ) -> Psig_type ( fl , List . map ~ f : u_type_declaration tds ) | Psig_typext text -> Psig_typext ( u_type_extension text ) | Psig_exception texn -> Psig_exception ( u_type_exception texn ) | Psig_module md -> Psig_module ( u_module_declaration md ) | Psig_recmodule mds -> Psig_recmodule ( List . map ~ f : u_module_declaration mds ) | Psig_modtype mtd -> Psig_modtype ( u_module_type_declaration mtd ) | Psig_open od -> Psig_open ( u_open_description od ) | Psig_include id -> Psig_include ( u_include_description id ) | Psig_class cds -> Psig_class ( List . map ~ f : u_class_description cds ) | Psig_class_type cts -> Psig_class_type ( List . map ~ f : u_class_type_declaration cts ) | Psig_attribute attr -> Psig_attribute ( u_attribute attr ) | Psig_extension ( ext , attrs ) -> Psig_extension ( u_extension ext , u_attributes attrs ) | Psig_typesubst tds -> Psig_typesubst ( List . map ~ f : u_type_declaration tds ) | Psig_modsubst ms -> Psig_modsubst ( u_module_substitution ms ) and u_type_exception { ptyexn_constructor ; ptyexn_loc ; ptyexn_attributes } = { ptyexn_constructor = u_extension_constructor ptyexn_constructor ; ptyexn_loc ; ptyexn_attributes = u_attributes ptyexn_attributes } and u_module_declaration { pmd_name ; pmd_type ; pmd_attributes ; pmd_loc } = enter ( ) ; let pmd_name = u_loc pmd_name in let pmd_type = u_module_type pmd_type in let pmd_attributes = u_attributes pmd_attributes in let pmd_loc = leave pmd_loc in { pmd_name ; pmd_type ; pmd_attributes ; pmd_loc } and u_module_substitution { pms_name ; pms_manifest ; pms_attributes ; pms_loc } = let pms_name = u_loc pms_name in let pms_manifest = u_loc pms_manifest in let pms_attributes = u_attributes pms_attributes in { pms_name ; pms_manifest ; pms_attributes ; pms_loc } and u_module_type_declaration { pmtd_name ; pmtd_type ; pmtd_attributes ; pmtd_loc } = enter ( ) ; let pmtd_name = u_loc pmtd_name in let pmtd_type = u_option u_module_type pmtd_type in let pmtd_attributes = u_attributes pmtd_attributes in let pmtd_loc = leave pmtd_loc in { pmtd_name ; pmtd_type ; pmtd_attributes ; pmtd_loc } and u_open_declaration { popen_expr ; popen_override ; popen_loc ; popen_attributes } = enter ( ) ; let popen_expr = u_module_expr popen_expr in let popen_attributes = u_attributes popen_attributes in let popen_loc = leave popen_loc in { popen_expr ; popen_override ; popen_loc ; popen_attributes } and u_open_description { popen_expr ; popen_override ; popen_loc ; popen_attributes } = enter ( ) ; let popen_expr = u_loc popen_expr in let popen_attributes = u_attributes popen_attributes in let popen_loc = leave popen_loc in { popen_expr ; popen_override ; popen_loc ; popen_attributes } and u_include_infos : ' a ' b . ( ' a -> ' b ) -> ' a include_infos -> ' b include_infos = fun u_a { pincl_mod ; pincl_loc ; pincl_attributes } -> enter ( ) ; let pincl_mod = u_a pincl_mod in let pincl_attributes = u_attributes pincl_attributes in let pincl_loc = leave pincl_loc in { pincl_mod ; pincl_loc ; pincl_attributes } and u_include_description id = u_include_infos u_module_type id and u_include_declaration id = u_include_infos u_module_expr id and u_with_constraint = function | Pwith_type ( loc , td ) -> Pwith_type ( u_loc loc , u_type_declaration td ) | Pwith_module ( loc1 , loc2 ) -> Pwith_module ( u_loc loc1 , u_loc loc2 ) | Pwith_typesubst ( loc , td ) -> Pwith_typesubst ( u_loc loc , u_type_declaration td ) | Pwith_modsubst ( loc1 , loc2 ) -> Pwith_modsubst ( u_loc loc1 , u_loc loc2 ) and u_module_expr { pmod_desc ; pmod_loc ; pmod_attributes } = enter ( ) ; let pmod_desc = u_module_expr_desc pmod_desc in let pmod_attributes = u_attributes pmod_attributes in let pmod_loc = leave pmod_loc in { pmod_desc ; pmod_loc ; pmod_attributes } and u_module_expr_desc = function | Pmod_ident loc -> Pmod_ident ( u_loc loc ) | Pmod_structure str -> Pmod_structure ( u_structure str ) | Pmod_functor ( fp , me ) -> Pmod_functor ( u_functor_parameter fp , u_module_expr me ) | Pmod_apply ( me1 , me2 ) -> Pmod_apply ( u_module_expr me1 , u_module_expr me2 ) | Pmod_constraint ( me , mt ) -> Pmod_constraint ( u_module_expr me , u_module_type mt ) | Pmod_unpack e -> Pmod_unpack ( u_expression e ) | Pmod_extension ext -> Pmod_extension ( u_extension ext ) and u_structure l = List . map ~ f : u_structure_item l and u_structure_item { pstr_desc ; pstr_loc } = enter ( ) ; let pstr_desc = u_structure_item_desc pstr_desc in let pstr_loc = leave pstr_loc in { pstr_desc ; pstr_loc } and u_structure_item_desc = function | Pstr_eval ( expr , attrs ) -> Pstr_eval ( u_expression expr , u_attributes attrs ) | Pstr_value ( fl , vbs ) -> Pstr_value ( fl , List . map ~ f : u_value_binding vbs ) | Pstr_primitive vd -> Pstr_primitive ( u_value_description vd ) | Pstr_type ( fl , tds ) -> Pstr_type ( fl , List . map ~ f : u_type_declaration tds ) | Pstr_typext text -> Pstr_typext ( u_type_extension text ) | Pstr_exception texn -> Pstr_exception ( u_type_exception texn ) | Pstr_module mb -> Pstr_module ( u_module_binding mb ) | Pstr_recmodule mbs -> Pstr_recmodule ( List . map ~ f : u_module_binding mbs ) | Pstr_modtype mtd -> Pstr_modtype ( u_module_type_declaration mtd ) | Pstr_open od -> Pstr_open ( u_open_declaration od ) | Pstr_class cds -> Pstr_class ( List . map ~ f : u_class_declaration cds ) | Pstr_class_type ctds -> Pstr_class_type ( List . map ~ f : u_class_type_declaration ctds ) | Pstr_include id -> Pstr_include ( u_include_declaration id ) | Pstr_attribute attr -> Pstr_attribute ( u_attribute attr ) | Pstr_extension ( ext , attrs ) -> Pstr_extension ( u_extension ext , u_attributes attrs ) and u_value_binding { pvb_pat ; pvb_expr ; pvb_attributes ; pvb_loc } = enter ( ) ; let pvb_pat = u_pattern pvb_pat in let pvb_expr = u_expression pvb_expr in let pvb_attributes = u_attributes pvb_attributes in let pvb_loc = leave pvb_loc in { pvb_pat ; pvb_expr ; pvb_attributes ; pvb_loc } and u_module_binding { pmb_name ; pmb_expr ; pmb_attributes ; pmb_loc } = enter ( ) ; let pmb_name = u_loc pmb_name in let pmb_expr = u_module_expr pmb_expr in let pmb_attributes = u_attributes pmb_attributes in let pmb_loc = leave pmb_loc in { pmb_name ; pmb_expr ; pmb_attributes ; pmb_loc } end
let rewrite_loc t = Rewrite_loc . start ( ) ; let t = match t with | ` str str -> ` str ( Rewrite_loc . u_structure str ) | ` fake str -> ` fake ( Rewrite_loc . u_structure str ) | ` sg sg -> ` sg ( Rewrite_loc . u_signature sg ) in Rewrite_loc . exit ( ) ; t
type value = QuotedList of value list | Symbol of string | Keyword of string | Variable of string | Number of int | Boolean of bool | String of string | Plus | Minus | Divide | Multiply | Modulo | LT | LTE | GT | GTE | EQ | NEQ | AND | OR | LParen | RParen | Quote | EOF
type sexp = Atom of value | List of sexp list
let boolean_of_string s = match s with | " # f " -> false | _ -> true
let rec debug_string_of_value value = match value with | QuotedList values -> " ' ( " ( ^ String . concat " , " ( List . map ( fun value -> string_of_value value ) values ) ) " ) " ^ | Symbol s -> " Symbol ( " ^ s " ) " ^ | Variable s -> " Variable ( " ^ s " ) " ^ | Keyword kw -> " Keyword ( " ^ kw " ) " ^ | Number s -> " Number ( " ( ^ string_of_int s ) " ) " ^ | Quote -> " Quote " | String s -> " String ( " ^ s " ) " ^ | _ -> string_of_value value " [ " ( ^ String . concat " , " ( List . map ( fun value -> debug_string_of_value value ) values ) ) " ] " ^ match value with | Symbol s -> s | Keyword kw -> kw | Variable s -> s | Number s -> ( string_of_int s ) | Boolean s -> if s then " # t " else " # f " | String s -> s | LParen -> " LParen " | RParen -> " RParen " | Plus -> " " + | Minus -> " " - | Divide -> " " / | Multiply -> " " * | Modulo -> " " % | EOF -> " \ n " | LT -> " " < | LTE -> " " <= | GT -> " " > | GTE -> " " >= | EQ -> " " = | NEQ -> " " /= | AND -> " and " | OR -> " or " | Quote -> " ' " | QuotedList values -> " ( " ( ^ String . concat " " ( List . map ( fun value -> string_of_value value ) values ) ) " ) " ^ " [ " ( ^ String . concat " " ( List . map ( fun value -> string_of_value value ) values ) ) " ] " ^
let rec string_of_sexp sexpr = match sexpr with | Atom x -> " Atom ( " ( ^ string_of_value x ) " ) " ^ | List xs -> " List ( " ( ^ String . concat " " ( List . map string_of_sexp xs ) ) " ) " ^
type test = { snippet : string ; loc : Lexing . position ; exn : exn }
let name_table ( defns : Unresolved . t list ) = List . map defns ~ f ( : fun ( def : _ Named . t ) -> ( def . name , def ) ) |> String . Map . of_list_reducei ~ f ( : fun name v1 v2 -> let open Unresolved in match ( v1 . Named . data , v2 . data ) with | Enum_anon _ , _ -> v1 | _ , Enum_anon _ -> v2 | _ , _ -> if v1 = v2 then v1 else let open Dyn . Encoder in Code_error . raise " definition conflict " [ ( " name " , string name ) ] )
let resolve_all ( defns : Unresolved . t list ) = let names = name_table defns in let defns = String . Map . values names in let rename_change_field = object inherit Unresolved . map as super method ! field x = if x . name = " change " then match x . data with | Single { typ = Ident " number " ; optional = true } -> let typ = Unresolved . Ident " TextDocumentSyncKind " in let data = Unresolved . Single { typ ; optional = true } in super # field { x with data } | _ -> super # field x else super # field x end in let unresolved = List . map defns ~ f : rename_change_field # t in Ts_types . resolve_all unresolved ~ names
let test_snippets s = let fails , succs = List . partition_map s ~ f ( : fun s -> let lexbuf = Lexing . from_string s in try Right ( Ts_parser . main Ts_lexer . token lexbuf ) with | exn -> Left { snippet = s ; loc = lexbuf . lex_curr_p ; exn } ) in ignore ( resolve_all ( List . concat succs ) ) ; fails
let pp_results ppf tests = List . iteri tests ~ f ( : fun i { snippet ; loc ; exn } -> Format . pp_print_string ppf snippet ; Format . fprintf ppf " line : % d char : % d . " @ loc . pos_lnum ( loc . pos_cnum - loc . pos_bol ) ; Format . fprintf ppf " % d . exn : % s . " @%! ( i + 1 ) ( Printexc . to_string exn ) ; Format . fprintf ppf " . . " ) @---@
let of_snippets s = List . concat_map s ~ f ( : fun s -> let lexbuf = Lexing . from_string s in try Ts_parser . main Ts_lexer . token lexbuf with | _exn -> [ ] )
module Type_var_names = struct let last_char : char ref = ref ' a ' let table : ( Types . type_expr , char ) Hashtbl . t = Hashtbl . create 1024 let reset ( ) = last_char := ' a ' let find t = match Hashtbl . find_opt table t with | None -> Hashtbl . add table t ! last_char ; let ret = String . make 1 ! last_char in last_char := Char . chr ( Char . code ! last_char + 1 ) ; ret | Some v -> String . make 1 v end
module Fun = struct let rec mk_type_expr : Types . type_expr -> Erlang . Ast . type_expr = fun type_expr -> match type_expr . desc with | Tarrow ( _ , _ , _ , _ ) -> ( match Uncurry . from_type_expr type_expr with | ` Uncurried ( args , return ) -> let args = List . map mk_type_expr args in let return = mk_type_expr return in Type . fun_ ~ args ~ return | ` Not_a_function -> Format . fprintf Format . std_formatter " Tried to uncurry a non - function type !\ n " ; %! Printtyp . type_expr Format . std_formatter type_expr ; Format . fprintf Format . std_formatter " \ n " ; %! Error . unsupported_feature ` Uncurryable_functions ) | Tconstr ( p , args , _ ) -> let name , args = Names . type_name_of_path p ~ args in let args = List . map mk_type_expr args in Type . apply ~ name ~ args | Ttuple els -> let parts = els |> List . map mk_type_expr in Type . tuple parts | Tlink t -> mk_type_expr ( Btype . repr t ) | Tvar ( Some name ) -> Type . var ( Name . var ( " _ " ^ name ) ) | Tvar None -> Type . var ( Name . var ( Type_var_names . find type_expr ) ) | Tnil -> Type . apply ~ name ( : Name . atom ( Atom . mk " list " ) ) ~ args [ ] : | Tvariant { row_fields ; _ } -> let row_field_to_type_expr = function | Rpresent ( Some texpr ) -> [ mk_type_expr texpr ] | Rpresent None -> [ ] | Reither ( _ , args , _ , _ ) -> List . map mk_type_expr args | _ -> Format . fprintf Format . std_formatter " Tried to build a type expr for an odd variant constructor !\ n " ; %! Printtyp . type_expr Format . std_formatter type_expr ; Format . fprintf Format . std_formatter " \ n " ; %! Printtyp . raw_type_expr Format . std_formatter type_expr ; Format . fprintf Format . std_formatter " \ n " ; %! Error . unsupported_feature ` Absent_polymorphic_variants in let row_field_to_constr ( name , args ) = let name = Const . atom ( Atom . lowercase ( Atom . mk name ) ) in let args = row_field_to_type_expr args in match args with | [ ] -> Type . const name | _ -> Type . tuple ( Type . const name :: args ) in List . map row_field_to_constr row_fields |> Type . variant | Tpoly ( _ , _ ) | Tfield ( _ , _ , _ , _ ) | Tsubst _ | Tunivar _ | Tobject _ | Tpackage _ -> Format . fprintf Format . std_formatter " Tried to build a type expr for an unsupported feature !\ n " ; %! Printtyp . type_expr Format . std_formatter type_expr ; Format . fprintf Format . std_formatter " \ n " ; %! Printtyp . raw_type_expr Format . std_formatter type_expr ; Format . fprintf Format . std_formatter " \ n " ; %! Error . unsupported_feature ` Type_constructs let mk_spec : Types . value_description -> Erlang . Ast . type_expr option = fun { val_type ; _ } -> Type_var_names . reset ( ) ; match Uncurry . from_type_expr val_type with | ` Uncurried ( args , return ) -> let args = List . map mk_type_expr args in let return = mk_type_expr return in let fun_ = Type . fun_ ~ args ~ return in let clean_fun = Type . clean_unbound_named_vars fun_ in Some clean_fun | ` Not_a_function -> None let find_spec : typedtree : Typedtree . structure -> Erlang . Ast . atom -> Erlang . Ast . type_expr option = fun ~ typedtree name -> match List . filter_map ( function | Types . Sig_value ( id , vd , _ ) -> ( let type_name = Names . atom_of_ident id in match Atom . equal type_name name with | true -> mk_spec vd | false -> None ) | _ -> None ) typedtree . str_type with | [ x ] -> Some x | _ -> None end
let rec is_unit ( t : Types . type_expr ) = match t . desc with | Tconstr ( p , _ , _ ) -> Path . same p Predef . path_unit | Tlink t ' -> is_unit ( Btype . repr t ' ) | _ -> false
let is_opaque_in_signature type_decl signature = match signature with | None -> Type . type_ | Some sign -> List . fold_left ( fun kind sig_item -> match sig_item with | Sig_type ( name , { type_manifest = None ; _ } , _ , _ ) when Ident . name name = Ident . name type_decl . typ_id -> Type . opaque | _ -> kind ) Type . type_ sign
let rec mk_type_expr core_type = match core_type . ctyp_desc with | Ttyp_any -> Some Type . any | Ttyp_var var_name -> Some ( Type . var ( Name . var var_name ) ) | Ttyp_arrow ( _ , param , out ) -> let rec args t acc = match t . ctyp_desc with | Ttyp_arrow ( _ , p , t ' ) -> args t ' ( p :: acc ) | _ -> t :: acc in let args = args out [ param ] |> List . filter_map mk_type_expr in let return = List . hd args in let args = List . rev ( List . tl args ) in Some ( Type . fun_ ~ args ~ return ) | Ttyp_constr ( _ , { txt ; _ } , args ) -> let name , args = Names . longident_to_type_name ~ args txt in let args = List . filter_map mk_type_expr args in Some ( Type . apply ~ args ~ name ) | Ttyp_tuple els -> let parts = List . filter_map mk_type_expr els in Some ( Type . tuple parts ) | Ttyp_variant ( rows , _closed , _labels ) -> let rec all_rows rs acc = match rs with | [ ] -> acc |> List . rev | r :: rs ' -> ( match r . rf_desc with | Ttag ( { txt ; _ } , _ , core_types ) -> let name = Const . atom ( Atom . lowercase ( Atom . mk txt ) ) in let args = core_types |> List . filter_map mk_type_expr in let variant = match args with | [ ] -> Type . const name | _ -> Type . tuple ( Type . const name :: args ) in all_rows rs ' ( variant :: acc ) | Tinherit { ctyp_desc = Ttyp_constr ( _ , { txt ; _ } , args ) ; _ } -> let name , args = Names . longident_to_type_name ~ args txt in let args = List . filter_map mk_type_expr args in let t = Type . apply ~ name ~ args in all_rows rs ' ( t :: acc ) | _ -> all_rows rs ' acc ) in let constructors = all_rows rows [ ] in Some ( Type . variant constructors ) | Ttyp_poly ( _names , follow ) -> mk_type_expr follow | Ttyp_alias ( follow , _ ) -> mk_type_expr follow | Ttyp_object _ | Ttyp_class _ | Ttyp_package _ -> Error . unsupported_feature ` Type_objects_and_packages
let mk_record labels = let mk_field Typedtree . { ld_id ; ld_type ; _ } = let rf_name = Names . atom_of_ident ld_id in let rf_type = match mk_type_expr ld_type with Some t -> t | None -> Type . any in Type . map_field ~ presence : Mandatory ( Type . const ( Const . atom rf_name ) ) rf_type in let fields = List . map mk_field labels in Type . map fields
let mk_abstract name params type_decl core_type signature = match mk_type_expr core_type with | Some expr -> let kind = is_opaque_in_signature type_decl signature in Some ( Type . mk ~ name ~ params ~ expr ~ kind ) | None -> None
let mk_type_params params = params |> List . filter_map ( fun ( core_type , _ ) -> match core_type . ctyp_desc with | Ttyp_var name -> Some ( Name . var name ) | _ -> None )
let mk_type type_decl ~ signature = let name = Names . atom_of_ident type_decl . typ_id in let params = mk_type_params type_decl . typ_params in let params = List . map Type . var params in match type_decl . typ_kind with | Ttype_abstract -> ( match type_decl . typ_manifest with | Some abs -> mk_abstract name params type_decl abs signature | None -> let expr = Type . apply ~ args [ ] : ~ name ( : Name . atom ( Atom . mk " reference " ) ) in Some ( Type . mk ~ name ~ params ~ expr ~ kind : Opaque ) ) | Ttype_record labels -> let expr = mk_record labels in Some ( Type . mk ~ name ~ params ~ expr ~ kind : Type ) | Ttype_variant constructors -> let mk_constr Typedtree . { cd_id ; cd_args ; _ } = let args = match cd_args with | Cstr_tuple core_types -> core_types |> List . filter_map mk_type_expr | Cstr_record labels -> [ mk_record labels ] in let name = Const . atom ( Names . atom_of_ident cd_id ) in match args with | [ ] -> Type . const name | _ -> Type . tuple ( Type . const name :: args ) in let constructors = List . map mk_constr constructors in Some ( Type . mk ~ name ~ params ~ expr ( : Type . variant constructors ) ~ kind : Type ) | Ttype_open -> Some ( Type . mk ~ name ~ params ~ expr : Type . any ~ kind : Type )
let mk_types : Typedtree . structure -> Types . signature option -> Erlang . Ast . type_decl list = fun typedtree signature -> typedtree . str_items |> List . concat_map ( fun item -> match item . str_desc with Tstr_type ( _ , tys ) -> tys | _ -> [ ] ) |> List . filter_map ( mk_type ~ signature )
type inner_curve_var = Tick . Field . t Snarky_backendless . Cvar . t * Tick . Field . t Snarky_backendless . Cvar . t
module Basic = struct type ( ' var , ' value , ' n1 , ' n2 ) ' n2 t = { max_proofs_verified : ( module Nat . Add . Intf with type n = ' n1 ) ' n1 ; value_to_field_elements : ' value -> Impls . Step . Field . Constant . t array ; var_to_field_elements : ' var -> Impls . Step . Field . t array ; typ : ( ' var , ' value ) ' value Impls . Step . Typ . t ; branches : ' n2 Nat . t ; wrap_domains : Domains . t ; wrap_key : Tick . Inner_curve . Affine . t Plonk_verification_key_evals . t ; wrap_vk : Impls . Wrap . Verification_key . t } end
module Side_loaded = struct module Ephemeral = struct type t = { index : [ ` In_circuit of Side_loaded_verification_key . Checked . t | ` In_prover of Side_loaded_verification_key . t ] } end module Permanent = struct type ( ' var , ' value , ' n1 , ' n2 ) ' n2 t = { max_proofs_verified : ( module Nat . Add . Intf with type n = ' n1 ) ' n1 ; value_to_field_elements : ' value -> Impls . Step . Field . Constant . t array ; var_to_field_elements : ' var -> Impls . Step . Field . t array ; typ : ( ' var , ' value ) ' value Impls . Step . Typ . t ; branches : ' n2 Nat . t } end type ( ' var , ' value , ' n1 , ' n2 ) ' n2 t = { ephemeral : Ephemeral . t option ; permanent : ( ' var , ' value , ' n1 , ' n2 ) ' n2 Permanent . t } type packed = | T : ( ' var , ' value , ' n1 , ' n2 ) ' n2 Tag . tag * ( ' var , ' value , ' n1 , ' n2 ) ' n2 t -> packed let to_basic { permanent = { max_proofs_verified ; value_to_field_elements ; var_to_field_elements ; typ ; branches } ; ephemeral } = let wrap_key , wrap_vk = match ephemeral with | Some { index = ` In_prover i } -> ( i . wrap_index , i . wrap_vk ) wrap_vk | _ -> failwithf " Side_loaded . to_basic : Expected ` In_prover ( % s ) s " __LOC__ ( ) in let proofs_verified = Nat . to_int ( Nat . Add . n max_proofs_verified ) max_proofs_verified in let wrap_vk = Option . value_exn ~ here [ :% here ] here wrap_vk in { Basic . max_proofs_verified ; wrap_vk ; value_to_field_elements ; var_to_field_elements ; typ ; branches ; wrap_domains = Common . wrap_domains ~ proofs_verified ; wrap_key } end
module Compiled = struct type f = Impls . Wrap . field type ( ' a_var , ' a_value , ' max_proofs_verified , ' branches ) ' branches basic = { typ : ( ' a_var , ' a_value ) ' a_value Impls . Step . Typ . t ; proofs_verifieds : ( int , ' branches ) ' branches Vector . t ; var_to_field_elements : ' a_var -> Impls . Step . Field . t array ; value_to_field_elements : ' a_value -> Tick . Field . t array ; wrap_domains : Domains . t ; step_domains : ( Domains . t , ' branches ) ' branches Vector . t } type ( ' a_var , ' a_value , ' max_proofs_verified , ' branches ) ' branches t = { branches : ' branches Nat . t ; max_proofs_verified : ( module Nat . Add . Intf with type n = ' max_proofs_verified ) ' max_proofs_verified ; proofs_verifieds : ( int , ' branches ) ' branches Vector . t ; typ : ( ' a_var , ' a_value ) ' a_value Impls . Step . Typ . t ; value_to_field_elements : ' a_value -> Tick . Field . t array ; var_to_field_elements : ' a_var -> Impls . Step . Field . t array ; wrap_key : Tick . Inner_curve . Affine . t Plonk_verification_key_evals . t Lazy . t ; wrap_vk : Impls . Wrap . Verification_key . t Lazy . t ; wrap_domains : Domains . t ; step_domains : ( Domains . t , ' branches ) ' branches Vector . t } type packed = | T : ( ' var , ' value , ' n1 , ' n2 ) ' n2 Tag . tag * ( ' var , ' value , ' n1 , ' n2 ) ' n2 t -> packed let to_basic { branches ; max_proofs_verified ; proofs_verifieds ; typ ; value_to_field_elements ; var_to_field_elements ; wrap_vk ; wrap_domains ; step_domains ; wrap_key } = { Basic . max_proofs_verified ; wrap_domains ; value_to_field_elements ; var_to_field_elements ; typ ; branches = Vector . length step_domains ; wrap_key = Lazy . force wrap_key ; wrap_vk = Lazy . force wrap_vk } end
module For_step = struct type ( ' a_var , ' a_value , ' max_proofs_verified , ' branches ) ' branches t = { branches : ' branches Nat . t ; max_proofs_verified : ( module Nat . Add . Intf with type n = ' max_proofs_verified ) ' max_proofs_verified ; proofs_verifieds : ( Impls . Step . Field . t , ' branches ) ' branches Vector . t ; typ : ( ' a_var , ' a_value ) ' a_value Impls . Step . Typ . t ; value_to_field_elements : ' a_value -> Tick . Field . t array ; var_to_field_elements : ' a_var -> Impls . Step . Field . t array ; wrap_key : inner_curve_var Plonk_verification_key_evals . t ; wrap_domains : Domains . t ; step_domains : [ ` Known of ( Domains . t , ' branches ) ' branches Vector . t | ` Side_loaded of ( Impls . Step . Field . t Side_loaded_verification_key . Domain . t Side_loaded_verification_key . Domains . t , ' branches ) Vector . t ] ; max_width : Side_loaded_verification_key . Width . Checked . t option } let of_side_loaded ( type a b c d ) d ( { ephemeral ; permanent = { branches ; max_proofs_verified ; typ ; value_to_field_elements ; var_to_field_elements } } : ( a , b , c , d ) d Side_loaded . t ) : ( a , b , c , d ) d t = let index = match ephemeral with | Some { index = ` In_circuit i } -> i | _ -> failwithf " For_step . side_loaded : Expected ` In_circuit ( % s ) s " __LOC__ ( ) in let T = Nat . eq_exn branches Side_loaded_verification_key . Max_branches . n in { branches ; max_proofs_verified ; proofs_verifieds = Vector . map index . step_widths ~ f : Side_loaded_verification_key . Width . Checked . to_field ; typ ; value_to_field_elements ; var_to_field_elements ; wrap_key = index . wrap_index ; wrap_domains = Common . wrap_domains ~ proofs_verified ( : Nat . to_int ( Nat . Add . n max_proofs_verified ) max_proofs_verified ) max_proofs_verified ; step_domains = ` Side_loaded index . step_domains ; max_width = Some index . max_width } let of_compiled ( { branches ; max_proofs_verified ; proofs_verifieds ; typ ; value_to_field_elements ; var_to_field_elements ; wrap_key ; wrap_domains ; step_domains } : _ Compiled . t ) = { branches ; max_width = None ; max_proofs_verified ; proofs_verifieds = Vector . map proofs_verifieds ~ f : Impls . Step . Field . of_int ; typ ; value_to_field_elements ; var_to_field_elements ; wrap_key = Plonk_verification_key_evals . map ( Lazy . force wrap_key ) wrap_key ~ f : Step_main_inputs . Inner_curve . constant ; wrap_domains ; step_domains = ` Known step_domains } end
type t = { compiled : Compiled . packed Type_equal . Id . Uid . Table . t ; side_loaded : Side_loaded . packed Type_equal . Id . Uid . Table . t }
let univ : t = { compiled = Type_equal . Id . Uid . Table . create ( ) ; side_loaded = Type_equal . Id . Uid . Table . create ( ) }
let find t k = match Hashtbl . find t k with None -> failwith " key not found " | Some x -> x
let lookup_compiled : type a b n m . ( a , b , n , m ) m Tag . tag -> ( a , b , n , m ) m Compiled . t = fun t -> let ( T ( other_id , d ) d ) d = find univ . compiled ( Type_equal . Id . uid t ) t in let T = Type_equal . Id . same_witness_exn t other_id in d
let lookup_side_loaded : type a b n m . ( a , b , n , m ) m Tag . tag -> ( a , b , n , m ) m Side_loaded . t = fun t -> let ( T ( other_id , d ) d ) d = find univ . side_loaded ( Type_equal . Id . uid t ) t in let T = Type_equal . Id . same_witness_exn t other_id in d
let lookup_basic : type a b n m . ( a , b , n , m ) m Tag . t -> ( a , b , n , m ) m Basic . t = fun t -> match t . kind with | Compiled -> Compiled . to_basic ( lookup_compiled t . id ) id | Side_loaded -> Side_loaded . to_basic ( lookup_side_loaded t . id ) id
let lookup_step_domains : type a b n m . ( a , b , n , m ) m Tag . t -> ( Domain . t , m ) m Vector . t = fun t -> let f = Vector . map ~ f : Domains . h in match t . kind with | Compiled -> f ( lookup_compiled t . id ) id . step_domains | Side_loaded -> ( let t = lookup_side_loaded t . id in match t . ephemeral with | Some { index = ` In_circuit _ } | None -> failwith __LOC__ | Some { index = ` In_prover k } -> let a = At_most . to_array ( At_most . map k . step_data ~ f ( : fun ( ds , _ ) _ -> ds . h ) h ) h in Vector . init t . permanent . branches ~ f ( : fun i -> try a ( . i ) i with _ -> Domain . Pow_2_roots_of_unity 0 ) )
let max_proofs_verified : type n1 . ( _ , _ , n1 , _ ) _ Tag . t -> ( module Nat . Add . Intf with type n = n1 ) n1 = fun tag -> match tag . kind with | Compiled -> ( lookup_compiled tag . id ) id . max_proofs_verified | Side_loaded -> ( lookup_side_loaded tag . id ) id . permanent . max_proofs_verified
let typ : type var value . ( var , value , _ , _ ) _ Tag . t -> ( var , value ) value Impls . Step . Typ . t = fun tag -> match tag . kind with | Compiled -> ( lookup_compiled tag . id ) id . typ | Side_loaded -> ( lookup_side_loaded tag . id ) id . permanent . typ
let value_to_field_elements : type a . ( _ , a , _ , _ ) _ Tag . t -> a -> Tick . Field . t array = fun t -> match t . kind with | Compiled -> ( lookup_compiled t . id ) id . value_to_field_elements | Side_loaded -> ( lookup_side_loaded t . id ) id . permanent . value_to_field_elements
let lookup_map ( type a b c d ) d ( t : ( a , b , c , d ) d Tag . t ) t ~ self ~ default ( ~ f : [ ` Compiled of ( a , b , c , d ) d Compiled . t | ` Side_loaded of ( a , b , c , d ) d Side_loaded . t ] -> _ ) = match Type_equal . Id . same_witness t . id self with | Some _ -> default | None -> ( match t . kind with | Compiled -> let ( T ( other_id , d ) d ) d = find univ . compiled ( Type_equal . Id . uid t . id ) id in let T = Type_equal . Id . same_witness_exn t . id other_id in f ( ` Compiled d ) d | Side_loaded -> let ( T ( other_id , d ) d ) d = find univ . side_loaded ( Type_equal . Id . uid t . id ) id in let T = Type_equal . Id . same_witness_exn t . id other_id in f ( ` Side_loaded d ) d )
let add_side_loaded ~ name permanent = let id = Type_equal . Id . create ~ name sexp_of_opaque in Hashtbl . add_exn univ . side_loaded ~ key ( : Type_equal . Id . uid id ) id ~ data ( : T ( id , { ephemeral = None ; permanent } ) ) ; { Tag . kind = Side_loaded ; id }
let set_ephemeral { Tag . kind ; id } eph = ( match kind with Side_loaded -> ( ) | _ -> failwith " Expected Side_loaded ) " ; Hashtbl . update univ . side_loaded ( Type_equal . Id . uid id ) id ~ f ( : function | None -> assert false | Some ( T ( id , d ) d ) d -> T ( id , { d with ephemeral = Some eph } ) )
let add_exn ( type a b c d ) d ( tag : ( a , b , c , d ) d Tag . t ) t ( data : ( a , b , c , d ) d Compiled . t ) t = Hashtbl . add_exn univ . compiled ~ key ( : Type_equal . Id . uid tag . id ) id ~ data ( : Compiled . T ( tag . id , data ) data ) data
let test ( ) = print_endline " Types tests " ; let open EH1 in let open Global in init ( ) ; let bool_t = Type . bool ( ) in let int_t = Type . int ( ) in assert ( not Type . ( equal bool_t int_t ) ) ; let real_t = Type . real ( ) in assert ( not Type . ( equal real_t bool_t ) ) ; assert ( not Type . ( equal real_t int_t ) ) ; let bv_t = Type . bv 8 in let scal_t = Type . new_scalar ~ card : 12 in let unint_t = Type . new_uninterpreted ( ) in let tup1_t = Type . tuple [ bool_t ] in let tup2_t = Type . tuple [ int_t ; real_t ] in let tup3_t = Type . tuple [ bv_t ; scal_t ; unint_t ] in let ta4 = [ bool_t ; tup1_t ; tup2_t ; tup3_t ] in let tup4_t = Type . tuple ta4 in let fun1_t = Type . func [ int_t ] bool_t in let _fun2_t = Type . func [ real_t ; bv_t ] scal_t in let fun3_t = Type . func [ tup1_t ; tup2_t ; tup3_t ] fun1_t in let fun4_t = Type . func ta4 fun3_t in assert ( Type . is_bool bool_t ) ; assert ( not ( Type . is_bool int_t ) ) ; assert ( Type . is_int int_t ) ; assert ( Type . is_real real_t ) ; assert ( Type . is_arithmetic real_t ) ; assert ( Type . is_bitvector bv_t ) ; assert ( Type . is_tuple tup1_t ) ; assert ( Type . is_function fun4_t ) ; assert ( Type . is_scalar scal_t ) ; assert ( Type . is_uninterpreted unint_t ) ; assert ( Type . test_subtype int_t real_t ) ; assert ( not ( Type . test_subtype real_t int_t ) ) ; assert ( Types . equal_ytype ( Type . reveal bv_t ) ( BV 8 ) ) ; assert ( Type . scalar_card scal_t = 12 ) ; assert ( Type . num_children ( tup3_t ) = 3 ) ; assert ( Type . child tup3_t 1 = scal_t ) ; let type_v = Type . children tup4_t in assert ( List . length type_v = 4 ) ; assert ( List . nth type_v 0 = bool_t ) ; assert ( List . nth type_v 1 = tup1_t ) ; assert ( List . nth type_v 2 = tup2_t ) ; assert ( List . nth type_v 3 = tup3_t ) ; print_endline " Done with Types tests " ; exit ( )
type error = | Unbound_type_var of string | Wrong_number_args of Path . t * int * int | Expected_type_var of type_expr | Constraints_not_satisfied of type_expr * type_decl | Opaque_type_in_prover_mode of type_expr | Convertible_arities_differ of string * int * string * int | GADT_in_nonrec_type | Repeated_row_label of Ident . t | Missing_row_label of Ident . t | Expected_row_type of type_expr
let type0 { Typedast . type_type ; _ } = type_type
let unify = ref ( fun ~ loc : _ _env _typ1 _typ2 -> failwith " Undefined " )