text
stringlengths
0
601k
let statement_desc mapper = function | Tstmt_value ( p , e ) -> Tstmt_value ( mapper . pattern mapper p , mapper . expression mapper e ) | Tstmt_instance ( name , e ) -> Tstmt_instance ( ident mapper name , mapper . expression mapper e ) | Tstmt_type decl -> Tstmt_type ( mapper . type_decl mapper decl ) | Tstmt_convtype ( decl , tconv , convname , conv ) -> Tstmt_convtype ( mapper . type_decl mapper decl , type_conv mapper tconv , ident mapper convname , mapper . convert mapper conv ) | Tstmt_rectype decls -> Tstmt_rectype ( List . map ~ f ( : mapper . type_decl mapper ) decls ) | Tstmt_module ( name , me ) -> Tstmt_module ( ident mapper name , mapper . module_expr mapper me ) | Tstmt_modtype ( name , mty ) -> Tstmt_modtype ( ident mapper name , mapper . module_sig mapper mty ) | Tstmt_open name -> Tstmt_open ( path mapper name ) | Tstmt_open_instance name -> Tstmt_open_instance ( path mapper name ) | Tstmt_typeext ( typ , ctors ) -> Tstmt_typeext ( mapper . variant mapper typ , List . map ~ f ( : mapper . ctor_decl mapper ) ctors ) | Tstmt_request ( typ , ctor , handler ) -> Tstmt_request ( mapper . type_expr mapper typ , mapper . ctor_decl mapper ctor , Option . map handler ~ f ( : fun ( p , e ) -> ( Option . map ~ f ( : mapper . pattern mapper ) p , mapper . expression mapper e ) ) ) | Tstmt_multiple stmts -> Tstmt_multiple ( mapper . statements mapper stmts ) | Tstmt_prover stmts -> Tstmt_prover ( mapper . statements mapper stmts ) | Tstmt_convert ( name , typ , conv ) -> Tstmt_convert ( ident mapper name , mapper . type_expr mapper typ , mapper . convert mapper conv )
let module_expr mapper { mod_desc ; mod_loc } = { mod_loc = mapper . location mapper mod_loc ; mod_desc = mapper . module_desc mapper mod_desc }
let module_desc mapper = function | Tmod_struct stmts -> Tmod_struct ( mapper . statements mapper stmts ) | Tmod_name name -> Tmod_name ( path mapper name ) | Tmod_functor ( name , fsig , me ) -> Tmod_functor ( str mapper name , mapper . module_sig mapper fsig , mapper . module_expr mapper me )
let location ( _mapper : mapper ) ( loc : Location . t ) = loc
let longident mapper = function | Longident . Lident str -> Longident . Lident str | Ldot ( l , str ) -> Ldot ( mapper . longident mapper l , str ) | Lapply ( l1 , l2 ) -> Lapply ( mapper . longident mapper l1 , mapper . longident mapper l2 )
let path mapper = function | Path . Pident ident -> Path . Pident ( mapper . ident mapper ident ) | Path . Pdot ( path , mode , str ) -> Path . Pdot ( mapper . path mapper path , mode , str ) | Path . Pocamldot ( path , mode , str , ocaml_name ) -> Path . Pocamldot ( mapper . path mapper path , mode , str , ocaml_name ) | Path . Papply ( path1 , path2 ) -> Path . Papply ( mapper . path mapper path1 , mapper . path mapper path2 )
let ident ( _mapper : mapper ) ( ident : Ident . t ) = ident
let default_iterator = { type_expr ; type_desc ; variant ; row_tag ; field_decl ; ctor_args ; ctor_decl ; type_decl ; type_decl_desc ; literal ; pattern ; pattern_desc ; expression ; expression_desc ; convert_body ; convert_body_desc ; convert ; convert_desc ; signature_item ; signature ; signature_desc ; module_sig ; module_sig_desc ; statement ; statements ; statement_desc ; module_expr ; module_desc ; location ; longident ; ident ; path ; type0 = Type0_map . default_mapper }
let test_check_typed_dictionaries context = let assert_test_typed_dictionary source = let mypy_extensions_stub = { handle = " mypy_extensions . pyi " ; source = { | import typing def TypedDict ( typename : str , fields : typing . Dict [ str , typing . Type [ _T ] ] , total : bool = . . . , ) -> typing . Type [ dict ] : . . . } ; | } in let typed_dictionary_for_import = { handle = " foo / bar / baz . py " ; source = { | from mypy_extensions import TypedDict class ClassBasedTypedDictGreekLetters ( TypedDict ) : alpha : int beta : str gamma : bool class ClassBasedNonTotalTypedDictGreekLetters ( TypedDict , total = False ) : alpha : int beta : str gamma : bool def decorator ( cls : C ) -> C : return cls @ decorator class DecoratedClassBasedTypedDictGreekLetters ( TypedDict ) : alpha : int beta : str gamma : bool } ; | } in assert_type_errors ~ context ~ update_environment_with [ : mypy_extensions_stub ; typed_dictionary_for_import ] source in assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( ) -> None : movie : Movie a = foo ( movie [ ' year ' ] ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Empty = mypy_extensions . TypedDict ( ' Empty ' , { } ) d : Empty reveal_type ( d ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d ` is ` Empty ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( ) -> None : movie : Movie a = foo ( movie [ ' name ' ] ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` int ` but got ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( ) -> None : movie : Movie a = foo ( movie [ ' yar ' ] ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` int ` but got ` str ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Movie ` has no key ` yar ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( ) -> None : movie : Movie key = " year " a = foo ( movie [ key ] ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( key : str ) -> None : movie : Movie a = foo ( movie [ key ] ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` int ` but got ` str ` . " ; " TypedDict accessed with a non - literal [ 26 ] : TypedDict key must be a string literal . " ^ " Expected one of ( ' name ' , ' year ' ) . " ; ] ; assert_test_typed_dictionary { | import typing_extensions Movie = typing_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( key : str ) -> None : movie : Movie a = foo ( movie [ key ] ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` int ` but got ` str ` . " ; " TypedDict accessed with a non - literal [ 26 ] : TypedDict key must be a string literal . " ^ " Expected one of ( ' name ' , ' year ' ) . " ; ] ; assert_test_typed_dictionary { | import typing Movie = typing . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : int ) -> str : return " " def f ( key : str ) -> None : movie : Movie a = foo ( movie [ key ] ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` int ` but got ` str ` . " ; " TypedDict accessed with a non - literal [ 26 ] : TypedDict key must be a string literal . " ^ " Expected one of ( ' name ' , ' year ' ) . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) Film = mypy_extensions . TypedDict ( ' Film ' , { ' name ' : str , ' year ' : ' int ' , ' director ' : str } ) def foo ( movie : Movie ) -> str : return movie [ " name " ] def f ( ) -> None : movie : Film a = foo ( movie ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) Actor = mypy_extensions . TypedDict ( ' Actor ' , { ' name ' : str , ' birthyear ' : ' int ' } ) def foo ( movie : Movie ) -> str : return movie [ " name " ] def f ( ) -> None : actor : Actor a = foo ( actor ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` Movie ` but got ` Actor ` . " ; ] ; assert_test_typed_dictionary { | from mypy_extensions import TypedDict Movie = TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) Cat = TypedDict ( ' Cat ' , { ' name ' : str , ' breed ' : str } ) Named = TypedDict ( ' Named ' , { ' name ' : str } ) def foo ( x : int , a : Movie , b : Cat ) -> Named : if x == 7 : q = a else : q = b return q } | [ ] ; assert_test_typed_dictionary { | from mypy_extensions import TypedDict Movie = TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) Cat = TypedDict ( ' Cat ' , { ' name ' : str , ' breed ' : str } ) def foo ( x : int , a : Movie , b : Cat ) -> int : if x == 7 : q = a else : q = b return q [ " year " ] } | [ " Incompatible return type [ 7 ] : Expected ` int ` but got ` str ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Cat ` has no key ` year ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions from typing import Mapping , Any Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' foo ' : int , ' bar ' : str } ) def foo ( dictionary : Mapping [ str , Any ] ) -> None : pass def f ( ) -> None : baz : Baz a = foo ( baz ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions from typing import Mapping class A : pass class B ( A ) : pass Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' foo ' : A , ' bar ' : B } ) def foo ( dictionary : Mapping [ str , A ] ) -> A : return dictionary [ " foo " ] def f ( ) -> None : baz : Baz a = foo ( baz ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` Mapping [ str , A ] ` but got ` Baz ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions from typing import Mapping class A : pass class B ( A ) : pass class C ( A ) : pass Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' foo ' : A , ' bar ' : B } ) def foo ( x : int , a : Baz , b : Mapping [ str , C ] ) -> Mapping [ str , A ] : if x == 7 : q = a else : q = b return q } | [ " Incompatible return type [ 7 ] : Expected ` Mapping [ str , A ] ` but got ` Mapping [ str , object ] ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' foo ' : int , ' bar ' : int } ) def foo ( x : int , a : Baz ) -> int : if x == 7 : q = a [ " fou " ] else : q = a [ " bar " ] return q } | [ " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Baz ` has no key ` fou ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' foo ' : int , ' bar ' : int } ) def foo ( x : int , a : Baz ) -> int : if x == 7 : k = " foo " q = a [ k ] else : q = a [ " bar " ] return q } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' first_very_long_field ' : int , ' second_very_long_field ' : int , ' third_very_long_field ' : int , ' fourth_very_long_field ' : int , ' fifth_very_long_field ' : int } ) def foo ( x : int , a : Baz ) -> int : if x == 7 : k = " foo " q = a [ k ] else : q = a [ " first_very_long_field " ] return q } | [ " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Baz ` has no key ` foo ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Baz = mypy_extensions . TypedDict ( ' Baz ' , { ' first_very_long_field ' : int , ' second_very_long_field ' : int , ' third_very_long_field ' : int , ' fourth_very_long_field ' : int , ' fifth_very_long_field ' : int } ) def foo ( a : Baz ) -> int : . . . def bar ( ** kwargs : int ) -> None : foo ( kwargs ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` Baz ` but got ` Dict [ str , int ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : reveal_type ( Movie . __init__ ) movie = Movie ( name ' = Blade Runner ' , year = 1982 ) return movie [ ' year ' ] } | [ " Revealed type [ - 1 ] : Revealed type for ` Movie . __init__ ` is ` typing . Callable ( __init__ ) [ . . . , \ unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( name , str ) , KeywordOnly ( year , int ) ] , \ Movie ] [ [ Named ( self , unknown ) , Movie ] , Movie ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( year = 1982 , name ' = Blade Runner ' ) return movie [ ' year ' ] } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( name = 1982 , year ' = Blade Runner ' ) return movie [ ' year ' ] } | [ " Incompatible parameter type [ 6 ] : In call ` __init__ ` , for 1st parameter ` name ` expected \ ` str ` but got ` int ` . " ; " Incompatible parameter type [ 6 ] : In call ` __init__ ` , for 2nd parameter ` year ` expected \ ` int ` but got ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( ' Blade Runner ' , 1982 ) return movie [ ' year ' ] } | [ " Too many arguments [ 19 ] : Call ` __init__ ` expects 0 positional arguments , 2 were provided . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( ' Blade Runner ' ) return movie [ ' year ' ] } | [ " Incompatible parameter type [ 6 ] : In call ` __init__ ` , for 1st positional only parameter \ expected ` Movie ` but got ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( { " name " : " Blade Runner " , " year " : 1982 } ) return movie [ ' year ' ] } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( { " name " : 1982 , " year " : " Blade Runner " } ) return movie [ ' year ' ] } | [ " TypedDict initialization error [ 55 ] : Expected type ` str ` for ` Movie ` field ` name ` but got \ ` int ` . " ; " TypedDict initialization error [ 55 ] : Expected type ` int ` for ` Movie ` field ` year ` but got \ ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( name ' = Blade Runner ' , year = 1982 , extra = 42 ) return movie [ ' year ' ] } | [ " Unexpected keyword [ 28 ] : Unexpected keyword argument ` extra ` to call ` __init__ ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } ) def foo ( ) -> int : movie = Movie ( year = 1982 ) return movie [ ' year ' ] } | [ " Missing argument [ 20 ] : Call ` __init__ ` expects argument ` name ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : int } , total = False ) def foo ( ) -> int : movie = Movie ( year = 1982 ) return movie [ ' year ' ] } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie [ ' name ' ] = ' new name ' } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie [ ' name ' ] = 7 } | [ " Invalid TypedDict operation [ 54 ] : Expected ` str ` to be assigned to ` Movie ` field ` name ` but \ got ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie [ ' nme ' ] = ' new name ' } | [ " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Movie ` has no key ` nme ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions class A ( ) : pass class B ( A ) : pass Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' something ' : A } ) def f ( ) -> None : movie : Movie movie [ ' something ' ] = B ( ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions class A ( ) : pass class B ( A ) : pass Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' something ' : B } ) def f ( ) -> None : movie : Movie movie [ ' something ' ] = A ( ) } | [ " Invalid TypedDict operation [ 54 ] : Expected ` B ` to be assigned to ` Movie ` field ` something ` \ but got ` A ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie [ ' year ' ] += 7 } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie reveal_type ( len ( movie ) ) } | [ " Revealed type [ - 1 ] : Revealed type for ` len ( movie ) ` is ` int ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie for k in movie : reveal_type ( k ) } | [ " Revealed type [ - 1 ] : Revealed type for ` k ` is ` str ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie b = " key " in movie reveal_type ( b ) } | [ " Revealed type [ - 1 ] : Revealed type for ` b ` is ` bool ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie v = movie [ ' name ' ] reveal_type ( v ) v = movie . get ( ' name ' ) reveal_type ( v ) v = movie . get ( ' name ' , True ) reveal_type ( v ) v = movie . get ( ' nae ' , True ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is ` str ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is ` typing . Optional [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is " ^ " ` typing . Union [ typing_extensions . Literal [ True ] , str ] ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Movie ` has no key ` nae ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie v = movie . keys ( ) reveal_type ( v ) v = movie . values ( ) reveal_type ( v ) v = movie . items ( ) reveal_type ( v ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is ` typing . AbstractSet [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is ` typing . ValuesView [ object ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is " ^ " ` typing . AbstractSet [ typing . Tuple [ str , object ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie v = movie . copy ( ) reveal_type ( v ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is " ^ " ` Movie ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie v = movie . setdefault ( ' name ' , ' newname ' ) reveal_type ( v ) v = movie . setdefault ( ' name ' , 7 ) v = movie . setdefault ( ' nme ' , ' newname ' ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is ` str ` . " ; " Incompatible parameter type [ 6 ] : In call ` TypedDictionary . setdefault ` , for 2nd positional \ only parameter expected ` str ` but got ` int ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Movie ` has no key ` nme ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie . update ( ) movie . update ( name = " newName " ) movie . update ( year = 15 ) movie . update ( name = " newName " , year = 15 ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie . update ( name = 15 , year = " backwards " ) movie . update ( yar = " missing " ) } | [ " Incompatible parameter type [ 6 ] : In call ` TypedDictionary . update ` , for 1st parameter ` name ` \ expected ` str ` but got ` int ` . " ; " Incompatible parameter type [ 6 ] : In call ` TypedDictionary . update ` , for 2nd parameter ` year ` \ expected ` int ` but got ` str ` . " ; " Unexpected keyword [ 28 ] : Unexpected keyword argument ` yar ` to call " ^ " ` TypedDictionary . update ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) movie1 : Movie movie2 : Movie movie2 . update ( movie1 ) movie2 . update ( 7 ) } | [ " Incompatible parameter type [ 6 ] : In call ` TypedDictionary . update ` , for 1st positional only \ parameter expected ` Movie ` but got ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions # MovieNonTotal = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } , total = False ) MovieNonTotal = mypy_extensions . TypedDict ( ' MovieNonTotal ' , { ' name ' : str , ' year ' : ' int ' } , total = False ) def f ( ) -> None : movieNonTotal : MovieNonTotal v = movieNonTotal . pop ( " name " ) reveal_type ( v ) v = movieNonTotal . pop ( " name " , False ) reveal_type ( v ) v = movieNonTotal . pop ( " nae " , False ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is ` str ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is " ^ " ` typing . Union [ typing_extensions . Literal [ False ] , str ] ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` MovieNonTotal ` has no key ` nae ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie . pop ( " name " ) } | [ " Undefined attribute [ 16 ] : ` Movie ` has no attribute ` pop ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions MovieNonTotal = mypy_extensions . TypedDict ( ' MovieNonTotal ' , { ' name ' : str , ' year ' : ' int ' } , total = False ) def f ( ) -> None : movieNonTotal : MovieNonTotal movieNonTotal . __delitem__ ( " name " ) movieNonTotal . __delitem__ ( " nae " ) } | [ " TypedDict accessed with a missing key [ 27 ] : TypedDict ` MovieNonTotal ` has no key ` nae ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie . __delitem__ ( " name " ) } | [ " Undefined attribute [ 16 ] : ` Movie ` has no attribute ` __delitem__ ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions MovieNonTotal = mypy_extensions . TypedDict ( ' MovieNonTotal ' , { ' name ' : str , ' year ' : ' int ' } , total = False ) MoviePlus = mypy_extensions . TypedDict ( ' MoviePlus ' , { ' name ' : str , ' year ' : ' int ' , ' director ' : str } ) def f ( ) -> None : moviePlus : MoviePlus movieNonTotal : MovieNonTotal v = movieNonTotal . get ( " name " , False ) reveal_type ( v ) v = len ( movieNonTotal ) reveal_type ( v ) v = movieNonTotal . setdefault ( ' name ' , " n " ) reveal_type ( v ) } | [ " Revealed type [ - 1 ] : Revealed type for ` v ` is " ^ " ` typing . Union [ typing_extensions . Literal [ False ] , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` v ` is ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> None : movie : Movie movie [ ' name ' ] += 7 } | [ " Unsupported operand [ 58 ] : ` ` + is not supported for operand types ` str ` and ` int ` . " ; " Invalid TypedDict operation [ 54 ] : Expected ` str ` to be assigned to ` Movie ` field ` name ` but \ got ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) ReversedMovie = mypy_extensions . TypedDict ( ' ReversedMovie ' , { ' year ' : ' int ' , ' name ' : str } ) def f ( ) -> None : movie : Movie movie [ ' name ' ] = 7 reversedMovie : ReversedMovie reversedMovie [ ' name ' ] = 7 } | [ " Invalid TypedDict operation [ 54 ] : Expected ` str ` to be assigned to ` Movie ` field ` name ` but \ got ` int ` . " ; " Invalid TypedDict operation [ 54 ] : Expected ` str ` to be assigned to ` ReversedMovie ` field \ ` name ` but got ` int ` . " ; ] ; assert_test_typed_dictionary { | from foo . bar . baz import ClassBasedTypedDictGreekLetters def f ( ) -> int : baz = ClassBasedTypedDictGreekLetters ( alpha = 7 , beta = " a " , gamma = True ) return baz [ ' alpha ' ] } | [ ] ; assert_test_typed_dictionary { | from foo . bar . baz import ClassBasedTypedDictGreekLetters def f ( ) -> int : baz = ClassBasedTypedDictGreekLetters ( alpha = 7 , gamma = True ) return baz [ ' alpha ' ] } | [ " Missing argument [ 20 ] : Call ` __init__ ` expects argument ` beta ` . " ] ; assert_test_typed_dictionary { | from foo . bar . baz import ClassBasedNonTotalTypedDictGreekLetters def f ( ) -> int : baz = ClassBasedNonTotalTypedDictGreekLetters ( alpha = 7 , gamma = True ) return baz [ ' alpha ' ] } | [ ] ; assert_test_typed_dictionary { | from foo . bar . baz import DecoratedClassBasedTypedDictGreekLetters def f ( ) -> int : baz = DecoratedClassBasedTypedDictGreekLetters ( alpha = 7 , beta = " a " , gamma = True ) return baz [ ' alpha ' ] } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions NamelessTypedDict = mypy_extensions . TypedDict ( { ' name ' : str , ' year ' : int } ) def foo ( x : int ) -> str : return " " def f ( ) -> None : movie : NamelessTypedDict a = foo ( movie [ ' year ' ] ) } | [ " Missing global annotation [ 5 ] : Globally accessible variable ` NamelessTypedDict ` " ^ " has no type specified . " ; " Missing argument [ 20 ] : Call ` mypy_extensions . TypedDict ` expects argument ` fields ` . " ; " Undefined or invalid type [ 11 ] : Annotation ` NamelessTypedDict ` is not defined as a type . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : Movie ) -> str : return x [ " name " ] def f ( x : str , y : int ) -> None : foo ( { ' name ' : x , ' year ' : y } ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : Movie ) -> str : return x [ " name " ] def f ( ) -> None : foo ( { ' name ' : " Blade Runner " , ' year ' : 1982 } ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : Movie ) -> str : return x [ " name " ] def f ( ) -> None : foo ( { ' name ' : ' Blade Runner ' , ' year ' : ' 1982 ' } ) } | [ " TypedDict initialization error [ 55 ] : Expected type ` int ` for ` Movie ` field ` year ` but got \ ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : Movie ) -> str : return x [ " name " ] def f ( x : str , y : int ) -> None : foo ( { ' name ' : ' Blade Runner ' , x : y } ) } | [ " Incompatible parameter type [ 6 ] : In call ` foo ` , for 1st positional only parameter expected \ ` Movie ` but got ` Dict [ str , Union [ int , str ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def foo ( x : Movie ) -> str : return x [ " name " ] def f ( ) -> None : foo ( { ' name ' : " Blade Runner " , ' year ' : 1982 , ' extra_key ' : 1 } ) } | [ " TypedDict initialization error [ 55 ] : TypedDict ` Movie ` has no field ` extra_key ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> str : movie : Movie = { ' name ' : " Blade Runner " , ' year ' : 1982 } return movie [ ' name ' ] } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( x : bool ) -> str : movie : Movie = { ' name ' : " Blade Runner " , ' year ' : 1982 , ' bonus ' : x } reveal_type ( movie ) return movie [ ' name ' ] } | [ " TypedDict initialization error [ 55 ] : TypedDict ` Movie ` has no field ` bonus ` . " ; " Revealed type [ - 1 ] : Revealed type for ` movie ` is ` Movie ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> str : movie : Movie = { ' name ' : " Blade Runner " , ' year ' : ' 1982 ' } return movie [ ' name ' ] } | [ " TypedDict initialization error [ 55 ] : Expected type ` int ` for ` Movie ` field ` year ` but got \ ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Movie ( mypy_extensions . TypedDict , total = False ) : name : str year : int def f ( ) -> int : movie : Movie = { ' name ' : " Blade Runner " } reveal_type ( movie ) # this will fail at runtime , but that ' s the cost of doing business with non - total # typeddicts return movie [ ' year ' ] } | [ " Revealed type [ - 1 ] : Revealed type for ` movie ` is ` Movie ` . " ] ; assert_test_typed_dictionary { | import mypy_extensions class Movie ( mypy_extensions . TypedDict , total = False ) : name : str year : int def f ( ) -> int : movie : Movie = { ' name ' : 1982 } return movie [ ' year ' ] } | [ " TypedDict initialization error [ 55 ] : Expected type ` str ` for ` Movie ` field ` name ` but got \ ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> Movie : return { ' name ' : " Blade Runner " , ' year ' : 1982 } } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' scores ' : dict } ) def f ( ) -> Movie : return Movie ( scores = { " imdb " : 8 . 1 } ) } | [ " Invalid type parameters [ 24 ] : Generic type ` dict ` expects 2 type parameters , use \ ` typing . Dict ` to avoid runtime subscripting errors . " ; ] ; assert_test_typed_dictionary { | from typing import Dict import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' scores ' : Dict } ) def f ( ) -> Movie : return Movie ( scores = { " imdb " : 8 . 1 } ) } | [ " Invalid type parameters [ 24 ] : Generic type ` dict ` expects 2 type parameters , use \ ` typing . Dict ` to avoid runtime subscripting errors . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) def f ( ) -> Movie : return { ' name ' : " Blade Runner " , ' year ' : ' 1982 ' } } | [ " TypedDict initialization error [ 55 ] : Expected type ` int ` for ` Movie ` field ` year ` but got \ ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( ) : pass class Child ( Base ) : pass Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' something ' : Base } ) def f ( ) -> Movie : return { ' name ' : " Blade Runner " , ' something ' : Child ( ) } } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions class TotalTypedDict ( mypy_extensions . TypedDict ) : required : int foo = TotalTypedDict ( required = 0 ) } | [ ] ; assert_test_typed_dictionary { | import mypy_extensions class NotTotalTypedDict ( mypy_extensions . TypedDict , total = False ) : required : int foo = NotTotalTypedDict ( ) } | [ ] ; assert_test_typed_dictionary { | import typing import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : typing . Any , ' year ' : ' int ' } ) class Bar ( mypy_extensions . TypedDict ) : x : typing . Any } | [ " Prohibited any [ 33 ] : Explicit annotation for ` name ` cannot be ` Any ` . " ; " Prohibited any [ 33 ] : Explicit annotation for ` x ` cannot be ` Any ` . " ; ] ; assert_test_typed_dictionary { | import typing import mypy_extensions class Bar ( mypy_extensions . TypedDict ) : items : typing . List [ int ] foo : int } | [ ] ; assert_test_typed_dictionary { | import typing import mypy_extensions from typing import Protocol class HasField ( Protocol ) : some_field : int class RegularClass : some_field : int = 1 class Bar ( mypy_extensions . TypedDict ) : some_field : int def expects_has_field ( x : HasField ) -> None : . . . x : RegularClass d : Bar expects_has_field ( x ) expects_has_field ( d ) } | [ " Incompatible parameter type [ 6 ] : In call ` expects_has_field ` , for 1st positional only \ parameter expected ` HasField ` but got ` Bar ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions Movie = mypy_extensions . TypedDict ( ' Movie ' , { ' name ' : str , ' year ' : ' int ' } ) Movie2 = mypy_extensions . TypedDict ( ' Movie2 ' , { ' name ' : str } ) movie : Movie movie2 : Movie2 x = movie if True else movie2 reveal_type ( x ) } | [ " Missing global annotation [ 5 ] : Globally accessible variable ` x ` has type \ ` typing . Union [ Movie , Movie2 ] ` but no type is specified . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` typing . Union [ Movie , Movie2 ] ` . " ; ] ; assert_test_typed_dictionary { | from mypy_extensions import TypedDict class HasIllegalInitializedField ( TypedDict ) : foo : int bar : str = " hello " movie : HasIllegalInitializedField movie [ " bar " ] reveal_type ( movie [ " bar " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` movie [ " \ bar " ] ` \ is ` str ` . " ] ; ( )
let test_check_typed_dictionary_inference context = let assert_test_typed_dictionary source = let mypy_extensions_stub = { handle = " mypy_extensions . pyi " ; source = { | import typing def TypedDict ( typename : str , fields : typing . Dict [ str , typing . Type [ _T ] ] , total : bool = . . . , ) -> typing . Type [ dict ] : . . . } ; | } in assert_type_errors ~ context ~ update_environment_with [ : mypy_extensions_stub ] source in assert_test_typed_dictionary { | from typing import Dict import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : foo : int bar : str def baz ( data : Dict [ str , FooTypedDict ] ) -> None : pass baz ( data { ' = hello ' : { ' foo ' : 3 , ' bar ' : ' hello ' } } ) } | [ ] ; assert_test_typed_dictionary { | from typing import Dict import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : foo : int bar : str data : Dict [ str , FooTypedDict ] = { ' hello ' : { ' foo ' : 3 , ' bar ' : ' hello ' } } } | [ ] ; assert_test_typed_dictionary { | from typing import Dict import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : foo : int bar : str data : Dict [ str , Dict [ str , FooTypedDict ] ] = { ' hello ' : { ' nested_dictionary ' : { ' foo ' : 3 , ' bar ' : ' hello ' } } } } | [ ] ; assert_test_typed_dictionary { | from typing import Dict import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : dict_within_typed_dict : Dict [ str , int ] bar : str data : Dict [ str , FooTypedDict ] = { ' hello ' : { ' dict_within_typed_dict ' : { ' x ' : 3 , ' y ' : 7 } , ' bar ' : ' hello ' } } } | [ ] ; assert_test_typed_dictionary { | from typing import Dict , Mapping , Union def baz ( data : Dict [ str , Union [ Mapping [ str , int ] , bool , int ] ] ) -> None : pass baz ( data { ' = hello ' : 3 } ) } | [ ] ; assert_test_typed_dictionary { | from typing import Dict import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : foo : int bar : str class NestedTypedDict ( mypy_extensions . TypedDict ) : foo : FooTypedDict bar : str data : Dict [ str , NestedTypedDict ] = { ' hello ' : { ' foo ' : { ' foo ' : 3 , ' bar ' : ' hello ' } , ' bar ' : ' hello ' } } } | [ ] ; assert_test_typed_dictionary { | from typing import Dict , Protocol import mypy_extensions class NonTotal ( mypy_extensions . TypedDict , total = False ) : foo : int bar : str class Total ( mypy_extensions . TypedDict ) : foo : int bar : str class Copyable ( Protocol ) : def keys ( self ) -> object : . . . class Poppable ( Protocol ) : def pop ( self ) -> object : . . . def expects_copyable ( x : Copyable ) -> None : . . . def expects_poppable ( x : Poppable ) -> None : . . . def foo ( n : NonTotal , t : Total ) -> None : expects_copyable ( n ) expects_copyable ( t ) expects_poppable ( t ) # total dicts are not poppable expects_poppable ( n ) } | [ " Incompatible parameter type [ 6 ] : In call ` expects_poppable ` , for 1st positional only \ parameter expected ` Poppable ` but got ` Total ` . " ; ] ; assert_test_typed_dictionary { | from typing import Dict , Optional import mypy_extensions class FooTypedDict ( mypy_extensions . TypedDict ) : foo : int bar : str data : Optional [ FooTypedDict ] = { ' foo ' : 3 , ' bar ' : ' hello ' } } | [ ] ; ( )
let test_check_typed_dictionary_inheritance context = let assert_test_typed_dictionary source = let mypy_extensions_stub = { handle = " mypy_extensions . pyi " ; source = { | import typing def TypedDict ( typename : str , fields : typing . Dict [ str , typing . Type [ _T ] ] , total : bool = . . . , ) -> typing . Type [ dict ] : . . . } ; | } in let typed_dictionary_helpers = { handle = " helpers . py " ; source = { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base ) : bar : str class GrandChild ( Child ) : baz : str class ExplicitChild ( mypy_extensions . TypedDict ) : foo : int bar : str class NonChild ( mypy_extensions . TypedDict ) : foo : int baz : str class Movie ( mypy_extensions . TypedDict ) : name : str year : int class MultipleInheritance ( GrandChild , Movie ) : total : int def takes_base ( d : Base ) -> None : . . . def takes_child ( d : Child ) -> None : . . . def takes_grandchild ( d : GrandChild ) -> None : . . . def takes_explicit_child ( d : ExplicitChild ) -> None : . . . def takes_nonchild ( d : NonChild ) -> None : . . . base : Base = { " foo " : 3 } child : Child = { " foo " : 3 , " bar " : " hello " } grandchild : GrandChild = { " foo " : 3 , " bar " : " hello " , " baz " : " world " } explicit_child : ExplicitChild = { " foo " : 3 , " bar " : " hello " } non_child : NonChild = { " foo " : 3 , " baz " : " hello " } } ; | } in assert_type_errors ~ context ~ update_environment_with [ : mypy_extensions_stub ; typed_dictionary_helpers ] source in assert_test_typed_dictionary { | from helpers import Base , Child , GrandChild , child , grandchild d : Base reveal_type ( d ) d : GrandChild = child child [ " bar " ] reveal_type ( child [ " bar " ] ) grandchild [ " bar " ] reveal_type ( grandchild [ " bar " ] ) grandchild [ " foo " ] reveal_type ( grandchild [ " foo " ] ) grandchild [ " non_existent " ] # An attribute from a superclass shouldn ' t be seen as a field . grandchild [ " __doc__ " ] } | [ " Revealed type [ - 1 ] : Revealed type for ` d ` is ` Base ` . " ; " Incompatible variable type [ 9 ] : d is declared to have type ` GrandChild ` but is used as type \ ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` helpers . child [ " \ bar " ] ` \ is ` str ` . " ; " Revealed type [ - 1 ] : Revealed type for ` helpers . grandchild [ " \ bar " ] ` \ is ` str ` . " ; " Revealed type [ - 1 ] : Revealed type for ` helpers . grandchild [ " \ foo " ] ` \ is ` int ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` GrandChild ` has no key \ ` non_existent ` . " ; " TypedDict accessed with a missing key [ 27 ] : TypedDict ` GrandChild ` has no key ` __doc__ ` . " ; ] ; assert_test_typed_dictionary { | from helpers import child , Child child . bar reveal_type ( child . bar ) child . non_existent reveal_type ( child . non_existent ) } | [ " Undefined attribute [ 16 ] : ` Child ` has no attribute ` bar ` . " ; " Revealed type [ - 1 ] : Revealed type for ` helpers . child . bar ` is ` unknown ` . " ; " Undefined attribute [ 16 ] : ` Child ` has no attribute ` non_existent ` . " ; " Revealed type [ - 1 ] : Revealed type for ` helpers . child . non_existent ` is ` unknown ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Base , Child , GrandChild wrong1 : Base = { } wrong2 : Child = { " foo " : 3 } wrong3 : GrandChild = { " foo " : 3 , " bar " : " hello " } correct1 : Base = { " foo " : 3 } correct2 : Child = { " foo " : 3 , " bar " : " hello " } correct3 : GrandChild = { " foo " : 3 , " bar " : " hello " , " baz " : " world " } } | [ " TypedDict initialization error [ 55 ] : Missing required field ` foo ` for TypedDict ` Base ` . " ; " TypedDict initialization error [ 55 ] : Missing required field ` bar ` for TypedDict ` Child ` . " ; " TypedDict initialization error [ 55 ] : Missing required field ` baz ` for TypedDict \ ` GrandChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Base , base , child , grandchild , explicit_child , non_child x0 : Base = base x1 : Base = child x2 : Base = grandchild x3 : Base = explicit_child x4 : Base = non_child } | [ ] ; assert_test_typed_dictionary { | from helpers import Base , Child , NonChild , child , base , grandchild , explicit_child , non_child from typing_extensions import * x0 : Child = child x1 : Child = base x2 : Child = grandchild x3 : Child = explicit_child x4 : Child = non_child } | [ " Incompatible variable type [ 9 ] : x1 is declared to have type ` Child ` but is used as type \ ` Base ` . " ; " Incompatible variable type [ 9 ] : x4 is declared to have type ` Child ` but is used as type \ ` NonChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Base , Child , ExplicitChild , NonChild , GrandChild from helpers import grandchild , base , child , explicit_child , non_child x0 : GrandChild = grandchild x1 : GrandChild = base x2 : GrandChild = child x3 : GrandChild = explicit_child x4 : GrandChild = non_child } | [ " Incompatible variable type [ 9 ] : x1 is declared to have type ` GrandChild ` but is used as \ type ` Base ` . " ; " Incompatible variable type [ 9 ] : x2 is declared to have type ` GrandChild ` but is used as \ type ` Child ` . " ; " Incompatible variable type [ 9 ] : x3 is declared to have type ` GrandChild ` but is used as \ type ` ExplicitChild ` . " ; " Incompatible variable type [ 9 ] : x4 is declared to have type ` GrandChild ` but is used as \ type ` NonChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import ExplicitChild , Base , NonChild from helpers import explicit_child , base , child , grandchild , non_child x0 : ExplicitChild = explicit_child x1 : ExplicitChild = base x2 : ExplicitChild = child x3 : ExplicitChild = grandchild x4 : ExplicitChild = non_child } | [ " Incompatible variable type [ 9 ] : x1 is declared to have type ` ExplicitChild ` but is used as \ type ` Base ` . " ; " Incompatible variable type [ 9 ] : x4 is declared to have type ` ExplicitChild ` but is used as \ type ` NonChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import NonChild , Child , Base , ExplicitChild from helpers import explicit_child , base , child , grandchild , non_child x0 : NonChild = non_child x1 : NonChild = base x2 : NonChild = child x3 : NonChild = grandchild x4 : NonChild = explicit_child } | [ " Incompatible variable type [ 9 ] : x1 is declared to have type ` NonChild ` but is used as type \ ` Base ` . " ; " Incompatible variable type [ 9 ] : x2 is declared to have type ` NonChild ` but is used as type \ ` Child ` . " ; " Incompatible variable type [ 9 ] : x4 is declared to have type ` NonChild ` but is used as type \ ` ExplicitChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import takes_base , base , child , grandchild , explicit_child , non_child takes_base ( base ) takes_base ( child ) takes_base ( grandchild ) takes_base ( explicit_child ) takes_base ( non_child ) } | [ ] ; assert_test_typed_dictionary { | from helpers import Base , Child , NonChild from helpers import takes_child , base , child , grandchild , explicit_child , non_child takes_child ( base ) takes_child ( child ) takes_child ( grandchild ) takes_child ( explicit_child ) takes_child ( non_child ) } | [ " Incompatible parameter type [ 6 ] : In call ` takes_child ` , for 1st positional only parameter \ expected ` Child ` but got ` Base ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_child ` , for 1st positional only parameter \ expected ` Child ` but got ` NonChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Base , GrandChild , Child , ExplicitChild , NonChild from helpers import takes_grandchild , base , child , grandchild , explicit_child , non_child takes_grandchild ( base ) takes_grandchild ( child ) takes_grandchild ( grandchild ) takes_grandchild ( explicit_child ) takes_grandchild ( non_child ) } | [ " Incompatible parameter type [ 6 ] : In call ` takes_grandchild ` , for 1st positional only \ parameter expected ` GrandChild ` but got ` Base ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_grandchild ` , for 1st positional only \ parameter expected ` GrandChild ` but got ` Child ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_grandchild ` , for 1st positional only \ parameter expected ` GrandChild ` but got ` ExplicitChild ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_grandchild ` , for 1st positional only \ parameter expected ` GrandChild ` but got ` NonChild ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Base , NonChild , Child , ExplicitChild from helpers import takes_nonchild , base , child , grandchild , explicit_child , non_child takes_nonchild ( base ) takes_nonchild ( child ) takes_nonchild ( grandchild ) takes_nonchild ( explicit_child ) takes_nonchild ( non_child ) } | [ " Incompatible parameter type [ 6 ] : In call ` takes_nonchild ` , for 1st positional only \ parameter expected ` NonChild ` but got ` Base ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_nonchild ` , for 1st positional only \ parameter expected ` NonChild ` but got ` Child ` . " ; " Incompatible parameter type [ 6 ] : In call ` takes_nonchild ` , for 1st positional only \ parameter expected ` NonChild ` but got ` ExplicitChild ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class TotalBase ( mypy_extensions . TypedDict ) : foo : int class NonTotalChild ( TotalBase , total = False ) : bar : str def f ( ) -> None : d : NonTotalChild = { " foo " : 1 } reveal_type ( d [ " bar " ] ) d2 : NonTotalChild = { " bar " : " hello " } } | [ " Revealed type [ - 1 ] : Revealed type for ` d [ " \ bar " ] ` \ is ` str ` . " ; " TypedDict initialization error [ 55 ] : Missing required field ` foo ` for TypedDict \ ` NonTotalChild ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class NonTotalBase ( mypy_extensions . TypedDict , total = False ) : foo : int class TotalChild ( NonTotalBase ) : bar : str def f ( ) -> None : d : TotalChild = { " bar " : " hello " } reveal_type ( d ) reveal_type ( d [ " foo " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d ` is ` TotalChild ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ " \ foo " ] ` \ is ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class NonTotalBase ( mypy_extensions . TypedDict , total = False ) : foo : int class NonTotalChild ( NonTotalBase , total = False ) : bar : str d : NonTotalChild reveal_type ( d [ " foo " ] ) reveal_type ( d [ " bar " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d [ " \ foo " ] ` \ is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ " \ bar " ] ` \ is ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class TotalBase ( mypy_extensions . TypedDict ) : foo : int class NonTotalChild ( TotalBase , total = False ) : bar : str class TotalChild ( TotalBase ) : bar : str d : NonTotalChild d2 : TotalChild d3 : TotalBase = d d4 : TotalBase = d2 } | [ ] ; assert_test_typed_dictionary { | from helpers import Child , child child : Child child [ " foo " ] child [ " bar " ] child [ " non_existent " ] reveal_type ( child [ " foo " ] ) reveal_type ( child [ " bar " ] ) } | [ " TypedDict accessed with a missing key [ 27 ] : TypedDict ` Child ` has no key ` non_existent ` . " ; " Revealed type [ - 1 ] : Revealed type for ` child [ " \ foo " ] ` \ is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` child [ " \ bar " ] ` \ is ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base , total = False ) : bar : int child : Child y : int = child . pop ( " foo " ) y : int = child . pop ( " bar " ) child . __delitem__ ( " foo " ) child . __delitem__ ( " bar " ) } | [ " Invalid TypedDict operation [ 54 ] : Cannot ` pop ` required field ` foo ` from TypedDict ` Child ` . " ; " Invalid TypedDict operation [ 54 ] : Cannot delete required field ` foo ` from TypedDict ` Child ` . " ; ] ; assert_test_typed_dictionary { | from helpers import MultipleInheritance d : MultipleInheritance reveal_type ( d ) x : int = d [ " bar " ] y : str = d [ " total " ] } | [ " Revealed type [ - 1 ] : Revealed type for ` d ` is ` MultipleInheritance ` . " ; " Incompatible variable type [ 9 ] : x is declared to have type ` int ` but is used as type ` str ` . " ; " Incompatible variable type [ 9 ] : y is declared to have type ` str ` but is used as type ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base ) : . . . d : Child x : str = d [ " foo " ] reveal_type ( d ) } | [ " Incompatible variable type [ 9 ] : x is declared to have type ` str ` but is used as type ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d ` is ` Child ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base ) : foo : int reveal_type ( Child . __init__ ) } | [ " Revealed type [ - 1 ] : Revealed type for ` test . Child . __init__ ` is \ ` typing . Callable ( __init__ ) [ . . . , unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( foo , int ) ] , \ Child ] [ [ Named ( self , unknown ) , Child ] , Child ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base1 ( mypy_extensions . TypedDict ) : foo : int class Base2 ( mypy_extensions . TypedDict ) : foo : int class Child ( Base1 , Base2 ) : foo : int reveal_type ( Child . __init__ ) } | [ " Revealed type [ - 1 ] : Revealed type for ` test . Child . __init__ ` is \ ` typing . Callable ( __init__ ) [ . . . , unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( foo , int ) ] , \ Child ] [ [ Named ( self , unknown ) , Child ] , Child ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Base2 ( mypy_extensions . TypedDict ) : bar : str class Child ( Base , Base2 ) : foo : str bar : int reveal_type ( Child . __init__ ) } | [ " Inconsistent override [ 15 ] : ` bar ` overrides attribute defined in ` Base2 ` inconsistently . \ Type ` int ` is not a subtype of the overridden attribute ` str ` . " ; " Inconsistent override [ 15 ] : ` foo ` overrides attribute defined in ` Base ` inconsistently . \ Type ` str ` is not a subtype of the overridden attribute ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` test . Child . __init__ ` is \ ` typing . Callable ( __init__ ) [ . . . , unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( bar , int ) , \ KeywordOnly ( foo , str ) ] , Child ] [ [ Named ( self , unknown ) , Child ] , Child ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base , total = False ) : foo : int } | [ " Inconsistent override [ 15 ] : ` foo ` overrides attribute defined in ` Base ` inconsistently . \ Type ` int ` is not a subtype of the overridden attribute ` int ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base1 ( mypy_extensions . TypedDict ) : foo : int bar : str class Base2 ( mypy_extensions . TypedDict ) : foo : str bar : int class Child ( Base1 , Base2 ) : baz : str d : Child x : int = d [ " bar " ] y : str = d [ " bar " ] } | [ " Invalid inheritance [ 39 ] : Field ` bar ` has type ` str ` in base class ` Base1 ` and type ` int ` \ in base class ` Base2 ` . " ; " Invalid inheritance [ 39 ] : Field ` foo ` has type ` int ` in base class ` Base1 ` and type ` str ` \ in base class ` Base2 ` . " ; " Incompatible variable type [ 9 ] : x is declared to have type ` int ` but is used as type ` str ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base1 ( mypy_extensions . TypedDict ) : foo : int class Base2 ( mypy_extensions . TypedDict , total = False ) : foo : int class Child ( Base1 , Base2 ) : baz : str } | [ " Invalid inheritance [ 39 ] : ` foo ` is a required field in base class ` Base1 ` and a \ non - required field in base class ` Base2 ` ( because of ` total = False ` ) . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base1 ( mypy_extensions . TypedDict ) : foo : int class Base2 ( mypy_extensions . TypedDict ) : foo : str class Child ( Base1 , Base2 ) : foo : str } | [ " Invalid inheritance [ 39 ] : Field ` foo ` has type ` int ` in base class ` Base1 ` and type ` str ` \ in base class ` Base2 ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class NonTypedDict : not_a_field : int class Child ( Base , NonTypedDict ) : baz : str class NonTotalChild ( Base , NonTypedDict , total = False ) : non_total_baz : str reveal_type ( Child . __init__ ) reveal_type ( NonTotalChild . __init__ ) } | [ " Uninitialized attribute [ 13 ] : Attribute ` not_a_field ` is declared in class ` NonTypedDict ` \ to have type ` int ` but is never initialized . " ; " Invalid inheritance [ 39 ] : ` NonTypedDict ` is not a valid parent class for a typed \ dictionary . Expected a typed dictionary . " ; " Invalid inheritance [ 39 ] : ` NonTypedDict ` is not a valid parent class for a typed \ dictionary . Expected a typed dictionary . " ; " Revealed type [ - 1 ] : Revealed type for ` test . Child . __init__ ` is \ ` typing . Callable ( __init__ ) [ . . . , unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( baz , str ) , \ KeywordOnly ( foo , int ) ] , Child ] [ [ Named ( self , unknown ) , Child ] , Child ] ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` test . NonTotalChild . __init__ ` is \ ` typing . Callable ( __init__ ) [ . . . , unknown ] [ [ [ Named ( self , unknown ) , KeywordOnly ( foo , int ) , \ KeywordOnly ( non_total_baz , str , default ) ] , NonTotalChild ] [ [ Named ( self , unknown ) , \ NonTotalChild ] , NonTotalChild ] ] ` . " ; ] ; ( )
let test_check_typed_dictionary_in_alias context = let assert_test_typed_dictionary source = let mypy_extensions_stub = { handle = " mypy_extensions . pyi " ; source = { | import typing def TypedDict ( typename : str , fields : typing . Dict [ str , typing . Type [ _T ] ] , total : bool = . . . , ) -> typing . Type [ dict ] : . . . } ; | } in let typed_dictionary_helpers = { handle = " helpers . py " ; source = { | import mypy_extensions class Base ( mypy_extensions . TypedDict ) : foo : int class Child ( Base ) : bar : str class GrandChild ( Child ) : baz : str class ExplicitChild ( mypy_extensions . TypedDict ) : foo : int bar : str class NonChild ( mypy_extensions . TypedDict ) : foo : int baz : str class Movie ( mypy_extensions . TypedDict ) : name : str year : int class MultipleInheritance ( GrandChild , Movie ) : total : int def takes_base ( d : Base ) -> None : . . . def takes_child ( d : Child ) -> None : . . . def takes_grandchild ( d : GrandChild ) -> None : . . . def takes_explicit_child ( d : ExplicitChild ) -> None : . . . def takes_nonchild ( d : NonChild ) -> None : . . . base : Base = { " foo " : 3 } child : Child = { " foo " : 3 , " bar " : " hello " } grandchild : GrandChild = { " foo " : 3 , " bar " : " hello " , " baz " : " world " } explicit_child : ExplicitChild = { " foo " : 3 , " bar " : " hello " } non_child : NonChild = { " foo " : 3 , " baz " : " hello " } } ; | } in assert_type_errors ~ context ~ update_environment_with [ : mypy_extensions_stub ; typed_dictionary_helpers ] source in assert_test_typed_dictionary { | from helpers import child , Child from typing import List X = Child xs : X = child ys : X reveal_type ( xs ) reveal_type ( ys ) Y = List [ Child ] y : Y reveal_type ( y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` ys ` is ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` y ` is ` List [ Child ] ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Child , child from typing import List X = List [ Child ] xs : X = [ child , child ] ys : X = 1 } | [ " Incompatible variable type [ 9 ] : ys is declared to have type ` List [ Child ] ` but is used as \ type ` int ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Child , Base , grandchild , base , child from typing import Callable , List f : Callable [ [ Child ] , None ] f ( grandchild ) f ( base ) xs : List [ Child ] = [ child , child ] } | [ " Incompatible parameter type [ 6 ] : In anonymous call , for 1st positional only parameter \ expected ` Child ` but got ` Base ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Child , Base , GrandChild , base , child from typing import Generic , TypeVar T = TypeVar ( " T " ) class G ( Generic [ T ] ) : x : T def __init__ ( self , x : T ) -> None : self . x = x def return_T ( self ) -> T : . . . class C ( G [ Child ] ) : . . . reveal_type ( C . __init__ ) reveal_type ( C . return_T ) C ( base ) d : Base = C ( child ) . x reveal_type ( d ) d2 : GrandChild = C ( child ) . x d3 : GrandChild = C ( child ) . return_T ( ) reveal_type ( C ( child ) . x ) reveal_type ( C ( child ) ) def foo ( x : G [ T ] ) -> T : return x . return_T ( ) def bar ( c : C ) -> None : x = foo ( c ) reveal_type ( x ) y = c . return_T ( ) reveal_type ( y ) } | [ " Revealed type [ - 1 ] : Revealed type for ` test . C . __init__ ` is \ ` typing . Callable ( G . __init__ ) [ [ Named ( self , G [ Child ] ) , Named ( x , Child ) ] , None ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` test . C . return_T ` is \ ` typing . Callable ( G . return_T ) [ [ Named ( self , G [ Child ] ) ] , Child ] ` . " ; " Incompatible parameter type [ 6 ] : In call ` G . __init__ ` , for 1st positional only parameter \ expected ` Child ` but got ` Base ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d ` is ` Base ` ( inferred : ` Child ` ) . " ; " Incompatible variable type [ 9 ] : d2 is declared to have type ` GrandChild ` but is used as \ type ` Child ` . " ; " Incompatible variable type [ 9 ] : d3 is declared to have type ` GrandChild ` but is used as \ type ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` test . C ( helpers . child ) . x ` is ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` test . C ( helpers . child ) ` is ` C ` . " ; " Revealed type [ - 1 ] : Revealed type for ` x ` is ` Child ` . " ; " Revealed type [ - 1 ] : Revealed type for ` y ` is ` Child ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions from typing import List X = List [ int ] class RegularTypedDict ( mypy_extensions . TypedDict ) : use_alias : X other_alias : List [ X ] d : RegularTypedDict reveal_type ( d [ " use_alias " ] ) reveal_type ( d [ " other_alias " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d [ " \ use_alias " ] ` \ is ` List [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ " \ other_alias " ] ` \ is ` List [ List [ int ] ] ` . " ; ] ; assert_test_typed_dictionary { | from helpers import * from typing import List X = List [ int ] class OtherChild ( Base ) : use_alias : X other_alias : List [ X ] d : OtherChild reveal_type ( d [ " use_alias " ] ) reveal_type ( d [ " other_alias " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d [ " \ use_alias " ] ` \ is ` List [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ " \ other_alias " ] ` \ is ` List [ List [ int ] ] ` . " ; ] ; assert_test_typed_dictionary { | import mypy_extensions from typing import List X = List [ int ] class RegularTypedDict ( mypy_extensions . TypedDict ) : use_alias : X other_alias : List [ X ] Y = List [ RegularTypedDict ] d : Y reveal_type ( d ) reveal_type ( d [ 0 ] [ " use_alias " ] ) reveal_type ( d [ 0 ] [ " other_alias " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d ` is ` List [ RegularTypedDict ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ 0 ] [ " \ use_alias " ] ` \ is ` List [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ 0 ] [ " \ other_alias " ] ` \ is ` List [ List [ int ] ] ` . " ; ] ; assert_test_typed_dictionary { | from helpers import * from typing import List X = List [ int ] class OtherChild ( Base ) : use_alias : X other_alias : List [ X ] Y = List [ OtherChild ] d : Y reveal_type ( d [ 0 ] [ " other_alias " ] ) reveal_type ( d [ 0 ] [ " foo " ] ) } | [ " Revealed type [ - 1 ] : Revealed type for ` d [ 0 ] [ " \ other_alias " ] ` \ is ` List [ List [ int ] ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` d [ 0 ] [ " \ foo " ] ` \ is ` int ` . " ; ] ; assert_test_typed_dictionary { | from helpers import Child from typing import Callable , List def decorator ( f : Callable [ [ int ] , str ] ) -> Callable [ [ Child ] , Child ] : . . . @ decorator def foo ( x : int ) -> str : . . . reveal_type ( foo ( 1 ) ) d : int = foo ( 1 ) } | [ " Revealed type [ - 1 ] : Revealed type for ` test . foo ( 1 ) ` is ` Child ` . " ; " Incompatible variable type [ 9 ] : d is declared to have type ` int ` but is used as type \ ` Child ` . " ; " Incompatible parameter type [ 6 ] : In anonymous call , for 1st positional only parameter \ expected ` Child ` but got ` int ` . " ; ] ; ( )
let test_check_optional_typed_dictionary context = assert_type_errors ~ context { | from typing import Any , TypedDict , Optional class MyDict ( TypedDict ) : a : str b : str def foo ( b : bool ) -> Optional [ MyDict ] : if b : return None return { " a " : str ( 1 ) , " b " : " hi " } def bar ( b : bool ) -> Optional [ MyDict ] : if b : return None return { " a " : str ( 1 ) , " b " : 0 } } | [ " TypedDict initialization error [ 55 ] : Expected type ` str ` for ` MyDict ` field ` b ` but got \ ` int ` . " ; ]
let ( ) = " typed_dictionary " >::: [ " check_typed_dictionaries " >:: test_check_typed_dictionaries ; " check_typed_dictionary_inference " >:: test_check_typed_dictionary_inference ; " check_typed_dictionary_inheritance " >:: test_check_typed_dictionary_inheritance ; " check_typed_dictionary_in_alias " >:: test_check_typed_dictionary_in_alias ; " check_optional_typed_dictionary " >:: test_check_optional_typed_dictionary ; ] |> Test . run
type native_repr_kind = Unboxed | Untagged
type error = Repeated_parameter | Duplicate_constructor of string | Too_many_constructors | Duplicate_label of string | Recursive_abbrev of string | Cycle_in_def of string * type_expr | Definition_mismatch of type_expr * Includecore . type_mismatch option | Constraint_failed of type_expr * type_expr | Inconsistent_constraint of Env . t * Ctype . Unification_trace . t | Type_clash of Env . t * Ctype . Unification_trace . t | Parameters_differ of Path . t * type_expr * type_expr | Null_arity_external | Missing_native_external | Unbound_type_var of type_expr * type_declaration | Cannot_extend_private_type of Path . t | Not_extensible_type of Path . t | Extension_mismatch of Path . t * Includecore . type_mismatch | Rebind_wrong_type of Longident . t * Env . t * Ctype . Unification_trace . t | Rebind_mismatch of Longident . t * Path . t * Path . t | Rebind_private of Longident . t | Variance of Typedecl_variance . error | Unavailable_type_constructor of Path . t | Bad_fixed_type of string | Unbound_type_var_ext of type_expr * extension_constructor | Val_in_structure | Multiple_native_repr_attributes | Cannot_unbox_or_untag_type of native_repr_kind | Deep_unbox_or_untag_attribute of native_repr_kind | Immediacy of Typedecl_immediacy . error | Bad_unboxed_attribute of string | Wrong_unboxed_type_float | Boxed_and_unboxed | Nonrec_gadt
let get_unboxed_from_attributes sdecl = let unboxed = Builtin_attributes . has_unboxed sdecl . ptype_attributes in let boxed = Builtin_attributes . has_boxed sdecl . ptype_attributes in match boxed , unboxed , ! Clflags . unboxed_types with | true , true , _ -> raise ( Error ( sdecl . ptype_loc , Boxed_and_unboxed ) ) | true , false , _ -> unboxed_false_default_false | false , true , _ -> unboxed_true_default_false | false , false , false -> unboxed_false_default_true | false , false , true -> unboxed_true_default_true
let add_type ~ check id decl env = Builtin_attributes . warning_scope ~ ppwarning : false decl . type_attributes ( fun ( ) -> Env . add_type ~ check id decl env )
let enter_type rec_flag env sdecl id = let needed = match rec_flag with | Asttypes . Nonrecursive -> begin match sdecl . ptype_kind with | Ptype_variant scds -> List . iter ( fun cd -> if cd . pcd_res <> None then raise ( Error ( cd . pcd_loc , Nonrec_gadt ) ) ) scds | _ -> ( ) end ; Btype . is_row_name ( Ident . name id ) | Asttypes . Recursive -> true in if not needed then env else let decl = { type_params = List . map ( fun _ -> Btype . newgenvar ( ) ) sdecl . ptype_params ; type_arity = List . length sdecl . ptype_params ; type_kind = Type_abstract ; type_private = sdecl . ptype_private ; type_manifest = begin match sdecl . ptype_manifest with None -> None | Some _ -> Some ( Ctype . newvar ( ) ) end ; type_variance = List . map ( fun _ -> Variance . full ) sdecl . ptype_params ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = sdecl . ptype_loc ; type_attributes = sdecl . ptype_attributes ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } in add_type ~ check : true id decl env
let update_type temp_env env id loc = let path = Path . Pident id in let decl = Env . find_type path temp_env in match decl . type_manifest with None -> ( ) | Some ty -> let params = List . map ( fun _ -> Ctype . newvar ( ) ) decl . type_params in try Ctype . unify env ( Ctype . newconstr path params ) ty with Ctype . Unify trace -> raise ( Error ( loc , Type_clash ( env , trace ) ) )
let get_unboxed_type_representation env ty = match Typedecl_unboxed . get_unboxed_type_representation env ty with | Typedecl_unboxed . This x -> Some x | _ -> None
let is_float env ty = match get_unboxed_type_representation env ty with Some { desc = Tconstr ( p , _ , _ ) ; _ } -> Path . same p Predef . path_float | _ -> false
let is_fixed_type sd = let rec has_row_var sty = match sty . ptyp_desc with Ptyp_alias ( sty , _ ) -> has_row_var sty | Ptyp_class _ | Ptyp_object ( _ , Open ) | Ptyp_variant ( _ , Open , _ ) | Ptyp_variant ( _ , Closed , Some _ ) -> true | _ -> false in match sd . ptype_manifest with None -> false | Some sty -> sd . ptype_kind = Ptype_abstract && sd . ptype_private = Private && has_row_var sty
let set_fixed_row env loc p decl = let tm = match decl . type_manifest with None -> assert false | Some t -> Ctype . expand_head env t in let rv = match tm . desc with Tvariant row -> let row = Btype . row_repr row in tm . desc <- Tvariant { row with row_fixed = Some Fixed_private } ; if Btype . static_row row then Btype . newgenty Tnil else row . row_more | Tobject ( ty , _ ) -> snd ( Ctype . flatten_fields ty ) | _ -> raise ( Error ( loc , Bad_fixed_type " is not an object or variant " ) ) in if not ( Btype . is_Tvar rv ) then raise ( Error ( loc , Bad_fixed_type " has no row variable " ) ) ; rv . desc <- Tconstr ( p , decl . type_params , ref Mnil )
let make_params env params = let make_param ( sty , v ) = try ( transl_type_param env sty , v ) with Already_bound -> raise ( Error ( sty . ptyp_loc , Repeated_parameter ) ) in List . map make_param params
let transl_labels env closed lbls = assert ( lbls <> [ ] ) ; let all_labels = ref String . Set . empty in List . iter ( fun { pld_name = { txt = name ; loc } } -> if String . Set . mem name ! all_labels then raise ( Error ( loc , Duplicate_label name ) ) ; all_labels := String . Set . add name ! all_labels ) lbls ; let mk { pld_name = name ; pld_mutable = mut ; pld_type = arg ; pld_loc = loc ; pld_attributes = attrs } = Builtin_attributes . warning_scope attrs ( fun ( ) -> let arg = Ast_helper . Typ . force_poly arg in let cty = transl_simple_type env closed arg in { ld_id = Ident . create_local name . txt ; ld_name = name ; ld_mutable = mut ; ld_type = cty ; ld_loc = loc ; ld_attributes = attrs } ) in let lbls = List . map mk lbls in let lbls ' = List . map ( fun ld -> let ty = ld . ld_type . ctyp_type in let ty = match ty . desc with Tpoly ( t , [ ] ) -> t | _ -> ty in { Types . ld_id = ld . ld_id ; ld_mutable = ld . ld_mutable ; ld_type = ty ; ld_loc = ld . ld_loc ; ld_attributes = ld . ld_attributes } ) lbls in lbls , lbls '
let transl_constructor_arguments env closed = function | Pcstr_tuple l -> let l = List . map ( transl_simple_type env closed ) l in Types . Cstr_tuple ( List . map ( fun t -> t . ctyp_type ) l ) , Cstr_tuple l | Pcstr_record l -> let lbls , lbls ' = transl_labels env closed l in Types . Cstr_record lbls ' , Cstr_record lbls
let make_constructor env type_path type_params sargs sret_type = match sret_type with | None -> let args , targs = transl_constructor_arguments env true sargs in targs , None , args , None , type_params | Some sret_type -> let z = narrow ( ) in reset_type_variables ( ) ; let args , targs = transl_constructor_arguments env false sargs in let tret_type = transl_simple_type env false sret_type in let ret_type = tret_type . ctyp_type in let params = match ( Ctype . repr ret_type ) . desc with | Tconstr ( p ' , params , _ ) when Path . same type_path p ' -> params | _ -> raise ( Error ( sret_type . ptyp_loc , Constraint_failed ( ret_type , Ctype . newconstr type_path type_params ) ) ) in widen z ; targs , Some tret_type , args , Some ret_type , params
let check_type_var loc univ id = let f t = ( Btype . repr t ) . id = id in if not ( List . exists f univ ) then raise ( Error ( loc , Wrong_unboxed_type_float ) )
let rec check_unboxed_abstract_arg loc univ ty = match ty . desc with | Tvar _ -> check_type_var loc univ ty . id | Tarrow ( _ , t1 , t2 , _ ) | Tfield ( _ , _ , t1 , t2 ) -> check_unboxed_abstract_arg loc univ t1 ; check_unboxed_abstract_arg loc univ t2 | Ttuple args | Tconstr ( _ , args , _ ) | Tpackage ( _ , _ , args ) -> List . iter ( check_unboxed_abstract_arg loc univ ) args | Tobject ( fields , r ) -> check_unboxed_abstract_arg loc univ fields ; begin match ! r with | None -> ( ) | Some ( _ , args ) -> List . iter ( check_unboxed_abstract_arg loc univ ) args end | Tnil | Tunivar _ -> ( ) | Tlink e -> check_unboxed_abstract_arg loc univ e | Tsubst _ -> assert false | Tvariant { row_fields ; row_more ; row_name } -> List . iter ( check_unboxed_abstract_row_field loc univ ) row_fields ; check_unboxed_abstract_arg loc univ row_more ; begin match row_name with | None -> ( ) | Some ( _ , args ) -> List . iter ( check_unboxed_abstract_arg loc univ ) args end | Tpoly ( t , _ ) -> check_unboxed_abstract_arg loc univ t match field with | Rpresent ( Some ty ) -> check_unboxed_abstract_arg loc univ ty | Reither ( _ , args , _ , r ) -> List . iter ( check_unboxed_abstract_arg loc univ ) args ; begin match ! r with | None -> ( ) | Some f -> check_unboxed_abstract_row_field loc univ ( " " , f ) end | Rabsent | Rpresent None -> ( )
let rec check_unboxed_gadt_arg loc univ env ty = match get_unboxed_type_representation env ty with | Some { desc = Tvar _ ; id } -> check_type_var loc univ id | Some { desc = Tarrow _ | Ttuple _ | Tpackage _ | Tobject _ | Tnil | Tvariant _ ; _ } -> ( ) | Some { desc = Tconstr ( p , args , _ ) ; _ } -> let tydecl = Env . find_type p env in assert ( not tydecl . type_unboxed . unboxed ) ; if tydecl . type_kind = Type_abstract then List . iter ( check_unboxed_abstract_arg loc univ ) args | Some { desc = Tfield _ | Tlink _ | Tsubst _ ; _ } -> assert false | Some { desc = Tunivar _ ; _ } -> ( ) | Some { desc = Tpoly ( t2 , _ ) ; _ } -> check_unboxed_gadt_arg loc univ env t2 | None -> ( )
let transl_declaration env sdecl id = reset_type_variables ( ) ; Ctype . begin_def ( ) ; let tparams = make_params env sdecl . ptype_params in let params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) tparams in let cstrs = List . map ( fun ( sty , sty ' , loc ) -> transl_simple_type env false sty , transl_simple_type env false sty ' , loc ) sdecl . ptype_cstrs in let raw_status = get_unboxed_from_attributes sdecl in if raw_status . unboxed && not raw_status . default then begin match sdecl . ptype_kind with | Ptype_abstract -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " it is abstract " ) ) | Ptype_variant [ { pcd_args = Pcstr_tuple [ ] ; _ } ] -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " its constructor has no argument " ) ) | Ptype_variant [ { pcd_args = Pcstr_tuple [ _ ] ; _ } ] -> ( ) | Ptype_variant [ { pcd_args = Pcstr_tuple _ ; _ } ] -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " its constructor has more than one argument " ) ) | Ptype_variant [ { pcd_args = Pcstr_record [ { pld_mutable = Immutable ; _ } ] ; _ } ] -> ( ) | Ptype_variant [ { pcd_args = Pcstr_record [ { pld_mutable = Mutable ; _ } ] ; _ } ] -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " it is mutable " ) ) | Ptype_variant [ { pcd_args = Pcstr_record _ ; _ } ] -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " its constructor has more than one argument " ) ) | Ptype_variant _ -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " it has more than one constructor " ) ) | Ptype_record [ { pld_mutable = Immutable ; _ } ] -> ( ) | Ptype_record [ { pld_mutable = Mutable ; _ } ] -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " it is mutable " ) ) | Ptype_record _ -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " it has more than one field " ) ) | Ptype_open -> raise ( Error ( sdecl . ptype_loc , Bad_unboxed_attribute " extensible variant types cannot be unboxed " ) ) end ; let unboxed_status = match sdecl . ptype_kind with | Ptype_variant [ { pcd_args = Pcstr_tuple [ _ ] ; _ } ] | Ptype_variant [ { pcd_args = Pcstr_record [ { pld_mutable = Immutable ; _ } ] ; _ } ] | Ptype_record [ { pld_mutable = Immutable ; _ } ] -> raw_status | _ -> unboxed_false_default_false in let unbox = unboxed_status . unboxed in let ( tkind , kind ) = match sdecl . ptype_kind with | Ptype_abstract -> Ttype_abstract , Type_abstract | Ptype_variant scstrs -> if List . exists ( fun cstr -> cstr . pcd_res <> None ) scstrs then begin match cstrs with [ ] -> ( ) | ( _ , _ , loc ) :: _ -> Location . prerr_warning loc Warnings . Constraint_on_gadt end ; let all_constrs = ref String . Set . empty in List . iter ( fun { pcd_name = { txt = name } } -> if String . Set . mem name ! all_constrs then raise ( Error ( sdecl . ptype_loc , Duplicate_constructor name ) ) ; all_constrs := String . Set . add name ! all_constrs ) scstrs ; if List . length ( List . filter ( fun cd -> cd . pcd_args <> Pcstr_tuple [ ] ) scstrs ) > ( Config . max_tag + 1 ) then raise ( Error ( sdecl . ptype_loc , Too_many_constructors ) ) ; let make_cstr scstr = let name = Ident . create_local scstr . pcd_name . txt in let targs , tret_type , args , ret_type , cstr_params = make_constructor env ( Path . Pident id ) params scstr . pcd_args scstr . pcd_res in if Config . flat_float_array && unbox then begin match Datarepr . constructor_existentials args ret_type with | _ , [ ] -> ( ) | [ argty ] , _ex -> check_unboxed_gadt_arg sdecl . ptype_loc cstr_params env argty | _ -> assert false end ; let tcstr = { cd_id = name ; cd_name = scstr . pcd_name ; cd_args = targs ; cd_res = tret_type ; cd_loc = scstr . pcd_loc ; cd_attributes = scstr . pcd_attributes } in let cstr = { Types . cd_id = name ; cd_args = args ; cd_res = ret_type ; cd_loc = scstr . pcd_loc ; cd_attributes = scstr . pcd_attributes } in tcstr , cstr in let make_cstr scstr = Builtin_attributes . warning_scope scstr . pcd_attributes ( fun ( ) -> make_cstr scstr ) in let tcstrs , cstrs = List . split ( List . map make_cstr scstrs ) in Ttype_variant tcstrs , Type_variant cstrs | Ptype_record lbls -> let lbls , lbls ' = transl_labels env true lbls in let rep = if unbox then Record_unboxed false else if List . for_all ( fun l -> is_float env l . Types . ld_type ) lbls ' then Record_float else Record_regular in Ttype_record lbls , Type_record ( lbls ' , rep ) | Ptype_open -> Ttype_open , Type_open in let ( tman , man ) = match sdecl . ptype_manifest with None -> None , None | Some sty -> let no_row = not ( is_fixed_type sdecl ) in let cty = transl_simple_type env no_row sty in Some cty , Some cty . ctyp_type in let decl = { type_params = params ; type_arity = List . length params ; type_kind = kind ; type_private = sdecl . ptype_private ; type_manifest = man ; type_variance = List . map ( fun _ -> Variance . full ) params ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = sdecl . ptype_loc ; type_attributes = sdecl . ptype_attributes ; type_immediate = Unknown ; type_unboxed = unboxed_status ; } in List . iter ( fun ( cty , cty ' , loc ) -> let ty = cty . ctyp_type in let ty ' = cty ' . ctyp_type in try Ctype . unify env ty ty ' with Ctype . Unify tr -> raise ( Error ( loc , Inconsistent_constraint ( env , tr ) ) ) ) cstrs ; Ctype . end_def ( ) ; if is_fixed_type sdecl then begin let p , _ = try Env . find_type_by_name ( Longident . Lident ( Ident . name id ^ " # row " ) ) env with Not_found -> assert false in set_fixed_row env sdecl . ptype_loc p decl end ; begin match decl . type_manifest with None -> ( ) | Some ty -> if Ctype . cyclic_abbrev env id ty then raise ( Error ( sdecl . ptype_loc , Recursive_abbrev sdecl . ptype_name . txt ) ) ; end ; { typ_id = id ; typ_name = sdecl . ptype_name ; typ_params = tparams ; typ_type = decl ; typ_cstrs = cstrs ; typ_loc = sdecl . ptype_loc ; typ_manifest = tman ; typ_kind = tkind ; typ_private = sdecl . ptype_private ; typ_attributes = sdecl . ptype_attributes ; }
let generalize_decl decl = List . iter Ctype . generalize decl . type_params ; Btype . iter_type_expr_kind Ctype . generalize decl . type_kind ; begin match decl . type_manifest with | None -> ( ) | Some ty -> Ctype . generalize ty end
let rec check_constraints_rec env loc visited ty = let ty = Ctype . repr ty in if TypeSet . mem ty ! visited then ( ) else begin visited := TypeSet . add ty ! visited ; match ty . desc with | Tconstr ( path , args , _ ) -> let args ' = List . map ( fun _ -> Ctype . newvar ( ) ) args in let ty ' = Ctype . newconstr path args ' in begin try Ctype . enforce_constraints env ty ' with Ctype . Unify _ -> assert false | Not_found -> raise ( Error ( loc , Unavailable_type_constructor path ) ) end ; if not ( Ctype . matches env ty ty ' ) then raise ( Error ( loc , Constraint_failed ( ty , ty ' ) ) ) ; List . iter ( check_constraints_rec env loc visited ) args | Tpoly ( ty , tl ) -> let _ , ty = Ctype . instance_poly false tl ty in check_constraints_rec env loc visited ty | _ -> Btype . iter_type_expr ( check_constraints_rec env loc visited ) ty end
let check_constraints_labels env visited l pl = let rec get_loc name = function [ ] -> assert false | pld :: tl -> if name = pld . pld_name . txt then pld . pld_type . ptyp_loc else get_loc name tl in List . iter ( fun { Types . ld_id = name ; ld_type = ty } -> check_constraints_rec env ( get_loc ( Ident . name name ) pl ) visited ty ) l
let check_constraints env sdecl ( _ , decl ) = let visited = ref TypeSet . empty in begin match decl . type_kind with | Type_abstract -> ( ) | Type_variant l -> let find_pl = function Ptype_variant pl -> pl | Ptype_record _ | Ptype_abstract | Ptype_open -> assert false in let pl = find_pl sdecl . ptype_kind in let pl_index = let foldf acc x = String . Map . add x . pcd_name . txt x acc in List . fold_left foldf String . Map . empty pl in List . iter ( fun { Types . cd_id = name ; cd_args ; cd_res } -> let { pcd_args ; pcd_res ; _ } = try String . Map . find ( Ident . name name ) pl_index with Not_found -> assert false in begin match cd_args , pcd_args with | Cstr_tuple tyl , Pcstr_tuple styl -> List . iter2 ( fun sty ty -> check_constraints_rec env sty . ptyp_loc visited ty ) styl tyl | Cstr_record tyl , Pcstr_record styl -> check_constraints_labels env visited tyl styl | _ -> assert false end ; match pcd_res , cd_res with | Some sr , Some r -> check_constraints_rec env sr . ptyp_loc visited r | _ -> ( ) ) l | Type_record ( l , _ ) -> let find_pl = function Ptype_record pl -> pl | Ptype_variant _ | Ptype_abstract | Ptype_open -> assert false in let pl = find_pl sdecl . ptype_kind in check_constraints_labels env visited l pl | Type_open -> ( ) end ; begin match decl . type_manifest with | None -> ( ) | Some ty -> let sty = match sdecl . ptype_manifest with Some sty -> sty | _ -> assert false in check_constraints_rec env sty . ptyp_loc visited ty end
let check_coherence env loc dpath decl = match decl with { type_kind = ( Type_variant _ | Type_record _ | Type_open ) ; type_manifest = Some ty } -> begin match ( Ctype . repr ty ) . desc with Tconstr ( path , args , _ ) -> begin try let decl ' = Env . find_type path env in let err = if List . length args <> List . length decl . type_params then Some Includecore . Arity else if not ( Ctype . equal env false args decl . type_params ) then Some Includecore . Constraint else Includecore . type_declarations ~ loc ~ equality : true env ~ mark : true ( Path . last path ) decl ' dpath ( Subst . type_declaration ( Subst . add_type_path dpath path Subst . identity ) decl ) in if err <> None then raise ( Error ( loc , Definition_mismatch ( ty , err ) ) ) with Not_found -> raise ( Error ( loc , Unavailable_type_constructor path ) ) end | _ -> raise ( Error ( loc , Definition_mismatch ( ty , None ) ) ) end | _ -> ( )
let check_abbrev env sdecl ( id , decl ) = check_coherence env sdecl . ptype_loc ( Path . Pident id ) decl
let check_well_founded env loc path to_check ty = let visited = ref TypeMap . empty in let rec check ty0 parents ty = let ty = Btype . repr ty in if TypeSet . mem ty parents then begin if match ty0 . desc with | Tconstr ( p , _ , _ ) -> Path . same p path | _ -> false then raise ( Error ( loc , Recursive_abbrev ( Path . name path ) ) ) else raise ( Error ( loc , Cycle_in_def ( Path . name path , ty0 ) ) ) end ; let ( fini , parents ) = try let prev = TypeMap . find ty ! visited in if TypeSet . subset parents prev then ( true , parents ) else ( false , TypeSet . union parents prev ) with Not_found -> ( false , parents ) in if fini then ( ) else let rec_ok = match ty . desc with Tconstr ( p , _ , _ ) -> ! Clflags . recursive_types && Ctype . is_contractive env p | Tobject _ | Tvariant _ -> true | _ -> ! Clflags . recursive_types in let visited ' = TypeMap . add ty parents ! visited in let arg_exn = try visited := visited ' ; let parents = if rec_ok then TypeSet . empty else TypeSet . add ty parents in Btype . iter_type_expr ( check ty0 parents ) ty ; None with e -> visited := visited ' ; Some e in match ty . desc with | Tconstr ( p , _ , _ ) when arg_exn <> None || to_check p -> if to_check p then Option . iter raise arg_exn else Btype . iter_type_expr ( check ty0 TypeSet . empty ) ty ; begin try let ty ' = Ctype . try_expand_once_opt env ty in let ty0 = if TypeSet . is_empty parents then ty else ty0 in check ty0 ( TypeSet . add ty parents ) ty ' with Ctype . Cannot_expand -> Option . iter raise arg_exn end | _ -> Option . iter raise arg_exn in let snap = Btype . snapshot ( ) in try Ctype . wrap_trace_gadt_instances env ( check ty TypeSet . empty ) ty with Ctype . Unify _ -> Btype . backtrack snap
let check_well_founded_manifest env loc path decl = if decl . type_manifest = None then ( ) else let args = List . map ( fun _ -> Ctype . newvar ( ) ) decl . type_params in check_well_founded env loc path ( Path . same path ) ( Ctype . newconstr path args )
let check_well_founded_decl env loc path decl to_check = let open Btype in let it = { type_iterators with it_type_expr = ( fun _ -> check_well_founded env loc path to_check ) } in it . it_type_declaration it ( Ctype . generic_instance_declaration decl )
let check_recursion env loc path decl to_check = if decl . type_params = [ ] then ( ) else let visited = ref [ ] in let rec check_regular cpath args prev_exp ty = let ty = Ctype . repr ty in if not ( List . memq ty ! visited ) then begin visited := ty :: ! visited ; match ty . desc with | Tconstr ( path ' , args ' , _ ) -> if Path . same path path ' then begin if not ( Ctype . equal env false args args ' ) then raise ( Error ( loc , Parameters_differ ( cpath , ty , Ctype . newconstr path args ) ) ) end else if to_check path ' && not ( List . mem path ' prev_exp ) then begin try let ( params0 , body0 , _ ) = Env . find_type_expansion path ' env in let ( params , body ) = Ctype . instance_parameterized_type params0 body0 in begin try List . iter2 ( Ctype . unify env ) params args ' with Ctype . Unify _ -> raise ( Error ( loc , Constraint_failed ( ty , Ctype . newconstr path ' params0 ) ) ) ; end ; check_regular path ' args ( path ' :: prev_exp ) body with Not_found -> ( ) end ; List . iter ( check_regular cpath args prev_exp ) args ' | Tpoly ( ty , tl ) -> let ( _ , ty ) = Ctype . instance_poly ~ keep_names : true false tl ty in check_regular cpath args prev_exp ty | _ -> Btype . iter_type_expr ( check_regular cpath args prev_exp ) ty end in Option . iter ( fun body -> let ( args , body ) = Ctype . instance_parameterized_type ~ keep_names : true decl . type_params body in check_regular path args [ ] body ) decl . type_manifest
let check_abbrev_recursion env id_loc_list to_check tdecl = let decl = tdecl . typ_type in let id = tdecl . typ_id in check_recursion env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl to_check
let check_duplicates sdecl_list = let labels = Hashtbl . create 7 and constrs = Hashtbl . create 7 in List . iter ( fun sdecl -> match sdecl . ptype_kind with Ptype_variant cl -> List . iter ( fun pcd -> try let name ' = Hashtbl . find constrs pcd . pcd_name . txt in Location . prerr_warning pcd . pcd_loc ( Warnings . Duplicate_definitions ( " constructor " , pcd . pcd_name . txt , name ' , sdecl . ptype_name . txt ) ) with Not_found -> Hashtbl . add constrs pcd . pcd_name . txt sdecl . ptype_name . txt ) cl | Ptype_record fl -> List . iter ( fun { pld_name = cname ; pld_loc = loc } -> try let name ' = Hashtbl . find labels cname . txt in Location . prerr_warning loc ( Warnings . Duplicate_definitions ( " label " , cname . txt , name ' , sdecl . ptype_name . txt ) ) with Not_found -> Hashtbl . add labels cname . txt sdecl . ptype_name . txt ) fl | Ptype_abstract -> ( ) | Ptype_open -> ( ) ) sdecl_list
let name_recursion sdecl id decl = match decl with | { type_kind = Type_abstract ; type_manifest = Some ty ; type_private = Private ; } when is_fixed_type sdecl -> let ty = Ctype . repr ty in let ty ' = Btype . newty2 ty . level ty . desc in if Ctype . deep_occur ty ty ' then let td = Tconstr ( Path . Pident id , decl . type_params , ref Mnil ) in Btype . link_type ty ( Btype . newty2 ty . level td ) ; { decl with type_manifest = Some ty ' } else decl | _ -> decl
let name_recursion_decls sdecls decls = List . map2 ( fun sdecl ( id , decl ) -> ( id , name_recursion sdecl id decl ) ) sdecls decls
let check_redefined_unit ( td : Parsetree . type_declaration ) = let open Parsetree in let is_unit_constructor cd = cd . pcd_name . txt = " ( ) " in match td with | { ptype_name = { txt = name } ; ptype_manifest = None ; ptype_kind = Ptype_variant [ cd ] } when is_unit_constructor cd -> Location . prerr_warning td . ptype_loc ( Warnings . Redefining_unit name ) | _ -> ( )
let add_types_to_env decls env = List . fold_right ( fun ( id , decl ) env -> add_type ~ check : true id decl env ) decls env
let transl_type_decl env rec_flag sdecl_list = List . iter check_redefined_unit sdecl_list ; let fixed_types = List . filter is_fixed_type sdecl_list in let sdecl_list = List . map ( fun sdecl -> let ptype_name = let loc = { sdecl . ptype_name . loc with Location . loc_ghost = true } in mkloc ( sdecl . ptype_name . txt " ^# row " ) loc in let ptype_kind = Ptype_abstract in let ptype_manifest = None in let ptype_loc = { sdecl . ptype_loc with Location . loc_ghost = true } in { sdecl with ptype_name ; ptype_kind ; ptype_manifest ; ptype_loc } ) fixed_types @ sdecl_list in let scope = Ctype . create_scope ( ) in let id_list = List . map ( fun sdecl -> Ident . create_scoped ~ scope sdecl . ptype_name . txt ) sdecl_list in Ctype . begin_def ( ) ; let temp_env = List . fold_left2 ( enter_type rec_flag ) env sdecl_list id_list in let current_slot = ref None in let warn_unused = Warnings . is_active ( Warnings . Unused_type_declaration " " ) in let id_slots id = match rec_flag with | Asttypes . Recursive when warn_unused -> let slot = ref [ ] in let td = Env . find_type ( Path . Pident id ) temp_env in let name = Ident . name id in Env . set_type_used_callback name td ( fun old_callback -> match ! current_slot with | Some slot -> slot := ( name , td ) :: ! slot | None -> List . iter ( fun ( name , d ) -> Env . mark_type_used name d ) ( get_ref slot ) ; old_callback ( ) ) ; id , Some slot | Asttypes . Recursive | Asttypes . Nonrecursive -> id , None in let transl_declaration name_sdecl ( id , slot ) = current_slot := slot ; Builtin_attributes . warning_scope name_sdecl . ptype_attributes ( fun ( ) -> transl_declaration temp_env name_sdecl id ) in let tdecls = List . map2 transl_declaration sdecl_list ( List . map id_slots id_list ) in let decls = List . map ( fun tdecl -> ( tdecl . typ_id , tdecl . typ_type ) ) tdecls in current_slot := None ; check_duplicates sdecl_list ; let new_env = add_types_to_env decls env in begin match rec_flag with | Asttypes . Nonrecursive -> ( ) | Asttypes . Recursive -> List . iter2 ( fun id sdecl -> update_type temp_env new_env id sdecl . ptype_loc ) id_list sdecl_list end ; Ctype . end_def ( ) ; List . iter ( fun ( _ , decl ) -> generalize_decl decl ) decls ; let id_loc_list = List . map2 ( fun id sdecl -> ( id , sdecl . ptype_loc ) ) id_list sdecl_list in List . iter ( fun ( id , decl ) -> check_well_founded_manifest new_env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl ) decls ; let to_check = function Path . Pident id -> List . mem_assoc id id_loc_list | _ -> false in List . iter ( fun ( id , decl ) -> check_well_founded_decl new_env ( List . assoc id id_loc_list ) ( Path . Pident id ) decl to_check ) decls ; List . iter ( check_abbrev_recursion new_env id_loc_list to_check ) tdecls ; List . iter2 ( fun sdecl tdecl -> let decl = tdecl . typ_type in match Ctype . closed_type_decl decl with Some ty -> raise ( Error ( sdecl . ptype_loc , Unbound_type_var ( ty , decl ) ) ) | None -> ( ) ) sdecl_list tdecls ; List . iter2 ( check_constraints new_env ) sdecl_list decls ; let decls = try decls |> name_recursion_decls sdecl_list |> Typedecl_variance . update_decls env sdecl_list |> Typedecl_immediacy . update_decls env with | Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) | Typedecl_immediacy . Error ( loc , err ) -> raise ( Error ( loc , Immediacy err ) ) in let final_env = add_types_to_env decls env in List . iter2 ( check_abbrev final_env ) sdecl_list decls ; let final_decls = List . map2 ( fun tdecl ( _id2 , decl ) -> { tdecl with typ_type = decl } ) tdecls decls in ( final_decls , final_env )
let transl_extension_constructor env type_path type_params typext_params priv sext = let scope = Ctype . create_scope ( ) in let id = Ident . create_scoped ~ scope sext . pext_name . txt in let args , ret_type , kind = match sext . pext_kind with Pext_decl ( sargs , sret_type ) -> let targs , tret_type , args , ret_type , _ = make_constructor env type_path typext_params sargs sret_type in args , ret_type , Text_decl ( targs , tret_type ) | Pext_rebind lid -> let usage = if priv = Public then Env . Positive else Env . Privatize in let cdescr = Env . lookup_constructor ~ loc : lid . loc usage lid . txt env in let ( args , cstr_res ) = Ctype . instance_constructor cdescr in let res , ret_type = if cdescr . cstr_generalized then let params = Ctype . instance_list type_params in let res = Ctype . newconstr type_path params in let ret_type = Some ( Ctype . newconstr type_path params ) in res , ret_type else ( Ctype . newconstr type_path typext_params ) , None in begin try Ctype . unify env cstr_res res with Ctype . Unify trace -> raise ( Error ( lid . loc , Rebind_wrong_type ( lid . txt , env , trace ) ) ) end ; if not cdescr . cstr_generalized then begin let vars = Ctype . free_variables ( Btype . newgenty ( Ttuple args ) ) in List . iter ( function { desc = Tvar ( Some " _ " ) } as ty -> if List . memq ty vars then ty . desc <- Tvar None | _ -> ( ) ) typext_params end ; let cstr_type_path , cstr_type_params = match cdescr . cstr_res . desc with Tconstr ( p , _ , _ ) -> let decl = Env . find_type p env in p , decl . type_params | _ -> assert false in let cstr_types = ( Btype . newgenty ( Tconstr ( cstr_type_path , cstr_type_params , ref Mnil ) ) ) :: cstr_type_params in let ext_types = ( Btype . newgenty ( Tconstr ( type_path , type_params , ref Mnil ) ) ) :: type_params in if not ( Ctype . equal env true cstr_types ext_types ) then raise ( Error ( lid . loc , Rebind_mismatch ( lid . txt , cstr_type_path , type_path ) ) ) ; begin match cdescr . cstr_private , priv with Private , Public -> raise ( Error ( lid . loc , Rebind_private lid . txt ) ) | _ -> ( ) end ; let path = match cdescr . cstr_tag with Cstr_extension ( path , _ ) -> path | _ -> assert false in let args = match cdescr . cstr_inlined with | None -> Types . Cstr_tuple args | Some decl -> let tl = match args with | [ { desc = Tconstr ( _ , tl , _ ) } ] -> tl | _ -> assert false in let decl = Ctype . instance_declaration decl in assert ( List . length decl . type_params = List . length tl ) ; List . iter2 ( Ctype . unify env ) decl . type_params tl ; let lbls = match decl . type_kind with | Type_record ( lbls , Record_extension _ ) -> lbls | _ -> assert false in Types . Cstr_record lbls in args , ret_type , Text_rebind ( path , lid ) in let ext = { ext_type_path = type_path ; ext_type_params = typext_params ; ext_args = args ; ext_ret_type = ret_type ; ext_private = priv ; Types . ext_loc = sext . pext_loc ; Types . ext_attributes = sext . pext_attributes ; } in { ext_id = id ; ext_name = sext . pext_name ; ext_type = ext ; ext_kind = kind ; Typedtree . ext_loc = sext . pext_loc ; Typedtree . ext_attributes = sext . pext_attributes ; }
let transl_extension_constructor env type_path type_params typext_params priv sext = Builtin_attributes . warning_scope sext . pext_attributes ( fun ( ) -> transl_extension_constructor env type_path type_params typext_params priv sext )
let transl_type_extension extend env loc styext = reset_type_variables ( ) ; Ctype . begin_def ( ) ; let type_path , type_decl = let lid = styext . ptyext_path in Env . lookup_type ~ loc : lid . loc lid . txt env in begin match type_decl . type_kind with | Type_open -> begin match type_decl . type_private with | Private when extend -> begin match List . find ( function { pext_kind = Pext_decl _ } -> true | { pext_kind = Pext_rebind _ } -> false ) styext . ptyext_constructors with | { pext_loc } -> raise ( Error ( pext_loc , Cannot_extend_private_type type_path ) ) | exception Not_found -> ( ) end | _ -> ( ) end | _ -> raise ( Error ( loc , Not_extensible_type type_path ) ) end ; let type_variance = List . map ( fun v -> let ( co , cn ) = Variance . get_upper v in ( not cn , not co , false ) ) type_decl . type_variance in let err = if type_decl . type_arity <> List . length styext . ptyext_params then Some Includecore . Arity else if List . for_all2 ( fun ( c1 , n1 , _ ) ( c2 , n2 , _ ) -> ( not c2 || c1 ) && ( not n2 || n1 ) ) type_variance ( Typedecl_variance . variance_of_params styext . ptyext_params ) then None else Some Includecore . Variance in begin match err with | None -> ( ) | Some err -> raise ( Error ( loc , Extension_mismatch ( type_path , err ) ) ) end ; let ttype_params = make_params env styext . ptyext_params in let type_params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) ttype_params in List . iter2 ( Ctype . unify_var env ) ( Ctype . instance_list type_decl . type_params ) type_params ; let constructors = List . map ( transl_extension_constructor env type_path type_decl . type_params type_params styext . ptyext_private ) styext . ptyext_constructors in Ctype . end_def ( ) ; List . iter Ctype . generalize type_params ; List . iter ( fun ext -> Btype . iter_type_expr_cstr_args Ctype . generalize ext . ext_type . ext_args ; Option . iter Ctype . generalize ext . ext_type . ext_ret_type ) constructors ; List . iter ( fun ext -> match Ctype . closed_extension_constructor ext . ext_type with Some ty -> raise ( Error ( ext . ext_loc , Unbound_type_var_ext ( ty , ext . ext_type ) ) ) | None -> ( ) ) constructors ; List . iter ( fun ext -> try Typedecl_variance . check_variance_extension env type_decl ext ( type_variance , loc ) with Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) ) constructors ; let newenv = List . fold_left ( fun env ext -> Env . add_extension ~ check : true ext . ext_id ext . ext_type env ) env constructors in let tyext = { tyext_path = type_path ; tyext_txt = styext . ptyext_path ; tyext_params = ttype_params ; tyext_constructors = constructors ; tyext_private = styext . ptyext_private ; tyext_loc = styext . ptyext_loc ; tyext_attributes = styext . ptyext_attributes ; } in ( tyext , newenv )
let transl_type_extension extend env loc styext = Builtin_attributes . warning_scope styext . ptyext_attributes ( fun ( ) -> transl_type_extension extend env loc styext )
let transl_exception env sext = reset_type_variables ( ) ; Ctype . begin_def ( ) ; let ext = transl_extension_constructor env Predef . path_exn [ ] [ ] Asttypes . Public sext in Ctype . end_def ( ) ; Btype . iter_type_expr_cstr_args Ctype . generalize ext . ext_type . ext_args ; Option . iter Ctype . generalize ext . ext_type . ext_ret_type ; begin match Ctype . closed_extension_constructor ext . ext_type with Some ty -> raise ( Error ( ext . ext_loc , Unbound_type_var_ext ( ty , ext . ext_type ) ) ) | None -> ( ) end ; let newenv = Env . add_extension ~ check : true ext . ext_id ext . ext_type env in ext , newenv
let transl_type_exception env t = Builtin_attributes . check_no_alert t . ptyexn_attributes ; let contructor , newenv = Builtin_attributes . warning_scope t . ptyexn_attributes ( fun ( ) -> transl_exception env t . ptyexn_constructor ) in { tyexn_constructor = contructor ; tyexn_loc = t . ptyexn_loc ; tyexn_attributes = t . ptyexn_attributes } , newenv
type native_repr_attribute = | Native_repr_attr_absent | Native_repr_attr_present of native_repr_kind
let get_native_repr_attribute attrs ~ global_repr = match Attr_helper . get_no_payload_attribute [ " unboxed " ; " ocaml . unboxed " ] attrs , Attr_helper . get_no_payload_attribute [ " untagged " ; " ocaml . untagged " ] attrs , global_repr with | None , None , None -> Native_repr_attr_absent | None , None , Some repr -> Native_repr_attr_present repr | Some _ , None , None -> Native_repr_attr_present Unboxed | None , Some _ , None -> Native_repr_attr_present Untagged | Some { Location . loc } , _ , _ | _ , Some { Location . loc } , _ -> raise ( Error ( loc , Multiple_native_repr_attributes ) )
let native_repr_of_type env kind ty = match kind , ( Ctype . expand_head_opt env ty ) . desc with | Untagged , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int -> Some Untagged_int | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_float -> Some Unboxed_float | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int32 -> Some ( Unboxed_integer Pint32 ) | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_int64 -> Some ( Unboxed_integer Pint64 ) | Unboxed , Tconstr ( path , _ , _ ) when Path . same path Predef . path_nativeint -> Some ( Unboxed_integer Pnativeint ) | _ -> None
let error_if_has_deep_native_repr_attributes core_type = let open Ast_iterator in let this_iterator = { default_iterator with typ = fun iterator core_type -> begin match get_native_repr_attribute core_type . ptyp_attributes ~ global_repr : None with | Native_repr_attr_present kind -> raise ( Error ( core_type . ptyp_loc , Deep_unbox_or_untag_attribute kind ) ) | Native_repr_attr_absent -> ( ) end ; default_iterator . typ iterator core_type } in default_iterator . typ this_iterator core_type
let make_native_repr env core_type ty ~ global_repr = error_if_has_deep_native_repr_attributes core_type ; match get_native_repr_attribute core_type . ptyp_attributes ~ global_repr with | Native_repr_attr_absent -> Same_as_ocaml_repr | Native_repr_attr_present kind -> begin match native_repr_of_type env kind ty with | None -> raise ( Error ( core_type . ptyp_loc , Cannot_unbox_or_untag_type kind ) ) | Some repr -> repr end
let rec parse_native_repr_attributes env core_type ty ~ global_repr = match core_type . ptyp_desc , ( Ctype . repr ty ) . desc , get_native_repr_attribute core_type . ptyp_attributes ~ global_repr : None with | Ptyp_arrow _ , Tarrow _ , Native_repr_attr_present kind -> raise ( Error ( core_type . ptyp_loc , Cannot_unbox_or_untag_type kind ) ) | Ptyp_arrow ( _ , ct1 , ct2 ) , Tarrow ( _ , t1 , t2 , _ ) , _ -> let repr_arg = make_native_repr env ct1 t1 ~ global_repr in let repr_args , repr_res = parse_native_repr_attributes env ct2 t2 ~ global_repr in ( repr_arg :: repr_args , repr_res ) | Ptyp_arrow _ , _ , _ | _ , Tarrow _ , _ -> assert false | _ -> ( [ ] , make_native_repr env core_type ty ~ global_repr )
let check_unboxable env loc ty = let check_type acc ty : Path . Set . t = let ty = Ctype . repr ( Ctype . expand_head_opt env ty ) in try match ty . desc with | Tconstr ( p , _ , _ ) -> let tydecl = Env . find_type p env in if tydecl . type_unboxed . default then Path . Set . add p acc else acc | _ -> acc with Not_found -> acc in let all_unboxable_types = Btype . fold_type_expr check_type Path . Set . empty ty in Path . Set . fold ( fun p ( ) -> Location . prerr_warning loc ( Warnings . Unboxable_type_in_prim_decl ( Path . name p ) ) ) all_unboxable_types ( )
let transl_value_decl env loc valdecl = let cty = Typetexp . transl_type_scheme env valdecl . pval_type in let ty = cty . ctyp_type in let v = match valdecl . pval_prim with [ ] when Env . is_in_signature env -> { val_type = ty ; val_kind = Val_reg ; Types . val_loc = loc ; val_attributes = valdecl . pval_attributes } | [ ] -> raise ( Error ( valdecl . pval_loc , Val_in_structure ) ) | _ -> let global_repr = match get_native_repr_attribute valdecl . pval_attributes ~ global_repr : None with | Native_repr_attr_present repr -> Some repr | Native_repr_attr_absent -> None in let native_repr_args , native_repr_res = parse_native_repr_attributes env valdecl . pval_type ty ~ global_repr in let prim = Primitive . parse_declaration valdecl ~ native_repr_args ~ native_repr_res in if prim . prim_arity = 0 && ( prim . prim_name = " " || prim . prim_name . [ 0 ] <> ' ' ) % then raise ( Error ( valdecl . pval_type . ptyp_loc , Null_arity_external ) ) ; if ! Clflags . native_code && prim . prim_arity > 5 && prim . prim_native_name = " " then raise ( Error ( valdecl . pval_type . ptyp_loc , Missing_native_external ) ) ; check_unboxable env loc ty ; { val_type = ty ; val_kind = Val_prim prim ; Types . val_loc = loc ; val_attributes = valdecl . pval_attributes } in let ( id , newenv ) = Env . enter_value valdecl . pval_name . txt v env ~ check ( : fun s -> Warnings . Unused_value_declaration s ) in let desc = { val_id = id ; val_name = valdecl . pval_name ; val_desc = cty ; val_val = v ; val_prim = valdecl . pval_prim ; val_loc = valdecl . pval_loc ; val_attributes = valdecl . pval_attributes ; } in desc , newenv
let transl_value_decl env loc valdecl = Builtin_attributes . warning_scope valdecl . pval_attributes ( fun ( ) -> transl_value_decl env loc valdecl )
let transl_with_constraint env id row_path orig_decl sdecl = Env . mark_type_used ( Ident . name id ) orig_decl ; reset_type_variables ( ) ; Ctype . begin_def ( ) ; let tparams = make_params env sdecl . ptype_params in let params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) tparams in let orig_decl = Ctype . instance_declaration orig_decl in let arity_ok = List . length params = orig_decl . type_arity in if arity_ok then List . iter2 ( Ctype . unify_var env ) params orig_decl . type_params ; let constraints = List . map ( function ( ty , ty ' , loc ) -> try let cty = transl_simple_type env false ty in let cty ' = transl_simple_type env false ty ' in let ty = cty . ctyp_type in let ty ' = cty ' . ctyp_type in Ctype . unify env ty ty ' ; ( cty , cty ' , loc ) with Ctype . Unify tr -> raise ( Error ( loc , Inconsistent_constraint ( env , tr ) ) ) ) sdecl . ptype_cstrs in let no_row = not ( is_fixed_type sdecl ) in let ( tman , man ) = match sdecl . ptype_manifest with None -> None , None | Some sty -> let cty = transl_simple_type env no_row sty in Some cty , Some cty . ctyp_type in let priv = if sdecl . ptype_private = Private then Private else if arity_ok && orig_decl . type_kind <> Type_abstract then orig_decl . type_private else sdecl . ptype_private in if arity_ok && orig_decl . type_kind <> Type_abstract && sdecl . ptype_private = Private then Location . deprecated sdecl . ptype_loc " spurious use of private " ; let type_kind , type_unboxed = if arity_ok && man <> None then orig_decl . type_kind , orig_decl . type_unboxed else Type_abstract , unboxed_false_default_false in let decl = { type_params = params ; type_arity = List . length params ; type_kind ; type_private = priv ; type_manifest = man ; type_variance = [ ] ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = sdecl . ptype_loc ; type_attributes = sdecl . ptype_attributes ; type_immediate = Unknown ; type_unboxed ; } in begin match row_path with None -> ( ) | Some p -> set_fixed_row env sdecl . ptype_loc p decl end ; begin match Ctype . closed_type_decl decl with None -> ( ) | Some ty -> raise ( Error ( sdecl . ptype_loc , Unbound_type_var ( ty , decl ) ) ) end ; let decl = name_recursion sdecl id decl in let type_variance = try Typedecl_variance . compute_decl env ~ check : true decl ( Typedecl_variance . variance_of_sdecl sdecl ) with Typedecl_variance . Error ( loc , err ) -> raise ( Error ( loc , Variance err ) ) in let type_immediate = Typedecl_immediacy . compute_decl env decl in let decl = { decl with type_variance ; type_immediate } in Ctype . end_def ( ) ; generalize_decl decl ; { typ_id = id ; typ_name = sdecl . ptype_name ; typ_params = tparams ; typ_type = decl ; typ_cstrs = constraints ; typ_loc = sdecl . ptype_loc ; typ_manifest = tman ; typ_kind = Ttype_abstract ; typ_private = sdecl . ptype_private ; typ_attributes = sdecl . ptype_attributes ; }
let abstract_type_decl arity = let rec make_params n = if n <= 0 then [ ] else Ctype . newvar ( ) :: make_params ( n - 1 ) in Ctype . begin_def ( ) ; let decl = { type_params = make_params arity ; type_arity = arity ; type_kind = Type_abstract ; type_private = Public ; type_manifest = None ; type_variance = replicate_list Variance . full arity ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = Location . none ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } in Ctype . end_def ( ) ; generalize_decl decl ; decl
let approx_type_decl sdecl_list = let scope = Ctype . create_scope ( ) in List . map ( fun sdecl -> ( Ident . create_scoped ~ scope sdecl . ptype_name . txt , abstract_type_decl ( List . length sdecl . ptype_params ) ) ) sdecl_list
let check_recmod_typedecl env loc recmod_ids path decl = let to_check path = Path . exists_free recmod_ids path in check_well_founded_decl env loc path decl to_check ; check_recursion env loc path decl to_check ; check_coherence env loc path decl
let explain_unbound_gen ppf tv tl typ kwd pr = try let ti = List . find ( fun ti -> Ctype . deep_occur tv ( typ ti ) ) tl in let ty0 = Btype . newgenty ( Tobject ( tv , ref None ) ) in Printtyp . reset_and_mark_loops_list [ typ ti ; ty0 ] ; fprintf ppf " . . [ @@< hov2 > In % s @ % a ; @< 1 - 2 > the variable % a is unbound ] " @ kwd pr ti Printtyp . marked_type_expr tv with Not_found -> ( )
let explain_unbound ppf tv tl typ kwd lab = explain_unbound_gen ppf tv tl typ kwd ( fun ppf ti -> fprintf ppf " % s % a " ( lab ti ) Printtyp . marked_type_expr ( typ ti ) )
let explain_unbound_single ppf tv ty = let trivial ty = explain_unbound ppf tv [ ty ] ( fun t -> t ) " type " ( fun _ -> " " ) in match ( Ctype . repr ty ) . desc with Tobject ( fi , _ ) -> let ( tl , rv ) = Ctype . flatten_fields fi in if rv == tv then trivial ty else explain_unbound ppf tv tl ( fun ( _ , _ , t ) -> t ) " method " ( fun ( lab , _ , _ ) -> lab ^ " : " ) | Tvariant row -> let row = Btype . row_repr row in if row . row_more == tv then trivial ty else explain_unbound ppf tv row . row_fields ( fun ( _l , f ) -> match Btype . row_field_repr f with Rpresent ( Some t ) -> t | Reither ( _ , [ t ] , _ , _ ) -> t | Reither ( _ , tl , _ , _ ) -> Btype . newgenty ( Ttuple tl ) | _ -> Btype . newgenty ( Ttuple [ ] ) ) " case " ( fun ( lab , _ ) -> " ` " ^ lab ^ " of " ) | _ -> trivial ty
let tys_of_constr_args = function | Types . Cstr_tuple tl -> tl | Types . Cstr_record lbls -> List . map ( fun l -> l . Types . ld_type ) lbls
let report_error ppf = function | Repeated_parameter -> fprintf ppf " A type parameter occurs several times " | Duplicate_constructor s -> fprintf ppf " Two constructors are named % s " s | Too_many_constructors -> fprintf ppf " [ @ Too many non - constant constructors @ -- maximum is % i % s ] " @ ( Config . max_tag + 1 ) " non - constant constructors " | Duplicate_label s -> fprintf ppf " Two labels are named % s " s | Recursive_abbrev s -> fprintf ppf " The type abbreviation % s is cyclic " s | Cycle_in_def ( s , ty ) -> fprintf ppf " [ @< v > The definition of % s contains a cycle :@ % a ] " @ s Printtyp . type_expr ty | Definition_mismatch ( ty , None ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% a ] ] " @@ " This variant or record definition " " does not match that of type " Printtyp . type_expr ty | Definition_mismatch ( ty , Some err ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% a ] @% a ] " @ " This variant or record definition " " does not match that of type " Printtyp . type_expr ty ( Includecore . report_type_mismatch " the original " " this " " definition " ) err | Constraint_failed ( ty , ty ' ) -> Printtyp . reset_and_mark_loops ty ; Printtyp . mark_loops ty ' ; Printtyp . Naming_context . reset ( ) ; fprintf ppf " [ @% s @ [ @< hv > Type @ % a @ should be an instance of @ % a ] ] " @@ " Constraints are not satisfied in this type . " ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ' ) | Parameters_differ ( path , ty , ty ' ) -> Printtyp . reset_and_mark_loops ty ; Printtyp . mark_loops ty ' ; Printtyp . Naming_context . reset ( ) ; fprintf ppf " [ @< hv > In the definition of % s , type @ % a @ should be @ % a ] " @ ( Path . name path ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ' ) | Inconsistent_constraint ( env , trace ) -> fprintf ppf " The type constraints are not consistent . . " ; @ Printtyp . report_unification_error ppf env trace ( fun ppf -> fprintf ppf " Type " ) ( fun ppf -> fprintf ppf " is not compatible with type " ) | Type_clash ( env , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " This type constructor expands to type " ) ( function ppf -> fprintf ppf " but is used here with type " ) | Null_arity_external -> fprintf ppf " External identifiers must be functions " | Missing_native_external -> fprintf ppf " [ @< hv > An external function with more than 5 arguments \ requires a second stub function @ \ for native - code compilation ] " @ | Unbound_type_var ( ty , decl ) -> fprintf ppf " A type variable is unbound in this type declaration " ; let ty = Ctype . repr ty in begin match decl . type_kind , decl . type_manifest with | Type_variant tl , _ -> explain_unbound_gen ppf ty tl ( fun c -> let tl = tys_of_constr_args c . Types . cd_args in Btype . newgenty ( Ttuple tl ) ) " case " ( fun ppf c -> fprintf ppf " % a of % a " Printtyp . ident c . Types . cd_id Printtyp . constructor_arguments c . Types . cd_args ) | Type_record ( tl , _ ) , _ -> explain_unbound ppf ty tl ( fun l -> l . Types . ld_type ) " field " ( fun l -> Ident . name l . Types . ld_id ^ " : " ) | Type_abstract , Some ty ' -> explain_unbound_single ppf ty ty ' | _ -> ( ) end | Unbound_type_var_ext ( ty , ext ) -> fprintf ppf " A type variable is unbound in this extension constructor " ; let args = tys_of_constr_args ext . ext_args in explain_unbound ppf ty args ( fun c -> c ) " type " ( fun _ -> " " ) | Cannot_extend_private_type path -> fprintf ppf " [ @% s @ % a ] " @ " Cannot extend private type definition " Printtyp . path path | Not_extensible_type path -> fprintf ppf " [ @% s @ % a @ % s ] " @ " Type definition " Printtyp . path path " is not extensible " | Extension_mismatch ( path , err ) -> fprintf ppf " [ @< v [ >@< hov >% s @ % s ; @< 1 2 >% s ] @% a ] " @ " This extension " " does not match the definition of type " ( Path . name path ) ( Includecore . report_type_mismatch " the type " " this extension " " definition " ) err | Rebind_wrong_type ( lid , env , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " The constructor % a @ has type " Printtyp . longident lid ) ( function ppf -> fprintf ppf " but was expected to be of type " ) | Rebind_mismatch ( lid , p , p ' ) -> fprintf ppf " [ @% s @ % a @ % s @ % s @ % s @ % s @ % s ] " @ " The constructor " Printtyp . longident lid " extends type " ( Path . name p ) " whose declaration does not match " " the declaration of type " ( Path . name p ' ) | Rebind_private lid -> fprintf ppf " [ @% s @ % a @ % s ] " @ " The constructor " Printtyp . longident lid " is private " | Variance ( Typedecl_variance . Bad_variance ( n , v1 , v2 ) ) -> let variance ( p , n , i ) = let inj = if i then " injective " else " " in match p , n with true , true -> inj ^ " invariant " | true , false -> inj ^ " covariant " | false , true -> inj ^ " contravariant " | false , false -> if inj = " " then " unrestricted " else inj in let suffix n = let teen = ( n mod 100 ) / 10 = 1 in match n mod 10 with | 1 when not teen -> " st " | 2 when not teen -> " nd " | 3 when not teen -> " rd " | _ -> " th " in ( match n with | Variance_not_reflected -> fprintf ppf " [ @% s @ % s @ It " " In this definition , a type variable has a variance that " " is not reflected by its occurrence in type parameters . " | No_variable -> fprintf ppf " [ @% s @ % s ] " @ " In this definition , a type variable cannot be deduced " " from the type parameters . " | Variance_not_deducible -> fprintf ppf " [ @% s @ % s @ It " " In this definition , a type variable has a variance that " " cannot be deduced from the type parameters . " | Variance_not_satisfied n -> fprintf ppf " [ @% s @ % s @ The % d % s type parameter " " In this definition , expected parameter " " variances are not satisfied . " n ( suffix n ) ) ; ( match n with | No_variable -> ( ) | _ -> fprintf ppf " was expected to be % s , @ but it is % s . ] " @ ( variance v2 ) ( variance v1 ) ) | Unavailable_type_constructor p -> fprintf ppf " The definition of type % a @ is unavailable " Printtyp . path p | Bad_fixed_type r -> fprintf ppf " This fixed type % s " r | Variance Typedecl_variance . Varying_anonymous -> fprintf ppf " [ @% s @ % s @ % s ] " @ " In this GADT definition , " " the variance of some parameter " " cannot be checked " | Val_in_structure -> fprintf ppf " Value declarations are only allowed in signatures " | Multiple_native_repr_attributes -> fprintf ppf " Too many [ @@ unboxed ] [ /@@ untagged ] attributes " | Cannot_unbox_or_untag_type Unboxed -> fprintf ppf " [ @ Don ' t know how to unbox this type . @ \ Only float , int32 , int64 and nativeint can be unboxed . ] " @ | Cannot_unbox_or_untag_type Untagged -> fprintf ppf " [ @ Don ' t know how to untag this type . @ \ Only int can be untagged . ] " @ | Deep_unbox_or_untag_attribute kind -> fprintf ppf " [ @ The attribute ' % s ' should be attached to @ \ a direct argument or result of the primitive , @ \ it should not occur deeply into its type . ] " @ ( match kind with Unboxed -> " @ unboxed " | Untagged -> " @ untagged " ) | Immediacy ( Typedecl_immediacy . Bad_immediacy_attribute violation ) -> fprintf ppf " [ @% a ] " @ Format . pp_print_text ( match violation with | Type_immediacy . Violation . Not_always_immediate -> " Types marked with the immediate attribute must be \ non - pointer types like int or bool . " | Type_immediacy . Violation . Not_always_immediate_on_64bits -> " Types marked with the immediate64 attribute must be \ produced using the Stdlib . Sys . Immediate64 . Make functor . " ) | Bad_unboxed_attribute msg -> fprintf ppf " [ @ This type cannot be unboxed because @ % s . ] " @ msg | Wrong_unboxed_type_float -> fprintf ppf " [ @ This type cannot be unboxed because @ \ it might contain both float and non - float values . @ \ You should annotate it with [ %@%@ ocaml . boxed ] . ] " @ | Boxed_and_unboxed -> fprintf ppf " [ @ A type cannot be boxed and unboxed at the same time . ] " @ | Nonrec_gadt -> fprintf ppf " [ @ GADT case syntax cannot be used in a ' nonrec ' block . ] " @
let ( ) = Location . register_error_of_exn ( function | Error ( loc , err ) -> Some ( Location . error_of_printer ~ loc report_error err ) | _ -> None )
type error = Bad_immediacy_attribute of Type_immediacy . Violation . t
let compute_decl env tdecl = match ( tdecl . type_kind , tdecl . type_manifest ) with | ( Type_variant [ { cd_args = Cstr_tuple [ arg ] ; _ } ] , _ ) | ( Type_variant [ { cd_args = Cstr_record [ { ld_type = arg ; _ } ] ; _ } ] , _ ) | ( Type_record ( [ { ld_type = arg ; _ } ] , _ ) , _ ) when tdecl . type_unboxed . unboxed -> begin match Typedecl_unboxed . get_unboxed_type_representation env arg with | Typedecl_unboxed . Unavailable -> Type_immediacy . Unknown | Typedecl_unboxed . This argrepr -> Ctype . immediacy env argrepr | Typedecl_unboxed . Only_on_64_bits argrepr -> match Ctype . immediacy env argrepr with | Type_immediacy . Always -> Type_immediacy . Always_on_64bits | Type_immediacy . Always_on_64bits | Type_immediacy . Unknown as x -> x end | ( Type_variant ( _ :: _ as cstrs ) , _ ) -> if not ( List . exists ( fun c -> c . Types . cd_args <> Types . Cstr_tuple [ ] ) cstrs ) then Type_immediacy . Always else Type_immediacy . Unknown | ( Type_abstract , Some ( typ ) ) -> Ctype . immediacy env typ | ( Type_abstract , None ) -> Type_immediacy . of_attributes tdecl . type_attributes | _ -> Type_immediacy . Unknown
let property : ( Type_immediacy . t , unit ) Typedecl_properties . property = let open Typedecl_properties in let eq = ( ) = in let merge ~ prop : _ ~ new_prop = new_prop in let default _decl = Type_immediacy . Unknown in let compute env decl ( ) = compute_decl env decl in let update_decl decl immediacy = { decl with type_immediate = immediacy } in let check _env _id decl ( ) = let written_by_user = Type_immediacy . of_attributes decl . type_attributes in match Type_immediacy . coerce decl . type_immediate ~ as_ : written_by_user with | Ok ( ) -> ( ) | Error violation -> raise ( Error ( decl . type_loc , Bad_immediacy_attribute violation ) ) in { eq ; merge ; default ; compute ; update_decl ; check ; }
let update_decls env decls = Typedecl_properties . compute_property_noreq property env decls
type ( ' prop , ' req ) property = { eq : ' prop -> ' prop -> bool ; merge : prop ' : prop -> new_prop ' : prop -> ' prop ; default : decl -> ' prop ; compute : Env . t -> decl -> ' req -> ' prop ; update_decl : decl -> ' prop -> decl ; check : Env . t -> Ident . t -> decl -> ' req -> unit ; }
let add_type ~ check id decl env = let open Types in Builtin_attributes . warning_scope ~ ppwarning : false decl . type_attributes ( fun ( ) -> Env . add_type ~ check id decl env )
let add_types_to_env decls env = List . fold_right ( fun ( id , decl ) env -> add_type ~ check : true id decl env ) decls env
let compute_property ( Ident . t * decl ) list -> ' req list -> ( Ident . t * decl ) list let props = List . map ( fun ( _id , decl ) -> property . default decl ) decls in let rec compute_fixpoint props = let new_decls = List . map2 ( fun ( id , decl ) prop -> ( id , property . update_decl decl prop ) ) decls props in let new_env = add_types_to_env new_decls env in let new_props = List . map2 ( fun ( _id , decl ) ( prop , req ) -> let new_prop = property . compute new_env decl req in property . merge ~ prop ~ new_prop ) new_decls ( List . combine props required ) in if not ( List . for_all2 property . eq props new_props ) then compute_fixpoint new_props else begin List . iter2 ( fun ( id , decl ) req -> property . check new_env id decl req ) new_decls required ; new_decls end in compute_fixpoint props
let compute_property_noreq property env decls = let req = List . map ( fun _ -> ( ) ) decls in compute_property property env decls req
type argument_to_unbox = { kind : parameter_kind ; mutability : Asttypes . mutable_flag ; argument_type : type_expr ; result_type_parameter_instances : type_expr list ; location : Location . t ; } | Record_field | Constructor_parameter | Constructor_field
type ' a multiplicity = | Zero | One of ' a | Several
type arity = argument_to_unbox multiplicity
type branching = arity multiplicity
type type_structure = | Synonym of type_expr | Abstract | Open | Algebraic of branching
let demultiply_list : type a b . a list -> ( a -> b ) -> b multiplicity = fun li f -> match li with | [ ] -> Zero | [ v ] -> One ( f v ) | _ :: _ :: _ -> Several
let structure : type_definition -> type_structure = fun def -> match def . type_kind with | Type_open -> Open | Type_abstract -> begin match def . type_manifest with | None -> Abstract | Some type_expr -> Synonym type_expr end | Type_record ( labels , _ ) -> Algebraic ( One ( demultiply_list labels @@ fun ld -> { location = ld . ld_loc ; kind = Record_field ; mutability = ld . ld_mutable ; argument_type = ld . ld_type ; result_type_parameter_instances = def . type_params ; } ) ) | Type_variant constructors -> Algebraic ( demultiply_list constructors @@ fun cd -> let result_type_parameter_instances = match cd . cd_res with | None -> def . type_params | Some ret_type -> begin match Ctype . repr ret_type with | { desc = Tconstr ( _ , tyl , _ ) } -> List . map Ctype . repr tyl | _ -> assert false end in begin match cd . cd_args with | Cstr_tuple tys -> demultiply_list tys @@ fun argument_type -> { location = cd . cd_loc ; kind = Constructor_parameter ; mutability = Asttypes . Immutable ; argument_type ; result_type_parameter_instances ; } | Cstr_record labels -> demultiply_list labels @@ fun ld -> let argument_type = ld . ld_type in { location = ld . ld_loc ; kind = Constructor_field ; mutability = ld . ld_mutable ; argument_type ; result_type_parameter_instances ; } end )
type error = | Non_separable_evar of string option
type mode = Sep . t = Ind | Sep | Deepsep
let compose : mode -> mode -> mode = fun m1 m2 -> match m1 with | Deepsep -> Deepsep | Sep -> m2 | Ind -> Ind
type type_var = { text : string option ; id : int ; }
module TVarMap = Map . Make ( struct type t = type_var let compare v1 v2 = compare v1 . id v2 . id end )
type context = mode TVarMap . t
let ( ) ++ = TVarMap . union ( fun _ m1 m2 -> Some ( max_mode m1 m2 ) )
let rec immediate_subtypes : type_expr -> type_expr list = fun ty -> match ( Ctype . repr ty ) . desc with | Tarrow ( _ , ty1 , ty2 , _ ) -> [ ty1 ; ty2 ] | Ttuple ( tys ) | Tpackage ( _ , _ , tys ) -> tys | Tobject ( row , class_ty ) -> let class_subtys = match ! class_ty with | None -> [ ] | Some ( _ , tys ) -> tys in immediate_subtypes_object_row class_subtys row | Tvariant ( row ) -> immediate_subtypes_variant_row [ ] row | Tnil | Tfield _ -> immediate_subtypes_object_row [ ] ty | Tlink _ | Tsubst _ -> assert false | Tvar _ | Tunivar _ -> [ ] | Tpoly ( pty , _ ) -> [ pty ] | Tconstr ( _path , tys , _ ) -> tys | Tnil -> acc | Tfield ( _label , _kind , ty , rest ) -> let acc = ty :: acc in immediate_subtypes_object_row acc rest | _ -> ty :: acc let add_subtypes acc = let add_subtype acc ( _l , rf ) = immediate_subtypes_variant_row_field acc rf in List . fold_left add_subtype acc desc . row_fields in let add_row acc = let row = Ctype . repr desc . row_more in match row . desc with | Tvariant more -> immediate_subtypes_variant_row acc more | _ -> row :: acc in add_row ( add_subtypes acc ) | Rpresent ( None ) | Rabsent -> acc | Rpresent ( Some ( ty ) ) -> ty :: acc | Reither ( _ , field_types , _ , r ) -> let acc = List . rev_append field_types acc in begin match ! r with | None -> acc | Some rf -> immediate_subtypes_variant_row_field acc rf end
let free_variables ty = Ctype . free_variables ( Ctype . repr ty ) |> List . map ( fun { desc ; id ; _ } -> match desc with | Tvar text -> { text ; id } | _ -> assert false )
type coinductive_hyps = { safe : ModeSet . t TypeMap . t ; unsafe : ModeSet . t TypeMap . t ; poison : ModeSet . t TypeMap . t ; }