text
stringlengths 0
601k
|
---|
module DefaultContext = struct let qualifier = Reference . empty let constraint_solving_style = Configuration . Analysis . default_constraint_solving_style let debug = false let define = + Test . mock_define let resolution_fixpoint = None let error_map = None module Builder = Callgraph . NullBuilder end |
let create_annotation_store ( ? immutables = [ ] ) annotations = let immutables = String . Map . of_alist_exn immutables in let annotify ( name , annotation ) = let annotation = let create annotation = match Map . find immutables name with | Some original -> Refinement . Unit . create ( Annotation . create_immutable ~ original ( : Some original ) annotation ) | _ -> Refinement . Unit . create ( Annotation . create_mutable annotation ) in create annotation in !& name , annotation in { Refinement . Store . annotations = List . map annotations ~ f : annotify |> Reference . Map . of_alist_exn ; temporary_annotations = Reference . Map . empty ; } |
let assert_annotation_store ~ expected actual = let actual = Resolution . annotation_store actual in let compare_annotation_store { Refinement . Store . annotations = left_annotations ; temporary_annotations = left_temporary_annotations ; } { Refinement . Store . annotations = right_annotations ; temporary_annotations = right_temporary_annotations ; } = let equal_map = Reference . Map . equal [ % equal : Refinement . Unit . t ] in equal_map left_annotations right_annotations && equal_map left_temporary_annotations right_temporary_annotations in let pp_annotation_store formatter { Refinement . Store . annotations ; temporary_annotations } = let annotation_to_string ( name , refinement_unit ) = Format . asprintf " % a -> % a " Reference . pp name Refinement . Unit . pp refinement_unit in let printed_annotations = Map . to_alist annotations |> List . map ~ f : annotation_to_string |> String . concat ~ sep " :\ n " in let printed_temporary_annotations = Map . to_alist temporary_annotations |> List . map ~ f : annotation_to_string |> String . concat ~ sep " :\ n " in Format . fprintf formatter " Annotations : % s \ nTemporaryAnnotations : % s " printed_annotations printed_temporary_annotations in assert_equal ~ cmp : compare_annotation_store ~ printer ( : Format . asprintf " % a " pp_annotation_store ) ~ pp_diff ( : diff ~ print : pp_annotation_store ) expected actual |
module Create ( Context : TypeCheck . Context ) = struct let create ( ? bottom = false ) ( ? immutables = [ ] ) ~ resolution annotations = let module State = State ( Context ) in if bottom then State . unreachable else let resolution = let annotation_store = create_annotation_store ~ immutables annotations in Resolution . with_annotation_store resolution ~ annotation_store in State . create ~ resolution end |
let description ~ resolution error = let ast_environment = Resolution . global_resolution resolution |> GlobalResolution . ast_environment in Error . instantiate ~ show_error_traces : false ~ lookup ( : AstEnvironment . ReadOnly . get_relative ast_environment ) error |> Error . Instantiated . description |
let test_initial context = let assert_initial ? parent ( ? environment = " " ) ( ? immutables = [ ] ) ~ annotations define = let define = match parse_single_statement define with | { Node . value = Define ( { signature ; _ } as define ) ; _ } -> let signature = { signature with parent = parent >>| Reference . create } in { define with signature } | _ -> failwith " Unable to parse define . " in let module Context = struct let debug = false let constraint_solving_style = Configuration . Analysis . default_constraint_solving_style let qualifier = Reference . empty let define = + define let resolution_fixpoint = Some ( LocalAnnotationMap . empty ( ) ) let error_map = Some ( LocalErrorMap . empty ( ) ) module Builder = Callgraph . NullBuilder end in let resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_resolution in let module Create = Create ( Context ) in let state = Create . create ~ immutables ~ resolution annotations in let module State = State ( Context ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let initial = let variables = let extract_variables { Node . value = { Expression . Parameter . annotation ; _ } ; _ } = match annotation with | None -> [ ] | Some annotation -> let annotation = GlobalResolution . parse_annotation ( Resolution . global_resolution resolution ) annotation in Type . Variable . all_free_variables annotation in List . concat_map define . signature . parameters ~ f : extract_variables |> List . dedup_and_sort ~ compare : Type . Variable . compare in let add_variable resolution variable = Resolution . add_type_variable resolution ~ variable in let resolution = List . fold variables ~ init : resolution ~ f : add_variable in State . initial ~ resolution in assert_state_equal state initial in assert_initial " def foo ( x : int ) -> None : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial " def foo ( x : int = 1 . 0 ) -> None : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial ~ annotations [ " : x " , Type . Any ] " def foo ( x = 1 . 0 ) -> None : . . . " ; assert_initial " def foo ( x : int ) -> int : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial " def foo ( x : float , y : str ) -> None : . . . " ~ immutables [ " : x " , Type . float ; " y " , Type . string ] ~ annotations [ " : x " , Type . float ; " y " , Type . string ] ; assert_initial " def foo ( x ) -> None : . . . " ~ annotations [ " : x " , Type . Any ] ; assert_initial " def foo ( x : typing . Any ) -> None : . . . " ~ immutables [ " : x " , Type . Any ] ~ annotations [ " : x " , Type . Any ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " def __eq__ ( self , other : object ) -> None : . . . " ~ immutables [ " : other " , Type . object_primitive ] ~ annotations [ " : self " , Type . Primitive " Foo " ; " other " , Type . object_primitive ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " def foo ( self ) -> None : . . . " ~ annotations [ " : self " , Type . Primitive " Foo " ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " @ staticmethod \ ndef foo ( a ) -> None : . . . " ~ annotations [ " : a " , Type . Any ] ; assert_initial ~ environment " : T = typing . TypeVar ( ' T ' ) " " def foo ( x : test . T ) -> None : . . . " ~ immutables [ " : x " , Type . Variable . mark_all_variables_as_bound ( Type . variable " test . T " ) ] ~ annotations [ " : x " , Type . Variable . mark_all_variables_as_bound ( Type . variable " test . T " ) ] |
let test_less_or_equal context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in assert_true ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . Top ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ; " y " , Type . integer ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ " x " , Type . Top ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " x " , Type . string ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " y " , Type . integer ] ) ) |
let test_widen context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let widening_threshold = 3 in assert_state_equal ( State . widen ~ previous ( : create [ " x " , Type . string ] ) ~ next ( : create [ " x " , Type . integer ] ) ~ iteration : 0 ) ( create [ " x " , Type . union [ Type . integer ; Type . string ] ] ) ; assert_state_equal ( State . widen ~ previous ( : create [ " x " , Type . string ] ) ~ next ( : create [ " x " , Type . integer ] ) ~ iteration ( : widening_threshold + 1 ) ) ( create [ " x " , Type . Top ] ) |
let test_check_annotation context = let assert_check_annotation source variable_name descriptions = let resolution = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_resolution in let module State = State ( DefaultContext ) in let errors = let expression = let location = { Location . start = { line = 1 ; column = 1 } ; stop = { line = 1 ; column = 1 + String . length variable_name } ; } in let value = Expression . Expression . Name ( Expression . create_name ~ location variable_name ) in Node . create ~ location value in State . parse_and_check_annotation ~ resolution expression |> fst |> AnalysisError . deduplicate in let errors = List . map ~ f ( : description ~ resolution ) errors in assert_equal ~ cmp ( : List . equal String . equal ) ~ printer ( : String . concat ~ sep " :\ n " ) descriptions errors in assert_check_annotation " " " x " [ " Undefined or invalid type [ 11 ] : Annotation ` x ` is not defined as a type . " ] ; assert_check_annotation " x : int = 1 " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x : typing . Type [ int ] = int " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x = int " " test . x " [ ] ; assert_check_annotation " x : typing . Any " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x = typing . Any " " test . x " [ ] ; assert_check_annotation " x : typing_extensions . TypeAlias = typing . Any " " test . x " [ ] ; assert_check_annotation { | class Foo : . . . x = Foo } | " test . x " [ ] ; assert_check_annotation { | class Foo : . . . x = Foo ( ) } | " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation { | class Foo : def __getitem__ ( self , other ) -> typing . Any : . . . x = Foo [ Undefined ] } | " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] |
let assert_resolved ~ context sources expression expected = let resolution = ScratchProject . setup ~ context sources |> ScratchProject . build_resolution in let resolved = Resolution . resolve_expression_to_type resolution ( parse_single_expression expression ) in assert_equal ~ printer : Type . show ~ cmp : Type . equal expected resolved |
let test_module_exports context = let assert_exports_resolved expression expected = let sources = [ " implementing . py " , { | def function ( ) -> int : . . . constant : int = 1 } ; | ( " exporting . py " , { | from implementing import function , constant from implementing import function as aliased from indirect import cyclic } | ) ; " indirect . py " , { | from exporting import constant , cyclic } ; | " wildcard . py " , { | from exporting import * } ; | ( " exporting_wildcard_default . py " , { | from implementing import function , constant from implementing import function as aliased __all__ = [ " constant " ] } | ) ; " wildcard_default . py " , { | from exporting_wildcard_default import * } ; | ] in assert_resolved ~ context sources expression expected in assert_exports_resolved " implementing . constant " Type . integer ; assert_exports_resolved " implementing . function ( ) " Type . integer ; assert_exports_resolved " implementing . undefined " Type . Top ; assert_exports_resolved " exporting . constant " Type . integer ; assert_exports_resolved " exporting . function ( ) " Type . integer ; assert_exports_resolved " exporting . aliased ( ) " Type . integer ; assert_exports_resolved " exporting . undefined " Type . Top ; assert_exports_resolved " indirect . constant " Type . integer ; assert_exports_resolved " indirect . cyclic " Type . Top ; assert_exports_resolved " wildcard . constant " Type . integer ; assert_exports_resolved " wildcard . cyclic " Type . Top ; assert_exports_resolved " wildcard . aliased ( ) " Type . integer ; assert_exports_resolved " wildcard_default . constant " Type . integer ; assert_exports_resolved " wildcard_default . aliased ( ) " Type . Any ; let assert_fixpoint_stop = assert_resolved ~ context [ " loop / b . py " , { | b : int = 1 } ; | " loop / a . py " , { | from loop . b import b } ; | " loop / a . py " , { | from loop . a import b } ; | " no_loop / b . py " , { | b : int = 1 } ; | " no_loop / a . py " , { | from no_loop . b import b as c } ; | " no_loop / __init__ . py " , { | from no_loop . a import c } ; | ] in assert_fixpoint_stop " loop . b " Type . Top ; assert_fixpoint_stop " no_loop . c " Type . integer |
let test_object_callables context = let assert_resolved expression annotation = assert_resolved ~ context [ ( " module . py " , { | _K = typing . TypeVar ( ' _K ' ) _V = typing . TypeVar ( ' _V ' ) _T = typing . TypeVar ( ' _T ' ) class object : def __init__ ( self ) -> None : pass class Call ( object , typing . Generic [ _K , _V ] ) : attribute : _K generic_callable : typing . Callable [ [ _K ] , _V ] def __call__ ( self ) -> _V : . . . class Submodule ( Call [ _T , _T ] , typing . Generic [ _T ] ) : pass call : Call [ int , str ] = . . . meta : typing . Type [ Call [ int , str ] ] = . . . submodule : Submodule [ int ] = . . . } | ) ; ] expression ( Type . create ~ aliases : Type . empty_aliases ( parse_single_expression annotation ) ) in assert_resolved " module . call " " module . Call [ int , str ] " ; assert_resolved " module . call . attribute " " int " ; assert_resolved " module . call . generic_callable " " typing . Callable [ [ int ] , str ] " ; assert_resolved " module . call ( ) " " str " ; assert_resolved " module . meta " " typing . Type [ module . Call [ int , str ] ] " ; assert_resolved " module . meta ( ) " " module . Call [ int , str ] " ; assert_resolved " module . submodule . generic_callable " " typing . Callable [ [ int ] , int ] " |
let test_callable_selection context = let assert_resolved source expression annotation = assert_resolved ~ context [ " test . py " , source ] expression ( Type . create ~ aliases : Type . empty_aliases ( parse_single_expression annotation ) ) in assert_resolved " call : typing . Callable [ [ ] , int ] " " test . call ( ) " " int " ; assert_resolved " call : typing . Callable [ [ int ] , int ] " " test . call ( ) " " int " |
type parameter_kind = | NamedParameter | VariableParameter | KeywordParameter |
let test_forward_expression context = let assert_forward ( ? precondition = [ ] ) ( ? postcondition = [ ] ) ( ? environment = " " ) expression annotation = let expression = let expression = parse expression |> Preprocessing . preprocess in expression |> function | { Source . statements = [ { Node . value = Expression expression ; _ } ] ; _ } -> expression | _ -> failwith " Unable to extract expression " in let global_resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_global_resolution in let new_resolution , resolved = let resolution = let annotation_store = create_annotation_store precondition in TypeCheck . resolution ~ annotation_store global_resolution ( module TypeCheck . DummyContext ) in Resolution . resolve_expression resolution expression in assert_annotation_store ~ expected ( : create_annotation_store postcondition ) new_resolution ; assert_equal ~ cmp : Type . equal ~ printer : Type . show annotation resolved in assert_forward " await awaitable_int ( ) " Type . integer ; assert_forward " await undefined " Type . Any ; assert_forward " 1 or ' string ' " ( Type . literal_integer 1 ) ; assert_forward " 1 and ' string ' " ( Type . literal_string " string " ) ; assert_forward " undefined or 1 " Type . Top ; assert_forward " 1 or undefined " ( Type . literal_integer 1 ) ; assert_forward " undefined and undefined " Type . Top ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 0 or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " False or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " None or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " ' ' or y " Type . integer ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " b ' ' or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . NoneType ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . NoneType ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . literal_integer 0 ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . literal_integer 0 ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . Literal ( Type . Boolean false ) ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . Literal ( Type . Boolean false ) ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . union [ Type . NoneType ; Type . integer ; Type . string ] ] ~ postcondition [ " : x " , Type . union [ Type . NoneType ; Type . integer ; Type . string ] ] " x or 1 " ( Type . Union [ Type . integer ; Type . string ] ) ; assert_forward ~ precondition [ " : x " , Type . union [ Type . NoneType ; Type . literal_integer 0 ] ; " y " , Type . string ] ~ postcondition [ " : x " , Type . union [ Type . NoneType ; Type . literal_integer 0 ] ; " y " , Type . string ] " x or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 1 and y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 1 and y " Type . string ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " ' foo ' and y " Type . integer ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " b ' foo ' and y " Type . integer ; assert_forward ~ precondition : [ " x " , Type . union [ Type . literal_integer 1 ; Type . literal_integer 2 ] ; " y " , Type . string ] ~ postcondition : [ " x " , Type . union [ Type . literal_integer 1 ; Type . literal_integer 2 ] ; " y " , Type . string ] " x and y " Type . string ; let assert_optional_forward ( ? postcondition = [ " x " , Type . optional Type . integer ] ) = assert_forward ~ precondition [ " : x " , Type . optional Type . integer ] ~ postcondition in assert_optional_forward " x or 1 " Type . integer ; assert_optional_forward " x or x " ( Type . optional Type . integer ) ; assert_optional_forward " x and 1 " ( Type . optional Type . integer ) ; assert_optional_forward " 1 and x " ( Type . optional Type . integer ) ; assert_optional_forward " x and x " ( Type . optional Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . dictionary ~ key : Type . integer ~ value : Type . Bottom ] ~ postcondition [ " : x " , Type . dictionary ~ key : Type . integer ~ value : Type . Bottom ] " x . add_key ( ' string ' ) " Type . none ; assert_forward ~ precondition [ " : unknown " , Type . Top ] ~ postcondition [ " : unknown " , Type . Top ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : int ) -> typing . Optional [ Foo ] : . . . } | " test . foo ( unknown ) . attribute " Type . Top ; assert_forward ~ precondition [ " : foo_instance " , Type . Primitive " Foo " ] ~ postcondition [ " : foo_instance " , Type . Primitive " Foo " ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : typing . Any ) -> Foo : . . . } | " test . foo ( foo_instance . unknown ) . attribute " Type . integer ; assert_forward ~ precondition [ " : foo_instance " , Type . Primitive " test . Foo " ] ~ postcondition [ " : foo_instance " , Type . Primitive " test . Foo " ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : typing . Any ) -> Foo : . . . } | " test . foo ( foo_instance . unknown ) . another_unknown " Type . Top ; assert_forward " 1 < 2 " Type . bool ; assert_forward " 1 < 2 < 3 " Type . bool ; assert_forward " 1 is 2 " Type . bool ; assert_forward ~ precondition [ " : container " , Type . list Type . integer ] ~ postcondition [ " : container " , Type . list Type . integer ] " 1 in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . list Type . integer ] ~ postcondition [ " : container " , Type . list Type . integer ] " 1 not in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . iterator Type . integer ] ~ postcondition [ " : container " , Type . iterator Type . integer ] " 1 in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . iterator Type . integer ] ~ postcondition [ " : container " , Type . iterator Type . integer ] " 1 not in container " Type . bool ; assert_forward ~ environment : { | class MetaFoo ( type ) : def __contains__ ( self , x : int ) -> bool : . . . class Foo ( metaclass = MetaFoo ) : def foo ( self ) -> int : return 9 } | ~ precondition [ " : Container " , Type . meta ( Type . Primitive " test . Foo " ) ] ~ postcondition [ " : Container " , Type . meta ( Type . Primitive " test . Foo " ) ] " 1 in Container " Type . bool ; let dictionary_set_union = Type . Union [ Type . dictionary ~ key : Type . integer ~ value : Type . string ; Type . set Type . integer ] in assert_forward ~ precondition [ " : Container " , dictionary_set_union ] ~ postcondition [ " : Container " , dictionary_set_union ] " 1 in Container " Type . bool ; assert_forward " undefined < 1 " Type . bool ; assert_forward " undefined == undefined " Type . Any ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] ~ postcondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] " getattr ( x , y ) " Type . integer ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition [ " : x " , Type . Primitive " test . Foo " ; " y " , Type . string ] ~ postcondition [ " : x " , Type . Primitive " test . Foo " ; " y " , Type . string ] " getattr ( x , y ) " Type . Any ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] ~ postcondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] " getattr ( x , y , None ) " Type . integer ; assert_forward " 1j " Type . complex ; assert_forward " 1 " ( Type . literal_integer 1 ) ; assert_forward { " " } || ( Type . literal_string " " ) ; assert_forward { | b " " } | ( Type . literal_bytes " " ) ; assert_forward " { 1 : 1 } " ( Type . dictionary ~ key : Type . integer ~ value : Type . integer ) ; assert_forward " { 1 : ' string ' } " ( Type . dictionary ~ key : Type . integer ~ value : Type . string ) ; assert_forward " { b ' ' : ' ' } " ( Type . dictionary ~ key : Type . bytes ~ value : Type . string ) ; assert_forward " { 1 : 1 , ' string ' : 1 } " ( Type . dictionary ~ key ( : Type . union [ Type . integer ; Type . string ] ) ~ value : Type . integer ) ; assert_forward " { 1 : 1 , 1 : ' string ' } " ( Type . dictionary ~ key : Type . integer ~ value ( : Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { { ** 1 : 1 } } " ( Type . dictionary ~ key : Type . integer ~ value : Type . integer ) ; assert_forward " { { ** 1 : 1 } , { ' ** a ' : ' b ' } } " ( Type . dictionary ~ key ( : Type . union [ Type . integer ; Type . string ] ) ~ value ( : Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { 1 : ' string ' , { ** undefined : 1 } } " Type . Top ; assert_forward " { undefined : 1 } " ( Type . dictionary ~ key : Type . Top ~ value : Type . integer ) ; assert_forward " { 1 : undefined } " ( Type . dictionary ~ key : Type . integer ~ value : Type . Top ) ; assert_forward " { 1 : undefined , undefined : undefined } " ( Type . dictionary ~ key : Type . Top ~ value : Type . Top ) ; assert_forward " { key : value for key in [ 1 ] for value in [ ' string ' ] } " ( Type . dictionary ~ key : Type . integer ~ value : Type . string ) ; assert_forward " . . . " Type . Any ; assert_forward " False " ( Type . Literal ( Type . Boolean false ) ) ; assert_forward " 1 . 0 " Type . float ; assert_forward " ( element for element in [ 1 ] ) " ( Type . generator_expression Type . integer ) ; assert_forward " ( element for element in [ ] ) " ( Type . generator_expression Type . Any ) ; assert_forward " ( ( element , independent ) for element in [ 1 ] for independent in [ ' string ' ] ) " ( Type . generator_expression ( Type . tuple [ Type . integer ; Type . string ] ) ) ; assert_forward " ( nested for element in [ [ 1 ] ] for nested in element ) " ( Type . generator_expression Type . integer ) ; assert_forward " ( undefined for element in [ 1 ] ) " ( Type . generator_expression Type . Top ) ; assert_forward " ( element for element in undefined ) " ( Type . generator_expression Type . Any ) ; let callable ~ parameters ~ annotation = let parameters = let open Type . Callable in let to_parameter ( name , kind , default ) = match kind with | NamedParameter -> Parameter . Named { name ; annotation = Type . Any ; default } | VariableParameter -> Parameter . Variable ( Concrete Type . Any ) | KeywordParameter -> Parameter . Keywords Type . Any in Defined ( List . map parameters ~ f : to_parameter ) in Type . Callable . create ~ parameters ~ annotation ( ) in assert_forward " lambda : 1 " ( callable ~ parameters [ ] : ~ annotation : Type . integer ) ; assert_forward " lambda parameter : parameter " ( callable ~ parameters [ " : parameter " , NamedParameter , false ] ~ annotation : Type . Any ) ; assert_forward " lambda parameter = 1 : parameter " ( callable ~ parameters [ " : parameter " , NamedParameter , true ] ~ annotation : Type . Any ) ; assert_forward " lambda * parameter : 42 " ( callable ~ parameters [ " : parameter " , VariableParameter , false ] ~ annotation : Type . integer ) ; assert_forward " lambda ** parameter : 42 " ( callable ~ parameters [ " : parameter " , KeywordParameter , false ] ~ annotation : Type . integer ) ; assert_forward " lambda : undefined " ( callable ~ parameters [ ] : ~ annotation : Type . Top ) ; Type . Variable . Namespace . reset ( ) ; let empty_list = Type . list ( Type . variable " _T " |> Type . Variable . mark_all_free_variables_as_escaped ) in Type . Variable . Namespace . reset ( ) ; assert_forward " [ ] " empty_list ; assert_forward " [ 1 ] " ( Type . list Type . integer ) ; assert_forward " [ 1 , ' string ' ] " ( Type . list ( Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " [ undefined ] " ( Type . list Type . Top ) ; assert_forward " [ undefined , undefined ] " ( Type . list Type . Top ) ; assert_forward " [ element for element in [ 1 ] ] " ( Type . list Type . integer ) ; assert_forward " [ 1 for _ in [ 1 ] ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ * x ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ 1 , * x ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ ' ' , * x ] " ( Type . list ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_forward ~ precondition [ " : x " , Type . integer ] ~ postcondition [ " : x " , Type . integer ] " x " Type . integer ; assert_forward " { 1 } " ( Type . set Type . integer ) ; assert_forward " { 1 , ' string ' } " ( Type . set ( Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { undefined } " ( Type . set Type . Top ) ; assert_forward " { undefined , undefined } " ( Type . set Type . Top ) ; assert_forward " { element for element in [ 1 ] } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " { * x } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " { 1 , * x } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . set Type . integer ] ~ postcondition [ " : x " , Type . set Type . integer ] " { ' ' , * x } " ( Type . set ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_forward " * 1 " Type . Top ; assert_forward " * undefined " Type . Top ; assert_forward " ' string ' " ( Type . literal_string " string " ) ; assert_forward " f ' string ' " Type . string ; assert_forward " f ' string { 1 } ' " Type . string ; assert_forward " f ' string { undefined } ' " Type . string ; assert_forward " 3 if True else 1 " ( Type . union [ Type . literal_integer 3 ; Type . literal_integer 1 ] ) ; assert_forward " True if True else False " ( Type . union [ Type . Literal ( Type . Boolean true ) ; Type . Literal ( Type . Boolean false ) ] ) ; assert_forward " ' foo ' if True else ' bar ' " ( Type . union [ Type . literal_string " foo " ; Type . literal_string " bar " ] ) ; assert_forward " 1 . 0 if True else 1 " Type . float ; assert_forward " 1 if True else 1 . 0 " Type . float ; assert_forward " undefined if True else 1 " Type . Top ; assert_forward " 1 if undefined else 1 " ( Type . literal_integer 1 ) ; assert_forward " 1 if True else undefined " Type . Top ; assert_forward " undefined if undefined else undefined " Type . Top ; assert_forward ~ precondition [ " : x " , Type . integer ] ~ postcondition [ " : x " , Type . integer ] " x if x is not None else 32 " Type . integer ; assert_forward " True " ( Type . Literal ( Boolean true ) ) ; assert_forward " 1 , " ( Type . tuple [ Type . literal_integer 1 ] ) ; assert_forward " 1 , ' string ' " ( Type . tuple [ Type . literal_integer 1 ; Type . literal_string " string " ] ) ; assert_forward " undefined , " ( Type . tuple [ Type . Top ] ) ; assert_forward " undefined , undefined " ( Type . tuple [ Type . Top ; Type . Top ] ) ; assert_forward " not 1 " Type . bool ; assert_forward " not undefined " Type . bool ; assert_forward " + 1 " ( Type . literal_integer 1 ) ; assert_forward " ~ 1 " Type . integer ; assert_forward " - undefined " Type . Any ; assert_forward " ( x := True ) " ( Type . Literal ( Boolean true ) ) ~ postcondition [ " : x " , Type . Literal ( Boolean true ) ] ; assert_forward ~ environment : { | Ts = pyre_extensions . TypeVarTuple ( " Ts " ) Rs = pyre_extensions . TypeVarTuple ( " Rs " ) def foo ( x : typing . Tuple [ pyre_extensions . Unpack [ Ts ] ] , y : typing . Tuple [ pyre_extensions . Unpack [ Rs ] ] ) -> pyre_extensions . Broadcast [ typing . Tuple [ pyre_extensions . Unpack [ Ts ] ] , typing . Tuple [ pyre_extensions . Unpack [ Rs ] ] , ] : . . . } | " foo ( ( 2 , 2 ) , ( 3 , 3 ) ) " Type . Any ; assert_forward " typing . Optional [ int ] " ( Type . meta ( Type . optional Type . integer ) ) ; assert_forward " typing . Callable [ [ int , str ] , int ] " ( Type . meta ( Type . Callable . create ~ annotation : Type . integer ( ) ) ) ; assert_forward " typing_extensions . Literal [ 1 , 2 , 3 ] " ( Type . meta Type . Any ) ; assert_forward " typing . ClassVar [ int ] " ( Type . meta ( Type . parametric " typing . ClassVar " [ Single Type . integer ] ) ) ; assert_forward " typing . Union [ int , str ] " ( Type . meta Type . Any ) ; let assert_annotation ( ? precondition = [ ] ) ( ? environment = " " ) expression annotation = let expression = let expression = parse expression in expression |> function | { Source . statements = [ { Node . value = Expression expression ; _ } ] ; _ } -> expression | _ -> failwith " Unable to extract expression " in let resolution = let global_resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_global_resolution in let annotation_store = create_annotation_store precondition in TypeCheck . resolution ~ annotation_store global_resolution ( module TypeCheck . DummyContext ) in let resolved_annotation = Resolution . resolve_expression_to_annotation resolution expression in assert_equal ~ cmp : Annotation . equal ~ printer : Annotation . show annotation resolved_annotation in assert_annotation ~ environment " : x = 1 " " test . x " ( Annotation . create_immutable Type . integer ) ; assert_annotation ~ environment " : x : typing . Union [ int , str ] = 1 " " test . x " ( Annotation . create_immutable ~ original ( : Some ( Type . union [ Type . string ; Type . integer ] ) ) ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_annotation ~ environment : { | class Foo : def __init__ ( self ) : self . attribute : int = 1 } | " test . Foo ( ) . attribute " ( Annotation . create_immutable Type . integer ) |
let test_forward_statement context = let global_resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_global_resolution in let assert_forward ( ? precondition_immutables = [ ] ) ( ? postcondition_immutables = [ ] ) ( ? bottom = false ) precondition statement postcondition = let forwarded = let parsed = parse statement |> function | { Source . statements = statement :: rest ; _ } -> statement :: rest | _ -> failwith " unable to parse test " in let resolution = let annotation_store = create_annotation_store ~ immutables : precondition_immutables precondition in TypeCheck . resolution global_resolution ~ annotation_store ( module TypeCheck . DummyContext ) in let rec process_statement resolution = function | [ ] -> Some resolution | statement :: rest -> ( match Resolution . resolve_statement resolution statement with | Resolution . Unreachable -> None | Resolution . Reachable { resolution ; _ } -> process_statement resolution rest ) in process_statement resolution parsed in match forwarded with | None -> assert_true bottom | Some actual_resolution -> assert_false bottom ; assert_annotation_store ~ expected ( : create_annotation_store ~ immutables : postcondition_immutables postcondition ) actual_resolution in assert_forward [ " y " , Type . integer ] " x = y " [ " x " , Type . integer ; " y " , Type . integer ] ; assert_forward [ " y " , Type . integer ; " z " , Type . Top ] " x = z " [ " x " , Type . Top ; " y " , Type . integer ; " z " , Type . Top ] ; assert_forward [ " x " , Type . integer ] " x += 1 " [ " x " , Type . integer ] ; assert_forward [ " z " , Type . integer ] " x = y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . integer ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . Any ] [ ] " x : Derp " [ " x " , Type . Any ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . string ] [ ] " x : str = 1 " [ " x " , Type . string ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . union [ Type . string ; Type . integer ] ] [ ] " x : typing . Union [ int , str ] = 1 " [ " x " , Type . literal_integer 1 ] ; assert_forward [ " c " , Type . integer ; " d " , Type . Top ] " a , b = c , d " [ " a " , Type . integer ; " b " , Type . Top ; " c " , Type . integer ; " d " , Type . Top ] ; assert_forward [ " z " , Type . integer ] " x , y = z " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . integer ] ; assert_forward [ " z " , Type . tuple [ Type . integer ; Type . string ; Type . string ] ] " x , y = z " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . tuple [ Type . integer ; Type . string ; Type . string ] ] ; assert_forward [ " y " , Type . integer ; " z " , Type . Top ] " x = y , z " [ " x " , Type . tuple [ Type . integer ; Type . Top ] ; " y " , Type . integer ; " z " , Type . Top ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . tuple [ Type . Any ; Type . Any ] ] [ ] " x : typing . Tuple [ typing . Any , typing . Any ] = 1 , 2 " [ " x " , Type . tuple [ Type . literal_integer 1 ; Type . literal_integer 2 ] ] ; assert_forward [ " z " , Type . tuple [ Type . integer ; Type . string ] ] " x , y = z " [ " x " , Type . integer ; " y " , Type . string ; " z " , Type . tuple [ Type . integer ; Type . string ] ] ; assert_forward [ " z " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " x , y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ ] " ( x , y ) , z = 1 " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . Any ] ; assert_forward [ " z " , Type . list Type . integer ] " x , y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . list Type . integer ] ; assert_forward [ ] " x , y = return_tuple ( ) " [ " x " , Type . integer ; " y " , Type . integer ] ; assert_forward [ ] " x = ( ) " [ " x " , Type . Tuple ( Concrete [ ] ) ] ; assert_forward [ " x " , Type . list Type . integer ] " [ a , b ] = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . integer ] ; assert_forward [ " x " , Type . list Type . integer ] " [ a , * b ] = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . list Type . integer ] ; assert_forward [ " x " , Type . list Type . integer ] " a , * b = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . list Type . integer ] ; assert_forward [ " x " , Type . iterable Type . integer ] " [ a , b ] = x " [ " x " , Type . iterable Type . integer ; " a " , Type . integer ; " b " , Type . integer ] ; assert_forward [ " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " a , b = c " [ " a " , Type . integer ; " b " , Type . integer ; " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " * a , b = c " [ " a " , Type . list Type . integer ; " b " , Type . integer ; " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ] " * a , b = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ; " a " , Type . list ( Type . union [ Type . integer ; Type . string ] ) ; " b " , Type . float ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ] " a , * b = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ; " a " , Type . integer ; " b " , Type . list ( Type . union [ Type . string ; Type . float ] ) ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . integer ; Type . float ] ] " a , * b , c = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . integer ; Type . float ] ; " a " , Type . integer ; " b " , Type . list ( Type . union [ Type . string ; Type . integer ] ) ; " c " , Type . float ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ] ] " a , * b = x " [ " x " , Type . tuple [ Type . integer ] ; " a " , Type . integer ; " b " , Type . tuple [ ] ] ; assert_forward [ " x " , Type . tuple [ Type . integer ] ] " * b , c = x " [ " x " , Type . tuple [ Type . integer ] ; " b " , Type . tuple [ ] ; " c " , Type . integer ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . float ] ] " a , * b , c = x " [ " x " , Type . tuple [ Type . integer ; Type . float ] ; " a " , Type . integer ; " b " , Type . tuple [ ] ; " c " , Type . float ; ] ; assert_forward ~ postcondition_immutables [ " : y " , Type . integer ] [ ] " y : int " [ " y " , Type . integer ] ; assert_forward ~ postcondition_immutables [ " : y " , Type . integer ] [ ] " y : int = x " [ " y " , Type . integer ] ; assert_forward ~ precondition_immutables [ " : y " , Type . Top ] ~ postcondition_immutables [ " : y " , Type . Top ] [ " x " , Type . Top ; " y " , Type . Top ] " y = x " [ " x " , Type . Top ; " y " , Type . Top ] ; assert_forward ~ precondition_immutables [ " : y " , Type . string ] ~ postcondition_immutables [ " : y " , Type . integer ] [ " y " , Type . string ] " y : int " [ " y " , Type . integer ] ; assert_forward [ " d " , Type . dictionary ~ key : Type . string ~ value : Type . integer ] " del d [ 0 ] " [ " d " , Type . dictionary ~ key : Type . string ~ value : Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x " [ " x " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . integer ] " assert y " [ " x " , Type . optional Type . integer ; " y " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x is not None " [ " x " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] " assert x and y " [ " x " , Type . integer ; " y " , Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ; " z " , Type . optional Type . float ] " assert x and ( y and z ) " [ " x " , Type . integer ; " y " , Type . float ; " z " , Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] " assert x or y " [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x is None " [ " x " , Type . none ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert ( not x ) or 1 " [ " x " , Type . optional Type . integer ] ; assert_forward [ " x " , Type . list ( Type . optional Type . integer ) ] " assert all ( x ) " [ " x " , Type . list Type . integer ] ; assert_forward [ " x " , Type . iterable ( Type . optional Type . integer ) ] " assert all ( x ) " [ " x " , Type . iterable Type . integer ] ; assert_forward [ " x " , Type . list ( Type . union [ Type . none ; Type . integer ; Type . string ] ) ] " assert all ( x ) " [ " x " , Type . list ( Type . union [ Type . integer ; Type . string ] ) ] ; assert_forward [ " x " , Type . awaitable ( Type . union [ Type . none ; Type . integer ] ) ] " assert all ( x ) " [ " x " , Type . awaitable ( Type . union [ Type . none ; Type . integer ] ) ] ; assert_forward [ " x " , Type . dictionary ~ key ( : Type . optional Type . integer ) ~ value : Type . integer ] " assert all ( x ) " [ " x " , Type . dictionary ~ key ( : Type . optional Type . integer ) ~ value : Type . integer ] ; assert_forward [ " x " , Type . dictionary ~ key : Type . integer ~ value : Type . string ; " y " , Type . float ] " assert y in x " [ " x " , Type . dictionary ~ key : Type . integer ~ value : Type . string ; " y " , Type . integer ] ; assert_forward [ " x " , Type . list Type . string ; " y " , Type . union [ Type . integer ; Type . string ] ] " assert y in x " [ " x " , Type . list Type . string ; " y " , Type . string ] ; assert_forward [ " x " , Type . list Type . Top ; " y " , Type . integer ] " assert y in x " [ " x " , Type . list Type . Top ; " y " , Type . integer ] ; assert_forward [ ] " assert None in [ 1 ] " [ ] ; assert_forward [ " x " , Type . list Type . Top ] " assert None in x " [ " x " , Type . list Type . Top ] ; assert_forward ~ precondition_immutables [ " : x " , Type . float ] ~ postcondition_immutables [ " : x " , Type . float ] [ " x " , Type . float ] " assert x in [ 1 ] " [ " x " , Type . integer ] ; assert_forward ~ bottom : true [ " x " , Type . none ] " assert x " [ " x " , Type . none ] ; assert_forward ~ bottom : true [ " x " , Type . none ] " assert x is not None " [ " x " , Type . none ] ; let assert_refinement_by_type_comparison ( ? bottom = false ) ~ precondition ( ? negated = false ) ~ variable ~ type_expression ~ postcondition ( ) = let assert_forward_expression assertion_expression = assert_forward ~ bottom precondition ( Format . asprintf " assert % s " assertion_expression ) postcondition in Format . asprintf " % s isinstance ( % s , % s ) " ( if negated then " not " else " " ) variable type_expression |> assert_forward_expression ; Format . asprintf " type ( % s ) % s % s " variable ( if negated then " is not " else " is " ) type_expression |> assert_forward_expression ; Format . asprintf " type ( % s ) % s % s " variable ( if negated then " " != else " " ) == type_expression |> assert_forward_expression in assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ] ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ; " y " , Type . Top ] ~ variable " : y " ~ type_expression " : str " ~ postcondition [ " : x " , Type . Any ; " y " , Type . string ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ] ~ variable " : x " ~ type_expression " ( : int , str ) " ~ postcondition [ " : x " , Type . union [ Type . integer ; Type . string ] ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " ( : int , str ) " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " : str " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . Bottom ] ~ variable " : x " ~ type_expression " : str " ~ postcondition [ " : x " , Type . string ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . float ] ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " : 1 " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ negated : true ~ variable " : x " ~ type_expression " : float " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . float ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . float ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . optional ( Type . union [ Type . integer ; Type . string ] ) ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . optional Type . string ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . optional ( Type . union [ Type . integer ; Type . string ] ) ] ~ negated : true ~ variable " : x " ~ type_expression " : type ( None ) " ~ postcondition [ " : x " , Type . union [ Type . integer ; Type . string ] ] ( ) ; assert_refinement_by_type_comparison ~ precondition : [ " my_type " , Type . tuple [ Type . meta Type . integer ; Type . meta Type . string ] ; " x " , Type . Top ] ~ variable " : x " ~ type_expression " : my_type " ~ postcondition : [ " my_type " , Type . tuple [ Type . meta Type . integer ; Type . meta Type . string ] ; " x " , Type . union [ Type . integer ; Type . string ] ; ] ( ) ; assert_refinement_by_type_comparison ~ precondition : [ ( " my_type " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation ( Type . meta Type . integer ) ) ) ; " x " , Type . Top ; ] ~ variable " : x " ~ type_expression " : my_type " ~ postcondition : [ ( " my_type " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation ( Type . meta Type . integer ) ) ) ; " x " , Type . integer ; ] ( ) ; assert_forward ~ bottom : true [ " x " , Type . integer ] " assert not isinstance ( x + 1 , int ) " [ " x " , Type . integer ] ; assert_forward ~ bottom : false [ " x " , Type . Bottom ] " assert not isinstance ( x , int ) " [ " x " , Type . Bottom ] ; assert_forward ~ bottom : true [ ] " assert False " [ ] ; assert_forward ~ bottom : true [ ] " assert None " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 . 0 " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 . 0j " [ ] ; assert_forward ~ bottom : true [ ] " assert ' ' " [ ] ; assert_forward ~ bottom : true [ ] " assert b ' ' " [ ] ; assert_forward ~ bottom : true [ ] " assert [ ] " [ ] ; assert_forward ~ bottom : true [ ] " assert ( ) " [ ] ; assert_forward ~ bottom : true [ ] " assert { } " [ ] ; assert_forward ~ bottom : false [ ] " assert ( not True ) " [ ] ; assert_forward [ ] " raise 1 " [ ] ; assert_forward [ ] " raise Exception " [ ] ; assert_forward [ ] " raise Exception ( ) " [ ] ; assert_forward [ ] " raise undefined " [ ] ; assert_forward [ ] " raise " [ ] ; assert_forward [ ] " return 1 " [ ] ; assert_forward [ " y " , Type . integer ] " pass " [ " y " , Type . integer ] |
let test_forward context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let assert_forward ( ? precondition_bottom = false ) ( ? postcondition_bottom = false ) precondition statement postcondition = let forwarded = let parsed = parse statement |> function | { Source . statements = statement :: rest ; _ } -> statement :: rest | _ -> failwith " unable to parse test " in List . fold ~ f ( : fun state statement -> State . forward ~ statement_key : Cfg . entry_index ~ statement state ) ~ init ( : create ~ bottom : precondition_bottom precondition ) parsed in assert_state_equal ( create ~ bottom : postcondition_bottom postcondition ) forwarded in assert_forward [ ] " x = 1 " [ " x " , Type . literal_integer 1 ] ; assert_forward ~ precondition_bottom : true ~ postcondition_bottom : true [ ] " x = 1 " [ ] ; assert_forward ~ postcondition_bottom : true [ ] " sys . exit ( 1 ) " [ ] |
type method_call = { direct_target : string ; class_name : string ; dispatch : Callgraph . dispatch ; is_optional_class_attribute : bool ; } |
type property_setter_call = { direct_target : string ; class_name : string ; } |
let function_caller name = Callgraph . FunctionCaller !& name |
let property_setter_caller name = Callgraph . PropertySetterCaller !& name |
let test_calls context = let assert_calls source calls = let project = ScratchProject . setup ~ context [ " qualifier . py " , source ] in let _ = ScratchProject . build_type_environment project in let assert_calls ( caller , callees ) = let expected_callees = let callee = function | ` Method { direct_target ; class_name ; dispatch ; is_optional_class_attribute } -> Callgraph . Method { direct_target = Reference . create direct_target ; class_name = Type . Primitive class_name ; dispatch ; is_optional_class_attribute ; } | ` Function name -> Callgraph . Function ( Reference . create name ) | ` PropertySetter { direct_target ; class_name } -> Callgraph . PropertySetter { direct_target = Reference . create direct_target ; class_name = Type . Primitive class_name ; } in List . map callees ~ f : callee |> List . map ~ f : Callgraph . show_callee |> String . Set . of_list in let actual_callees = let show { Callgraph . callee ; _ } = Callgraph . show_callee callee in Callgraph . get ~ caller |> List . map ~ f : show |> String . Set . of_list in assert_equal ~ printer ( : fun set -> Set . to_list set |> String . concat ~ sep " , " ) : ~ cmp : String . Set . equal expected_callees actual_callees in List . iter calls ~ f : assert_calls ; Memory . reset_shared_memory ( ) in assert_calls { | def foo ( ) : . . . def calls_foo ( ) : foo ( ) } | [ function_caller " qualifier . foo " , [ ] ; function_caller " qualifier . calls_foo " , [ ` Function " qualifier . foo " ] ; ] ; assert_calls { | def foo ( ) : . . . def bar ( ) : . . . def calls_on_same_line ( ) : foo ( ) ; bar ( ) } | [ ( function_caller " qualifier . calls_on_same_line " , [ ` Function " qualifier . foo " ; ` Function " qualifier . bar " ] ) ; ] ; assert_calls { | class Class : def method ( ) : . . . def calls_method ( c : Class ) : c . method ( ) } | [ ( function_caller " qualifier . calls_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; dispatch = Dynamic ; is_optional_class_attribute = false ; } ; ] ) ; ] ; assert_calls { | class Class : . . . class ClassWithInit : def __init__ ( self ) : super ( ) . __init__ ( ) def calls_Class ( ) : Class ( ) def calls_ClassWithInit ( ) : ClassWithInit ( ) def calls_ClassWithInit__init__ ( object : object ) : ClassWithInit . __init__ ( object ) } | [ ( function_caller " qualifier . ClassWithInit . __init__ " , [ ` Method { direct_target = " object . __init__ " ; class_name = " object " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Class " , [ ` Method { direct_target = " object . __init__ " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_ClassWithInit " , [ ` Method { direct_target = " qualifier . ClassWithInit . __init__ " ; class_name = " qualifier . ClassWithInit " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_ClassWithInit__init__ " , [ ` Method { direct_target = " qualifier . ClassWithInit . __init__ " ; class_name = " qualifier . ClassWithInit " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ] ; assert_calls { | class Class : @ classmethod def classmethod ( cls ) : . . . def calls_class_method ( ) : Class . classmethod ( ) } | [ ( function_caller " qualifier . calls_class_method " , [ ` Method { direct_target = " qualifier . Class . classmethod " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ] ; assert_calls { | class Class : def method ( self ) : . . . class Indirect ( Class ) : . . . class Subclass ( Indirect ) : . . . class OverridingSubclass ( Subclass ) : def method ( self ) : . . . def calls_Class_method ( c : Class ) : c . method ( ) def calls_Indirect_method ( i : Indirect ) : i . method ( ) def calls_Subclass_method ( s : Subclass ) : s . method ( ) def calls_OverridingSubclass_method ( o : OverridingSubclass ) : o . method ( ) } | [ ( function_caller " qualifier . calls_Class_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Indirect_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Subclass_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_OverridingSubclass_method " , [ ` Method { direct_target = " qualifier . OverridingSubclass . method " ; class_name = " qualifier . OverridingSubclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Class : @ classmethod def class_method ( cls ) : . . . class Indirect ( Class ) : . . . class Subclass ( Indirect ) : @ classmethod def class_method ( cls ) : . . . def calls_Class_class_method ( ) : Class . class_method ( ) def calls_Indirect_class_method ( ) : Indirect . class_method ( ) def calls_Subclass_class_method ( ) : Subclass . class_method ( ) def calls_Type_Class_class_method ( c : typing . Type [ Class ] ) : c . class_method ( ) def calls_Type_Indirect_class_method ( c : typing . Type [ Indirect ] ) : c . class_method ( ) def calls_Type_Subclass_class_method ( c : typing . Type [ Subclass ] ) : c . class_method ( ) } | [ ( function_caller " qualifier . calls_Class_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Indirect_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Subclass_class_method " , [ ` Method { direct_target = " qualifier . Subclass . class_method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Class_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Indirect_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Subclass_class_method " , [ ` Method { direct_target = " qualifier . Subclass . class_method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Class : def method ( ) : . . . class OtherClass : def method ( ) : . . . def calls_method_on_union ( union : typing . Union [ Class , OtherClass ] ) : union . method ( ) } | [ ( function_caller " qualifier . calls_method_on_union " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ` Method { direct_target = " qualifier . OtherClass . method " ; class_name = " qualifier . OtherClass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : def method ( ) : . . . def call_twice ( foo : Foo ) : foo . method ( ) bar = foo bar . method ( ) } | [ ( function_caller " qualifier . call_twice " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . def call_property ( foo : Foo ) : x = foo . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . class Bar ( Foo ) : pass def call_property ( bar : Bar ) : x = bar . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def x ( self ) -> int : . . . @ x . setter def x ( self , item : int ) -> None : . . . def call_property_setter ( foo : Foo ) -> None : foo . x = 1 } | [ ( function_caller " qualifier . call_property_setter " , [ ` PropertySetter { direct_target = " qualifier . Foo . x " ; class_name = " qualifier . Foo " } ] ) ; ] ; assert_calls { | class Foo : def method ( self ) -> int : . . . class Bar : pass def call_property ( bar : Bar ) : x = bar . method } | [ function_caller " qualifier . call_property " , [ ] ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . class Bar : @ property def method ( self ) -> int : . . . def call_property ( parameter : typing . Union [ Foo , Bar ] ) : x = parameter . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ` Method { direct_target = " qualifier . Bar . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . def call_property ( ) : x = Foo . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | import typing class Foo : def method ( self ) -> int : . . . def calls_optional ( foo : typing . Optional [ Foo ] ) -> None : foo . method ( ) } | [ ( function_caller " qualifier . calls_optional " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | import typing class Foo : def method ( self ) -> int : . . . class Bar ( Foo ) : pass def calls_optional ( bar : typing . Optional [ Bar ] ) -> None : bar . method ( ) } | [ ( function_caller " qualifier . calls_optional " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | from typing import Optional class Foo : @ property def x ( self ) -> int : . . . def optional_property ( foo : typing . Optional [ Foo ] ) -> None : y = foo . x } | [ ( function_caller " qualifier . optional_property " , [ ` Method { direct_target = " qualifier . Foo . x " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | def calls_isinstance ( ) : x = 1 if isinstance ( x , int ) : return 0 return 1 } | [ function_caller " qualifier . calls_isinstance " , [ ` Function " isinstance " ] ] ; assert_calls { | from typing import Generic , TypeVar T = TypeVar ( " T " ) class C ( Generic [ T ] ) : def method ( self ) -> int : . . . class D ( C [ int ] ) : def method ( self ) -> int : . . . def calls_C_str ( c : C [ str ] ) -> None : c . method ( ) } | [ ( function_caller " qualifier . calls_C_str " , [ ` Method { direct_target = " qualifier . C . method " ; class_name = " qualifier . C [ str ] " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | def foo ( ) : . . . def bar ( ) : . . . class C : @ property def p ( self ) -> int : foo ( ) return 0 @ p . setter def p ( self , value : int ) -> None : bar ( ) } | [ function_caller " qualifier . C . p " , [ ` Function " qualifier . foo " ] ; property_setter_caller " qualifier . C . p " , [ ` Function " qualifier . bar " ] ; ] |
let test_unpack_callable_and_self_argument context = let parse ~ global_resolution annotation = parse_single_expression ~ preprocess : true annotation |> GlobalResolution . parse_annotation global_resolution in let assert_unpack_type ( ? source = " " ) ~ signature_select given expected = let global_resolution = let { ScratchProject . BuiltGlobalEnvironment . global_environment ; _ } = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_global_environment in AnnotatedGlobalEnvironment . read_only global_environment |> GlobalResolution . create in let actual = TypeCheck . unpack_callable_and_self_argument ~ signature_select ~ global_resolution ( parse ~ global_resolution given ) in let expected = expected >>| fun ( callable , self_argument ) -> { TypeOperation . callable ; self_argument } in assert_equal ~ printer [ :% show : TypeOperation . callable_and_self_argument option ] ~ cmp [ :% eq : TypeOperation . callable_and_self_argument option ] actual expected in let assert_unpack ( ? source = " " ) given expected = let global_resolution = let { ScratchProject . BuiltGlobalEnvironment . global_environment ; _ } = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_global_environment in AnnotatedGlobalEnvironment . read_only global_environment |> GlobalResolution . create in let expected = expected >>= fun ( expected_string , self_argument ) -> match parse ~ global_resolution expected_string with | Callable callable -> Some ( callable , self_argument ) | _ -> assert false in assert_unpack_type ~ source given expected in let signature_select ( ? pairs = [ ] ) ~ arguments : _ ~ callable ~ self_argument : _ = match pairs with | [ ( Type . Any , right ) ] -> SignatureSelectionTypes . Found { selected_return_annotation = right } | _ -> List . find ~ f ( : fun ( left , _ ) -> [ % eq : Type . t ] left ( Type . Callable callable ) ) pairs >>| ( fun ( _ , right ) -> SignatureSelectionTypes . Found { selected_return_annotation = right } ) |> Option . value ~ default : ( SignatureSelectionTypes . NotFound { closest_return_annotation = Type . Bottom ; reason = None } ) in let default_select ~ arguments : _ ~ callable : _ ~ self_argument : _ = SignatureSelectionTypes . Found { selected_return_annotation = Type . integer } in assert_unpack ~ signature_select : default_select " typing . Callable [ [ int ] , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack_type ~ signature_select : default_select " typing . Any " ( Some ( { kind = Anonymous ; implementation = { annotation = Type . Any ; parameters = Undefined } ; overloads = [ ] ; } , None ) ) ; assert_unpack_type ~ signature_select : default_select " typing . Any " ( Some ( { kind = Anonymous ; implementation = { annotation = Type . Any ; parameters = Undefined } ; overloads = [ ] ; } , None ) ) ; assert_unpack ~ signature_select : default_select " typing . Callable [ [ int ] , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack ~ signature_select : default_select " BoundMethod [ typing . Callable [ [ int ] , bool ] , str ] " ( Some ( " typing . Callable [ [ int ] , bool ] " , Some Type . string ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Generic , TypeVar T = TypeVar ( " T " ) class Foo ( Generic [ T ] ) : def __call__ ( self , x : int ) -> T : . . . } | " BoundMethod [ test . Foo [ str ] , int ] " ( Some ( " typing . Callable [ [ Named ( x , int ) ] , str ] " , Some Type . integer ) ) ; assert_unpack_type ~ signature_select : default_select ~ source : { | class Foo : def __call__ ( self , x : bool ) -> str : . . . class Bar : def __call__ ( self , x : str ) -> int : . . . } | " pyre_extensions . Compose [ test . Foo , test . Bar ] " ( Some ( { Type . Callable . kind = Type . Callable . Named ( Reference . create " test . Foo . __call__ " ) ; implementation = { parameters = Type . Callable . Defined [ Type . Callable . Parameter . Named { name = " $ parameter $ self " ; annotation = Type . Primitive " test . Foo " ; default = false ; } ; Type . Callable . Parameter . Named { name = " $ parameter $ x " ; annotation = Type . bool ; default = false } ; ] ; annotation = Type . integer ; } ; overloads = [ ] ; } , Some ( Type . Primitive " test . Foo " ) ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable class Bar : __call__ : Callable [ [ int ] , int ] = . . . class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , Some Type . integer ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable class Baz : __call__ : Callable [ [ int ] , int ] = . . . class Bar : __call__ : Baz = . . . class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " None ; assert_unpack ~ signature_select : default_select ~ source : { | class Bar : __call__ : int class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " None ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable from pyre_extensions import Compose class Bar2 : __call__ : Compose [ Callable [ [ int ] , int ] , Callable [ [ int ] , int ] ] = . . . class Baz2 : __call__ : Compose [ Callable [ [ int ] , int ] , Callable [ [ int ] , int ] ] = . . . } | " pyre_extensions . Compose [ test . Bar2 , test . Baz2 ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack ~ signature_select : default_select " typing . Tuple [ int , str ] " None ; assert_unpack ~ signature_select : ( signature_select ~ pairs : [ ( Type . Callable . create ~ parameters : ( Type . Callable . Defined [ PositionalOnly { index = 0 ; annotation = Type . integer ; default = false } ] ) ~ annotation : Type . float ( ) , Type . float ) ; ( Type . Callable . create ~ parameters : ( Type . Callable . Defined [ PositionalOnly { index = 0 ; annotation = Type . float ; default = false } ] ) ~ annotation : Type . string ( ) , Type . string ) ; ] ) { | pyre_extensions . Compose [ pyre_extensions . Compose [ typing . Callable [ [ bool ] , int ] , typing . Callable [ [ int ] , float ] ] , typing . Callable [ [ float ] , str ] ] } | ( Some ( " typing . Callable [ [ bool ] , str ] " , None ) ) ; ( ) |
let ( ) = " type " >::: [ " initial " >:: test_initial ; " less_or_equal " >:: test_less_or_equal ; " widen " >:: test_widen ; " check_annotation " >:: test_check_annotation ; " forward_expression " >:: test_forward_expression ; " forward_statement " >:: test_forward_statement ; " forward " >:: test_forward ; " module_exports " >:: test_module_exports ; " object_callables " >:: test_object_callables ; " callable_selection " >:: test_callable_selection ; " calls " >:: test_calls ; " unpack_callable_and_self_argument " >:: test_unpack_callable_and_self_argument ; ] |> Test . run |
type ' a class_info = { cls_id : Ident . t ; cls_id_loc : string loc ; cls_decl : class_declaration ; cls_ty_id : Ident . t ; cls_ty_decl : class_type_declaration ; cls_obj_id : Ident . t ; cls_obj_abbr : type_declaration ; cls_typesharp_id : Ident . t ; cls_abbr : type_declaration ; cls_arity : int ; cls_pub_methods : string list ; cls_info : ' a ; } |
type class_type_info = { clsty_ty_id : Ident . t ; clsty_id_loc : string loc ; clsty_ty_decl : class_type_declaration ; clsty_obj_id : Ident . t ; clsty_obj_abbr : type_declaration ; clsty_typesharp_id : Ident . t ; clsty_abbr : type_declaration ; clsty_info : Typedtree . class_type_declaration ; } |
type ' a full_class = { id : Ident . t ; id_loc : tag loc ; clty : class_declaration ; ty_id : Ident . t ; cltydef : class_type_declaration ; obj_id : Ident . t ; obj_abbr : type_declaration ; cl_id : Ident . t ; cl_abbr : type_declaration ; arity : int ; pub_meths : string list ; coe : Warnings . loc list ; expr : ' a ; req : ' a Typedtree . class_infos ; } |
type error = Unconsistent_constraint of Ctype . Unification_trace . t | Field_type_mismatch of string * string * Ctype . Unification_trace . t | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident . t | Unbound_class_type_2 of Longident . t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Ctype . Unification_trace . t | Virtual_class of bool * bool * string list * string list | Parameter_arity_mismatch of Longident . t * int * int | Parameter_mismatch of Ctype . Unification_trace . t | Bad_parameters of Ident . t * type_expr * type_expr | Class_match_failure of Ctype . class_match_failure list | Unbound_val of string | Unbound_type_var of ( formatter -> unit ) * Ctype . closed_class_failure | Non_generalizable_class of Ident . t * Types . class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident . t * Types . class_declaration * Ctype . Unification_trace . t | Final_self_clash of Ctype . Unification_trace . t | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of type_expr |
let type_open_descr : ( ? used_slot : bool ref -> Env . t -> Parsetree . open_description -> open_description * Env . t ) ref = ref ( fun ? used_slot : _ _ -> assert false ) |
let ctyp desc typ env loc = { ctyp_desc = desc ; ctyp_type = typ ; ctyp_loc = loc ; ctyp_env = env ; ctyp_attributes = [ ] } |
let unbound_class = Path . Pident ( Ident . create_local " * undef " ) * |
let rec scrape_class_type = function Cty_constr ( _ , _ , cty ) -> scrape_class_type cty | cty -> cty |
let rec generalize_class_type gen = function Cty_constr ( _ , params , cty ) -> List . iter gen params ; generalize_class_type gen cty | Cty_signature { csig_self = sty ; csig_vars = vars ; csig_inher = inher } -> gen sty ; Vars . iter ( fun _ ( _ , _ , ty ) -> gen ty ) vars ; List . iter ( fun ( _ , tl ) -> List . iter gen tl ) inher | Cty_arrow ( _ , ty , cty ) -> gen ty ; generalize_class_type gen cty |
let generalize_class_type vars = let gen = if vars then Ctype . generalize else Ctype . generalize_structure in generalize_class_type gen |
let virtual_methods sign = let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . Types . csig_self ) in List . fold_left ( fun virt ( lab , _ , _ ) -> if lab = dummy_method then virt else if Concr . mem lab sign . csig_concr then virt else lab :: virt ) [ ] fields |
let rec constructor_type constr cty = match cty with Cty_constr ( _ , _ , cty ) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow ( l , ty , cty ) -> Ctype . newty ( Tarrow ( l , ty , constructor_type constr cty , Cok ) ) |
let rec class_body cty = match cty with Cty_constr _ -> cty | Cty_signature _ -> cty | Cty_arrow ( _ , _ , cty ) -> class_body cty |
let extract_constraints cty = let sign = Ctype . signature_of_class_type cty in ( Vars . fold ( fun lab _ vars -> lab :: vars ) sign . csig_vars [ ] , begin let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . csig_self ) in List . fold_left ( fun meths ( lab , _ , _ ) -> if lab = dummy_method then meths else lab :: meths ) [ ] fields end , sign . csig_concr ) |
let rec abbreviate_class_type path params cty = match cty with Cty_constr ( _ , _ , _ ) | Cty_signature _ -> Cty_constr ( path , params , cty ) | Cty_arrow ( l , ty , cty ) -> Cty_arrow ( l , ty , abbreviate_class_type path params cty ) |
let rec closed_class_type = function Cty_constr ( _ , params , _ ) -> List . for_all ( Ctype . closed_schema Env . empty ) params | Cty_signature sign -> Ctype . closed_schema Env . empty sign . csig_self && Vars . fold ( fun _ ( _ , _ , ty ) cc -> Ctype . closed_schema Env . empty ty && cc ) sign . csig_vars true | Cty_arrow ( _ , ty , cty ) -> Ctype . closed_schema Env . empty ty && closed_class_type cty |
let closed_class cty = List . for_all ( Ctype . closed_schema Env . empty ) cty . cty_params && closed_class_type cty . cty_type |
let rec limited_generalize rv = function Cty_constr ( _path , params , cty ) -> List . iter ( Ctype . limited_generalize rv ) params ; limited_generalize rv cty | Cty_signature sign -> Ctype . limited_generalize rv sign . csig_self ; Vars . iter ( fun _ ( _ , _ , ty ) -> Ctype . limited_generalize rv ty ) sign . csig_vars ; List . iter ( fun ( _ , tl ) -> List . iter ( Ctype . limited_generalize rv ) tl ) sign . csig_inher | Cty_arrow ( _ , ty , cty ) -> Ctype . limited_generalize rv ty ; limited_generalize rv cty |
let rc node = Cmt_format . add_saved_type ( Cmt_format . Partial_class_expr node ) ; Stypes . record ( Stypes . Ti_class node ) ; node |
let enter_met_env ? check loc lab kind unbound_kind ty val_env met_env par_env = let val_env = Env . enter_unbound_value lab unbound_kind val_env in let par_env = Env . enter_unbound_value lab unbound_kind par_env in let ( id , met_env ) = Env . enter_value ? check lab { val_type = ty ; val_kind = kind ; val_attributes = [ ] ; Types . val_loc = loc } met_env in ( id , val_env , met_env , par_env ) |
let enter_val cl_num vars inh lab mut virt ty val_env met_env par_env loc = let ( id , virt ) = try let ( id , mut ' , virt ' , ty ' ) = Vars . find lab ! vars in if mut ' <> mut then raise ( Error ( loc , val_env , Mutability_mismatch ( lab , mut ) ) ) ; Ctype . unify val_env ( Ctype . instance ty ) ( Ctype . instance ty ' ) ; ( if not inh then Some id else None ) , ( if virt ' = Concrete then virt ' else virt ) with Ctype . Unify tr -> raise ( Error ( loc , val_env , Field_type_mismatch ( " instance variable " , lab , tr ) ) ) | Not_found -> None , virt in let ( id , _ , _ , _ ) as result = match id with Some id -> ( id , val_env , met_env , par_env ) | None -> enter_met_env Location . none lab ( Val_ivar ( mut , cl_num ) ) Val_unbound_instance_variable ty val_env met_env par_env in vars := Vars . add lab ( id , mut , virt , ty ) ! vars ; result |
let concr_vals vars = Vars . fold ( fun id ( _ , vf , _ ) s -> if vf = Virtual then s else Concr . add id s ) vars Concr . empty |
let inheritance self_type env ovf concr_meths warn_vals loc parent = match scrape_class_type parent with Cty_signature cl_sig -> begin try Ctype . unify env self_type cl_sig . csig_self with Ctype . Unify trace -> let open Ctype . Unification_trace in match trace with | Diff _ :: Incompatible_fields { name = n ; _ } :: rem -> raise ( Error ( loc , env , Field_type_mismatch ( " method " , n , rem ) ) ) | _ -> assert false end ; let over_meths = Concr . inter cl_sig . csig_concr concr_meths in let concr_vals = concr_vals cl_sig . csig_vars in let over_vals = Concr . inter concr_vals warn_vals in begin match ovf with Some Fresh -> let cname = match parent with Cty_constr ( p , _ , _ ) -> Path . name p | _ -> " inherited " in if not ( Concr . is_empty over_meths ) then Location . prerr_warning loc ( Warnings . Method_override ( cname :: Concr . elements over_meths ) ) ; if not ( Concr . is_empty over_vals ) then Location . prerr_warning loc ( Warnings . Instance_variable_override ( cname :: Concr . elements over_vals ) ) ; | Some Override when Concr . is_empty over_meths && Concr . is_empty over_vals -> raise ( Error ( loc , env , No_overriding ( " " , " " ) ) ) | _ -> ( ) end ; let concr_meths = Concr . union cl_sig . csig_concr concr_meths and warn_vals = Concr . union concr_vals warn_vals in ( cl_sig , concr_meths , warn_vals ) | _ -> raise ( Error ( loc , env , Structure_expected parent ) ) |
let virtual_method val_env meths self_type lab priv sty loc = let ( _ , ty ' ) = Ctype . filter_self_method val_env lab priv meths self_type in let sty = Ast_helper . Typ . force_poly sty in let cty = transl_simple_type val_env false sty in let ty = cty . ctyp_type in begin try Ctype . unify val_env ty ty ' with Ctype . Unify trace -> raise ( Error ( loc , val_env , Field_type_mismatch ( " method " , lab , trace ) ) ) ; end ; cty |
let delayed_meth_specs = ref [ ] |
let declare_method val_env meths self_type lab priv sty loc = let ( _ , ty ' ) = Ctype . filter_self_method val_env lab priv meths self_type in let unif ty = try Ctype . unify val_env ty ty ' with Ctype . Unify trace -> raise ( Error ( loc , val_env , Field_type_mismatch ( " method " , lab , trace ) ) ) in let sty = Ast_helper . Typ . force_poly sty in match sty . ptyp_desc , priv with Ptyp_poly ( [ ] , sty ' ) , Public -> let returned_cty = ctyp Ttyp_any ( Ctype . newty Tnil ) val_env loc in delayed_meth_specs := Warnings . mk_lazy ( fun ( ) -> let cty = transl_simple_type_univars val_env sty ' in let ty = cty . ctyp_type in unif ty ; returned_cty . ctyp_desc <- Ttyp_poly ( [ ] , cty ) ; returned_cty . ctyp_type <- ty ; ) :: ! delayed_meth_specs ; returned_cty | _ -> let cty = transl_simple_type val_env false sty in let ty = cty . ctyp_type in unif ty ; cty |
let type_constraint val_env sty sty ' loc = let cty = transl_simple_type val_env false sty in let ty = cty . ctyp_type in let cty ' = transl_simple_type val_env false sty ' in let ty ' = cty ' . ctyp_type in begin try Ctype . unify val_env ty ty ' with Ctype . Unify trace -> raise ( Error ( loc , val_env , Unconsistent_constraint trace ) ) ; end ; ( cty , cty ' ) |
let make_method loc cl_num expr = let open Ast_helper in let mkid s = mkloc s loc in Exp . fun_ ~ loc : expr . pexp_loc Nolabel None ( Pat . alias ~ loc ( Pat . var ~ loc ( mkid " self " ) ) -* ( mkid ( " self " - ^ cl_num ) ) ) expr |
let add_val lab ( mut , virt , ty ) val_sig = let virt = try let ( _mut ' , virt ' , _ty ' ) = Vars . find lab val_sig in if virt ' = Concrete then virt ' else virt with Not_found -> virt in Vars . add lab ( mut , virt , ty ) val_sig |
let rec class_type_field env self_type meths arg ctf = Builtin_attributes . warning_scope ctf . pctf_attributes ( fun ( ) -> class_type_field_aux env self_type meths arg ctf ) ( fields , val_sig , concr_meths , inher ) ctf = let loc = ctf . pctf_loc in let mkctf desc = { ctf_desc = desc ; ctf_loc = loc ; ctf_attributes = ctf . pctf_attributes } in match ctf . pctf_desc with Pctf_inherit sparent -> let parent = class_type env sparent in let inher = match parent . cltyp_type with Cty_constr ( p , tl , _ ) -> ( p , tl ) :: inher | _ -> inher in let ( cl_sig , concr_meths , _ ) = inheritance self_type env None concr_meths Concr . empty sparent . pcty_loc parent . cltyp_type in let val_sig = Vars . fold add_val cl_sig . csig_vars val_sig in ( mkctf ( Tctf_inherit parent ) :: fields , val_sig , concr_meths , inher ) | Pctf_val ( { txt = lab } , mut , virt , sty ) -> let cty = transl_simple_type env false sty in let ty = cty . ctyp_type in ( mkctf ( Tctf_val ( lab , mut , virt , cty ) ) :: fields , add_val lab ( mut , virt , ty ) val_sig , concr_meths , inher ) | Pctf_method ( { txt = lab } , priv , virt , sty ) -> let cty = declare_method env meths self_type lab priv sty ctf . pctf_loc in let concr_meths = match virt with | Concrete -> Concr . add lab concr_meths | Virtual -> concr_meths in ( mkctf ( Tctf_method ( lab , priv , virt , cty ) ) :: fields , val_sig , concr_meths , inher ) | Pctf_constraint ( sty , sty ' ) -> let ( cty , cty ' ) = type_constraint env sty sty ' ctf . pctf_loc in ( mkctf ( Tctf_constraint ( cty , cty ' ) ) :: fields , val_sig , concr_meths , inher ) | Pctf_attribute x -> Builtin_attributes . warning_attribute x ; ( mkctf ( Tctf_attribute x ) :: fields , val_sig , concr_meths , inher ) | Pctf_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) let meths = ref Meths . empty in let self_cty = transl_simple_type env false sty in let self_cty = { self_cty with ctyp_type = Ctype . expand_head env self_cty . ctyp_type } in let self_type = self_cty . ctyp_type in let dummy_obj = Ctype . newvar ( ) in Ctype . unify env ( Ctype . filter_method env dummy_method Private dummy_obj ) ( Ctype . newty ( Ttuple [ ] ) ) ; begin try Ctype . unify env self_type dummy_obj with Ctype . Unify _ -> raise ( Error ( sty . ptyp_loc , env , Pattern_type_clash self_type ) ) end ; let ( rev_fields , val_sig , concr_meths , inher ) = Builtin_attributes . warning_scope [ ] ( fun ( ) -> List . fold_left ( class_type_field env self_type meths ) ( [ ] , Vars . empty , Concr . empty , [ ] ) sign ) in let cty = { csig_self = self_type ; csig_vars = val_sig ; csig_concr = concr_meths ; csig_inher = inher } in { csig_self = self_cty ; csig_fields = List . rev rev_fields ; csig_type = cty ; } Builtin_attributes . warning_scope scty . pcty_attributes ( fun ( ) -> class_type_aux env scty ) let cltyp desc typ = { cltyp_desc = desc ; cltyp_type = typ ; cltyp_loc = scty . pcty_loc ; cltyp_env = env ; cltyp_attributes = scty . pcty_attributes ; } in match scty . pcty_desc with Pcty_constr ( lid , styl ) -> let ( path , decl ) = Env . lookup_cltype ~ loc : scty . pcty_loc lid . txt env in if Path . same decl . clty_path unbound_class then raise ( Error ( scty . pcty_loc , env , Unbound_class_type_2 lid . txt ) ) ; let ( params , clty ) = Ctype . instance_class decl . clty_params decl . clty_type in if List . length params <> List . length styl then raise ( Error ( scty . pcty_loc , env , Parameter_arity_mismatch ( lid . txt , List . length params , List . length styl ) ) ) ; let ctys = List . map2 ( fun sty ty -> let cty ' = transl_simple_type env false sty in let ty ' = cty ' . ctyp_type in begin try Ctype . unify env ty ' ty with Ctype . Unify trace -> raise ( Error ( sty . ptyp_loc , env , Parameter_mismatch trace ) ) end ; cty ' ) styl params in let typ = Cty_constr ( path , params , clty ) in cltyp ( Tcty_constr ( path , lid , ctys ) ) typ | Pcty_signature pcsig -> let clsig = class_signature env pcsig in let typ = Cty_signature clsig . csig_type in cltyp ( Tcty_signature clsig ) typ | Pcty_arrow ( l , sty , scty ) -> let cty = transl_simple_type env false sty in let ty = cty . ctyp_type in let ty = if Btype . is_optional l then Ctype . newty ( Tconstr ( Predef . path_option , [ ty ] , ref Mnil ) ) else ty in let clty = class_type env scty in let typ = Cty_arrow ( l , ty , clty . cltyp_type ) in cltyp ( Tcty_arrow ( l , cty , clty ) ) typ | Pcty_open ( od , e ) -> let ( od , newenv ) = ! type_open_descr env od in let clty = class_type newenv e in cltyp ( Tcty_open ( od , clty ) ) clty . cltyp_type | Pcty_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) |
let class_type env scty = delayed_meth_specs := [ ] ; let cty = class_type env scty in List . iter Lazy . force ( List . rev ! delayed_meth_specs ) ; delayed_meth_specs := [ ] ; cty |
let rec class_field self_loc cl_num self_type meths vars arg cf = Builtin_attributes . warning_scope cf . pcf_attributes ( fun ( ) -> class_field_aux self_loc cl_num self_type meths vars arg cf ) ( val_env , met_env , par_env , fields , concr_meths , warn_vals , inher , local_meths , local_vals ) cf = let loc = cf . pcf_loc in let mkcf desc = { cf_desc = desc ; cf_loc = loc ; cf_attributes = cf . pcf_attributes } in match cf . pcf_desc with Pcf_inherit ( ovf , sparent , super ) -> let parent = class_expr cl_num val_env par_env sparent in let inher = match parent . cl_type with Cty_constr ( p , tl , _ ) -> ( p , tl ) :: inher | _ -> inher in let ( cl_sig , concr_meths , warn_vals ) = inheritance self_type val_env ( Some ovf ) concr_meths warn_vals sparent . pcl_loc parent . cl_type in let ( val_env , met_env , par_env , inh_vars ) = Vars . fold ( fun lab info ( val_env , met_env , par_env , inh_vars ) -> let mut , vr , ty = info in let ( id , val_env , met_env , par_env ) = enter_val cl_num vars true lab mut vr ty val_env met_env par_env sparent . pcl_loc in ( val_env , met_env , par_env , ( lab , id ) :: inh_vars ) ) cl_sig . csig_vars ( val_env , met_env , par_env , [ ] ) in let inh_meths = Concr . fold ( fun lab rem -> ( lab , Ident . create_local lab ) :: rem ) cl_sig . csig_concr [ ] in let ( val_env , met_env , par_env , super ) = match super with None -> ( val_env , met_env , par_env , None ) | Some { txt = name } -> let ( _id , val_env , met_env , par_env ) = enter_met_env ~ check ( : fun s -> Warnings . Unused_ancestor s ) sparent . pcl_loc name ( Val_anc ( inh_meths , cl_num ) ) Val_unbound_ancestor self_type val_env met_env par_env in ( val_env , met_env , par_env , Some name ) in ( val_env , met_env , par_env , lazy ( mkcf ( Tcf_inherit ( ovf , parent , super , inh_vars , inh_meths ) ) ) :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_val ( lab , mut , Cfk_virtual styp ) -> if ! Clflags . principal then Ctype . begin_def ( ) ; let cty = Typetexp . transl_simple_type val_env false styp in let ty = cty . ctyp_type in if ! Clflags . principal then begin Ctype . end_def ( ) ; Ctype . generalize_structure ty end ; let ( id , val_env , met_env ' , par_env ) = enter_val cl_num vars false lab . txt mut Virtual ty val_env met_env par_env loc in ( val_env , met_env ' , par_env , lazy ( mkcf ( Tcf_val ( lab , mut , id , Tcfk_virtual cty , met_env == met_env ' ) ) ) :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_val ( lab , mut , Cfk_concrete ( ovf , sexp ) ) -> if Concr . mem lab . txt local_vals then raise ( Error ( loc , val_env , Duplicate ( " instance variable " , lab . txt ) ) ) ; if Concr . mem lab . txt warn_vals then begin if ovf = Fresh then Location . prerr_warning lab . loc ( Warnings . Instance_variable_override [ lab . txt ] ) end else begin if ovf = Override then raise ( Error ( loc , val_env , No_overriding ( " instance variable " , lab . txt ) ) ) end ; if ! Clflags . principal then Ctype . begin_def ( ) ; let exp = type_exp val_env sexp in if ! Clflags . principal then begin Ctype . end_def ( ) ; Ctype . generalize_structure exp . exp_type end ; let ( id , val_env , met_env ' , par_env ) = enter_val cl_num vars false lab . txt mut Concrete exp . exp_type val_env met_env par_env loc in ( val_env , met_env ' , par_env , lazy ( mkcf ( Tcf_val ( lab , mut , id , Tcfk_concrete ( ovf , exp ) , met_env == met_env ' ) ) ) :: fields , concr_meths , Concr . add lab . txt warn_vals , inher , local_meths , Concr . add lab . txt local_vals ) | Pcf_method ( lab , priv , Cfk_virtual sty ) -> let cty = virtual_method val_env meths self_type lab . txt priv sty loc in ( val_env , met_env , par_env , lazy ( mkcf ( Tcf_method ( lab , priv , Tcfk_virtual cty ) ) ) :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_method ( lab , priv , Cfk_concrete ( ovf , expr ) ) -> let expr = match expr . pexp_desc with | Pexp_poly _ -> expr | _ -> Ast_helper . Exp . poly ~ loc : expr . pexp_loc expr None in if Concr . mem lab . txt local_meths then raise ( Error ( loc , val_env , Duplicate ( " method " , lab . txt ) ) ) ; if Concr . mem lab . txt concr_meths then begin if ovf = Fresh then Location . prerr_warning loc ( Warnings . Method_override [ lab . txt ] ) end else begin if ovf = Override then raise ( Error ( loc , val_env , No_overriding ( " method " , lab . txt ) ) ) end ; let ( _ , ty ) = Ctype . filter_self_method val_env lab . txt priv meths self_type in begin try match expr . pexp_desc with Pexp_poly ( sbody , sty ) -> begin match sty with None -> ( ) | Some sty -> let sty = Ast_helper . Typ . force_poly sty in let cty ' = Typetexp . transl_simple_type val_env false sty in let ty ' = cty ' . ctyp_type in Ctype . unify val_env ty ' ty end ; begin match ( Ctype . repr ty ) . desc with Tvar _ -> let ty ' = Ctype . newvar ( ) in Ctype . unify val_env ( Ctype . newty ( Tpoly ( ty ' , [ ] ) ) ) ty ; Ctype . unify val_env ( type_approx val_env sbody ) ty ' | Tpoly ( ty1 , tl ) -> let _ , ty1 ' = Ctype . instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype . unify val_env ty2 ty1 ' | _ -> assert false end | _ -> assert false with Ctype . Unify trace -> raise ( Error ( loc , val_env , Field_type_mismatch ( " method " , lab . txt , trace ) ) ) end ; let meth_expr = make_method self_loc cl_num expr in let vars_local = ! vars in let field = Warnings . mk_lazy ( fun ( ) -> let ( _ , ty ) = Meths . find lab . txt ! meths in let meth_type = mk_expected ( Btype . newgenty ( Tarrow ( Nolabel , self_type , ty , Cok ) ) ) in Ctype . raise_nongen_level ( ) ; vars := vars_local ; let texp = type_expect met_env meth_expr meth_type in Ctype . end_def ( ) ; mkcf ( Tcf_method ( lab , priv , Tcfk_concrete ( ovf , texp ) ) ) ) in ( val_env , met_env , par_env , field :: fields , Concr . add lab . txt concr_meths , warn_vals , inher , Concr . add lab . txt local_meths , local_vals ) | Pcf_constraint ( sty , sty ' ) -> let ( cty , cty ' ) = type_constraint val_env sty sty ' loc in ( val_env , met_env , par_env , lazy ( mkcf ( Tcf_constraint ( cty , cty ' ) ) ) :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_initializer expr -> let expr = make_method self_loc cl_num expr in let vars_local = ! vars in let field = lazy begin Ctype . raise_nongen_level ( ) ; let meth_type = mk_expected ( Ctype . newty ( Tarrow ( Nolabel , self_type , Ctype . instance Predef . type_unit , Cok ) ) ) in vars := vars_local ; let texp = type_expect met_env expr meth_type in Ctype . end_def ( ) ; mkcf ( Tcf_initializer texp ) end in ( val_env , met_env , par_env , field :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_attribute x -> Builtin_attributes . warning_attribute x ; ( val_env , met_env , par_env , lazy ( mkcf ( Tcf_attribute x ) ) :: fields , concr_meths , warn_vals , inher , local_meths , local_vals ) | Pcf_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) { pcstr_self = spat ; pcstr_fields = str } = let par_env = met_env in let self_loc = { spat . ppat_loc with Location . loc_ghost = true } in let self_type = Ctype . newobj ( Ctype . newvar ( ) ) in if not final then Ctype . unify val_env ( Ctype . filter_method val_env dummy_method Private self_type ) ( Ctype . newty ( Ttuple [ ] ) ) ; let private_self = if final then Ctype . newvar ( ) else self_type in let ( pat , meths , vars , val_env , meth_env , par_env ) = type_self_pattern cl_num private_self val_env met_env par_env spat in let public_self = pat . pat_type in let ty = if final then Ctype . newobj ( Ctype . newvar ( ) ) else self_type in begin try Ctype . unify val_env public_self ty with Ctype . Unify _ -> raise ( Error ( spat . ppat_loc , val_env , Pattern_type_clash public_self ) ) end ; let get_methods ty = ( fst ( Ctype . flatten_fields ( Ctype . object_fields ( Ctype . expand_head val_env ty ) ) ) ) in if final then begin List . iter ( fun ( lab , kind , ty ) -> let k = if Btype . field_kind_repr kind = Fpresent then Public else Private in try Ctype . unify val_env ty ( Ctype . filter_method val_env lab k self_type ) with _ -> assert false ) ( get_methods public_self ) end ; let ( _ , _ , _ , fields , concr_meths , _ , inher , _local_meths , _local_vals ) = Builtin_attributes . warning_scope [ ] ( fun ( ) -> List . fold_left ( class_field self_loc cl_num self_type meths vars ) ( val_env , meth_env , par_env , [ ] , Concr . empty , Concr . empty , [ ] , Concr . empty , Concr . empty ) str ) in Ctype . unify val_env self_type ( Ctype . newvar ( ) ) ; let sign = { csig_self = public_self ; csig_vars = Vars . map ( fun ( _id , mut , vr , ty ) -> ( mut , vr , ty ) ) ! vars ; csig_concr = concr_meths ; csig_inher = inher } in let methods = get_methods self_type in let priv_meths = List . filter ( fun ( _ , kind , _ ) -> Btype . field_kind_repr kind <> Fpresent ) methods in List . iter ( fun ( met , _kind , _ty ) -> if Meths . mem met ! meths then ( ) else ignore ( Ctype . filter_self_method val_env met Private meths self_type ) ) methods ; if final then begin if not ( Ctype . close_object self_type ) then raise ( Error ( loc , val_env , Closing_self_type self_type ) ) ; let mets = virtual_methods { sign with csig_self = self_type } in let vals = Vars . fold ( fun name ( _mut , vr , _ty ) l -> if vr = Virtual then name :: l else l ) sign . csig_vars [ ] in if mets <> [ ] || vals <> [ ] then raise ( Error ( loc , val_env , Virtual_class ( true , final , mets , vals ) ) ) ; let self_methods = List . fold_right ( fun ( lab , kind , ty ) rem -> Ctype . newty ( Tfield ( lab , Btype . copy_kind kind , ty , rem ) ) ) methods ( Ctype . newty Tnil ) in begin try Ctype . unify val_env private_self ( Ctype . newty ( Tobject ( self_methods , ref None ) ) ) ; Ctype . unify val_env public_self self_type with Ctype . Unify trace -> raise ( Error ( loc , val_env , Final_self_clash trace ) ) end ; end ; begin let ms = ! meths in Meths . iter ( fun _ ( _ , ty ) -> Ctype . generalize_spine ty ) ms ; meths := Meths . map ( fun ( id , ty ) -> ( id , Ctype . generic_instance ty ) ) ms ; Meths . iter ( fun _ ( _ , ty ) -> Ctype . unify val_env ty ( Ctype . newvar ( ) ) ) ms end ; let fields = List . map Lazy . force ( List . rev fields ) in let meths = Meths . map ( function ( id , _ty ) -> id ) ! meths in let pub_meths ' = List . filter ( fun ( _ , kind , _ ) -> Btype . field_kind_repr kind = Fpresent ) ( get_methods public_self ) in let names = List . map ( fun ( x , _ , _ ) -> x ) in let l1 = names priv_meths and l2 = names pub_meths ' in let added = List . filter ( fun x -> List . mem x l1 ) l2 in if added <> [ ] then Location . prerr_warning loc ( Warnings . Implicit_public_methods added ) ; let sign = if final then sign else { sign with Types . csig_self = Ctype . expand_head val_env public_self } in { cstr_self = pat ; cstr_fields = fields ; cstr_type = sign ; cstr_meths = meths } , sign Builtin_attributes . warning_scope scl . pcl_attributes ( fun ( ) -> class_expr_aux cl_num val_env met_env scl ) match scl . pcl_desc with Pcl_constr ( lid , styl ) -> let ( path , decl ) = Env . lookup_class ~ loc : scl . pcl_loc lid . txt val_env in if Path . same decl . cty_path unbound_class then raise ( Error ( scl . pcl_loc , val_env , Unbound_class_2 lid . txt ) ) ; let tyl = List . map ( fun sty -> transl_simple_type val_env false sty ) styl in let ( params , clty ) = Ctype . instance_class decl . cty_params decl . cty_type in let clty ' = abbreviate_class_type path params clty in if List . length params <> List . length tyl then raise ( Error ( scl . pcl_loc , val_env , Parameter_arity_mismatch ( lid . txt , List . length params , List . length tyl ) ) ) ; List . iter2 ( fun cty ' ty -> let ty ' = cty ' . ctyp_type in try Ctype . unify val_env ty ' ty with Ctype . Unify trace -> raise ( Error ( cty ' . ctyp_loc , val_env , Parameter_mismatch trace ) ) ) tyl params ; let cl = rc { cl_desc = Tcl_ident ( path , lid , tyl ) ; cl_loc = scl . pcl_loc ; cl_type = clty ' ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } in let ( vals , meths , concrs ) = extract_constraints clty in rc { cl_desc = Tcl_constraint ( cl , None , vals , meths , concrs ) ; cl_loc = scl . pcl_loc ; cl_type = clty ' ; cl_env = val_env ; cl_attributes = [ ] ; } | Pcl_structure cl_str -> let ( desc , ty ) = class_structure cl_num false val_env met_env scl . pcl_loc cl_str in rc { cl_desc = Tcl_structure desc ; cl_loc = scl . pcl_loc ; cl_type = Cty_signature ty ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_fun ( l , Some default , spat , sbody ) -> let loc = default . pexp_loc in let open Ast_helper in let scases = [ Exp . case ( Pat . construct ~ loc ( mknoloc ( Longident . ( Ldot ( Lident " * predef " , * " Some " ) ) ) ) ( Some ( Pat . var ~ loc ( mknoloc " * sth " ) ) ) ) * ( Exp . ident ~ loc ( mknoloc ( Longident . Lident " * sth " ) ) ) ; * Exp . case ( Pat . construct ~ loc ( mknoloc ( Longident . ( Ldot ( Lident " * predef " , * " None " ) ) ) ) None ) default ; ] in let smatch = Exp . match_ ~ loc ( Exp . ident ~ loc ( mknoloc ( Longident . Lident " * opt " ) ) ) * scases in let sfun = Cl . fun_ ~ loc : scl . pcl_loc l None ( Pat . var ~ loc ( mknoloc " * opt " ) ) * ( Cl . let_ ~ loc : scl . pcl_loc Nonrecursive [ Vb . mk spat smatch ] sbody ) in class_expr cl_num val_env met_env sfun | Pcl_fun ( l , None , spat , scl ' ) -> if ! Clflags . principal then Ctype . begin_def ( ) ; let ( pat , pv , val_env ' , met_env ) = Typecore . type_class_arg_pattern cl_num val_env met_env l spat in if ! Clflags . principal then begin Ctype . end_def ( ) ; iter_pattern ( fun { pat_type = ty } -> Ctype . generalize_structure ty ) pat end ; let pv = List . map begin fun ( id , id ' , _ty ) -> let path = Pident id ' in let vd = Env . find_value path val_env ' in ( id , { exp_desc = Texp_ident ( path , mknoloc ( Longident . Lident ( Ident . name id ) ) , vd ) ; exp_loc = Location . none ; exp_extra = [ ] ; exp_type = Ctype . instance vd . val_type ; exp_attributes = [ ] ; exp_env = val_env ' } ) end pv in let not_function = function Cty_arrow _ -> false | _ -> true in let partial = let dummy = type_exp val_env ( Ast_helper . Exp . unreachable ( ) ) in Typecore . check_partial val_env pat . pat_type pat . pat_loc [ { c_lhs = pat ; c_guard = None ; c_rhs = dummy } ] in Ctype . raise_nongen_level ( ) ; let cl = class_expr cl_num val_env ' met_env scl ' in Ctype . end_def ( ) ; if Btype . is_optional l && not_function cl . cl_type then Location . prerr_warning pat . pat_loc Warnings . Unerasable_optional_argument ; rc { cl_desc = Tcl_fun ( l , pat , pv , cl , partial ) ; cl_loc = scl . pcl_loc ; cl_type = Cty_arrow ( l , Ctype . instance pat . pat_type , cl . cl_type ) ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_apply ( scl ' , sargs ) -> assert ( sargs <> [ ] ) ; if ! Clflags . principal then Ctype . begin_def ( ) ; let cl = class_expr cl_num val_env met_env scl ' in if ! Clflags . principal then begin Ctype . end_def ( ) ; generalize_class_type false cl . cl_type ; end ; let rec nonopt_labels ls ty_fun = match ty_fun with | Cty_arrow ( l , _ , ty_res ) -> if Btype . is_optional l then nonopt_labels ls ty_res else nonopt_labels ( l :: ls ) ty_res | _ -> ls in let ignore_labels = ! Clflags . classic || let labels = nonopt_labels [ ] cl . cl_type in List . length labels = List . length sargs && List . for_all ( fun ( l , _ ) -> l = Nolabel ) sargs && List . exists ( fun l -> l <> Nolabel ) labels && begin Location . prerr_warning cl . cl_loc ( Warnings . Labels_omitted ( List . map Printtyp . string_of_label ( List . filter ( ( ) <> Nolabel ) labels ) ) ) ; true end in let rec type_args args omitted ty_fun ty_fun0 sargs more_sargs = match ty_fun , ty_fun0 with | Cty_arrow ( l , ty , ty_fun ) , Cty_arrow ( _ , ty0 , ty_fun0 ) when sargs <> [ ] || more_sargs <> [ ] -> let name = Btype . label_name l and optional = Btype . is_optional l in let sargs , more_sargs , arg = if ignore_labels && not ( Btype . is_optional l ) then begin match sargs , more_sargs with ( l ' , sarg0 ) :: _ , _ -> raise ( Error ( sarg0 . pexp_loc , val_env , Apply_wrong_label l ' ) ) | _ , ( l ' , sarg0 ) :: more_sargs -> if l <> l ' && l ' <> Nolabel then raise ( Error ( sarg0 . pexp_loc , val_env , Apply_wrong_label l ' ) ) else ( [ ] , more_sargs , Some ( type_argument val_env sarg0 ty ty0 ) ) | _ -> assert false end else try let ( l ' , sarg0 , sargs , more_sargs ) = try let ( l ' , sarg0 , sargs1 , sargs2 ) = Btype . extract_label name sargs in ( l ' , sarg0 , sargs1 @ sargs2 , more_sargs ) with Not_found -> let ( l ' , sarg0 , sargs1 , sargs2 ) = Btype . extract_label name more_sargs in ( l ' , sarg0 , sargs @ sargs1 , sargs2 ) in if not optional && Btype . is_optional l ' then Location . prerr_warning sarg0 . pexp_loc ( Warnings . Nonoptional_label ( Printtyp . string_of_label l ) ) ; sargs , more_sargs , if not optional || Btype . is_optional l ' then Some ( type_argument val_env sarg0 ty ty0 ) else let ty ' = extract_option_type val_env ty and ty0 ' = extract_option_type val_env ty0 in let arg = type_argument val_env sarg0 ty ' ty0 ' in Some ( option_some val_env arg ) with Not_found -> sargs , more_sargs , if Btype . is_optional l && ( List . mem_assoc Nolabel sargs || List . mem_assoc Nolabel more_sargs ) then Some ( option_none val_env ty0 Location . none ) else None in let omitted = if arg = None then ( l , ty0 ) :: omitted else omitted in type_args ( ( l , arg ) :: args ) omitted ty_fun ty_fun0 sargs more_sargs | _ -> match sargs @ more_sargs with ( l , sarg0 ) :: _ -> if omitted <> [ ] then raise ( Error ( sarg0 . pexp_loc , val_env , Apply_wrong_label l ) ) else raise ( Error ( cl . cl_loc , val_env , Cannot_apply cl . cl_type ) ) | [ ] -> ( List . rev args , List . fold_left ( fun ty_fun ( l , ty ) -> Cty_arrow ( l , ty , ty_fun ) ) ty_fun0 omitted ) in let ( args , cty ) = let ( _ , ty_fun0 ) = Ctype . instance_class [ ] cl . cl_type in if ignore_labels then type_args [ ] [ ] cl . cl_type ty_fun0 [ ] sargs else type_args [ ] [ ] cl . cl_type ty_fun0 sargs [ ] in rc { cl_desc = Tcl_apply ( cl , args ) ; cl_loc = scl . pcl_loc ; cl_type = cty ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_let ( rec_flag , sdefs , scl ' ) -> let ( defs , val_env ) = Typecore . type_let In_class_def val_env rec_flag sdefs None in let ( vals , met_env ) = List . fold_right ( fun ( id , _id_loc , _typ ) ( vals , met_env ) -> let path = Pident id in let vd = Env . find_value path val_env in Ctype . begin_def ( ) ; let expr = { exp_desc = Texp_ident ( path , mknoloc ( Longident . Lident ( Ident . name id ) ) , vd ) ; exp_loc = Location . none ; exp_extra = [ ] ; exp_type = Ctype . instance vd . val_type ; exp_attributes = [ ] ; exp_env = val_env ; } in Ctype . end_def ( ) ; Ctype . generalize expr . exp_type ; let desc = { val_type = expr . exp_type ; val_kind = Val_ivar ( Immutable , cl_num ) ; val_attributes = [ ] ; Types . val_loc = vd . Types . val_loc ; } in let id ' = Ident . create_local ( Ident . name id ) in ( ( id ' , expr ) :: vals , Env . add_value id ' desc met_env ) ) ( let_bound_idents_full defs ) ( [ ] , met_env ) in let cl = class_expr cl_num val_env met_env scl ' in let ( ) = if rec_flag = Recursive then check_recursive_bindings val_env defs in rc { cl_desc = Tcl_let ( rec_flag , defs , vals , cl ) ; cl_loc = scl . pcl_loc ; cl_type = cl . cl_type ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_constraint ( scl ' , scty ) -> Ctype . begin_class_def ( ) ; let context = Typetexp . narrow ( ) in let cl = class_expr cl_num val_env met_env scl ' in Typetexp . widen context ; let context = Typetexp . narrow ( ) in let clty = class_type val_env scty in Typetexp . widen context ; Ctype . end_def ( ) ; limited_generalize ( Ctype . row_variable ( Ctype . self_type cl . cl_type ) ) cl . cl_type ; limited_generalize ( Ctype . row_variable ( Ctype . self_type clty . cltyp_type ) ) clty . cltyp_type ; begin match Includeclass . class_types val_env cl . cl_type clty . cltyp_type with [ ] -> ( ) | error -> raise ( Error ( cl . cl_loc , val_env , Class_match_failure error ) ) end ; let ( vals , meths , concrs ) = extract_constraints clty . cltyp_type in rc { cl_desc = Tcl_constraint ( cl , Some clty , vals , meths , concrs ) ; cl_loc = scl . pcl_loc ; cl_type = snd ( Ctype . instance_class [ ] clty . cltyp_type ) ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_open ( pod , e ) -> let used_slot = ref false in let ( od , new_val_env ) = ! type_open_descr ~ used_slot val_env pod in let ( _ , new_met_env ) = ! type_open_descr ~ used_slot met_env pod in let cl = class_expr cl_num new_val_env new_met_env e in rc { cl_desc = Tcl_open ( od , cl ) ; cl_loc = scl . pcl_loc ; cl_type = cl . cl_type ; cl_env = val_env ; cl_attributes = scl . pcl_attributes ; } | Pcl_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) |
let var_option = Predef . type_option ( Btype . newgenvar ( ) ) |
let rec approx_declaration cl = match cl . pcl_desc with Pcl_fun ( l , _ , _ , cl ) -> let arg = if Btype . is_optional l then Ctype . instance var_option else Ctype . newvar ( ) in Ctype . newty ( Tarrow ( l , arg , approx_declaration cl , Cok ) ) | Pcl_let ( _ , _ , cl ) -> approx_declaration cl | Pcl_constraint ( cl , _ ) -> approx_declaration cl | _ -> Ctype . newvar ( ) |
let rec approx_description ct = match ct . pcty_desc with Pcty_arrow ( l , _ , ct ) -> let arg = if Btype . is_optional l then Ctype . instance var_option else Ctype . newvar ( ) in Ctype . newty ( Tarrow ( l , arg , approx_description ct , Cok ) ) | _ -> Ctype . newvar ( ) |
let temp_abbrev loc env id arity = let params = ref [ ] in for _i = 1 to arity do params := Ctype . newvar ( ) :: ! params done ; let ty = Ctype . newobj ( Ctype . newvar ( ) ) in let env = Env . add_type ~ check : true id { type_params = ! params ; type_arity = arity ; type_kind = Type_abstract ; type_private = Public ; type_manifest = Some ty ; type_variance = Misc . replicate_list Variance . full arity ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = loc ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } env in ( ! params , ty , env ) |
let initial_env define_class approx ( res , env ) ( cl , id , ty_id , obj_id , cl_id ) = let arity = List . length cl . pci_params in let ( obj_params , obj_ty , env ) = temp_abbrev cl . pci_loc env obj_id arity in let ( cl_params , cl_ty , env ) = temp_abbrev cl . pci_loc env cl_id arity in let constr_type = approx cl . pci_expr in if ! Clflags . principal then Ctype . generalize_spine constr_type ; let dummy_cty = Cty_signature { csig_self = Ctype . newvar ( ) ; csig_vars = Vars . empty ; csig_concr = Concr . empty ; csig_inher = [ ] } in let dummy_class = { Types . cty_params = [ ] ; cty_variance = [ ] ; cty_type = dummy_cty ; cty_path = unbound_class ; cty_new = begin match cl . pci_virt with | Virtual -> None | Concrete -> Some constr_type end ; cty_loc = Location . none ; cty_attributes = [ ] ; } in let env = Env . add_cltype ty_id { clty_params = [ ] ; clty_variance = [ ] ; clty_type = dummy_cty ; clty_path = unbound_class ; clty_loc = Location . none ; clty_attributes = [ ] ; } ( if define_class then Env . add_class id dummy_class env else env ) in ( ( cl , id , ty_id , obj_id , obj_params , obj_ty , cl_id , cl_params , cl_ty , constr_type , dummy_class ) :: res , env ) |
let class_infos define_class kind ( cl , id , ty_id , obj_id , obj_params , obj_ty , cl_id , cl_params , cl_ty , constr_type , dummy_class ) ( res , env ) = reset_type_variables ( ) ; Ctype . begin_class_def ( ) ; let ci_params = let make_param ( sty , v ) = try ( transl_type_param env sty , v ) with Already_bound -> raise ( Error ( sty . ptyp_loc , env , Repeated_parameter ) ) in List . map make_param cl . pci_params in let params = List . map ( fun ( cty , _ ) -> cty . ctyp_type ) ci_params in let coercion_locs = ref [ ] in let ( expr , typ ) = try Typecore . self_coercion := ( Path . Pident obj_id , coercion_locs ) :: ! Typecore . self_coercion ; let res = kind env cl . pci_expr in Typecore . self_coercion := List . tl ! Typecore . self_coercion ; res with exn -> Typecore . self_coercion := [ ] ; raise exn in Ctype . end_def ( ) ; let sty = Ctype . self_type typ in let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sty ) in List . iter ( fun ( met , _ , ty ) -> if met = dummy_method then Ctype . generalize ty ) fields ; let rv = Ctype . row_variable sty in List . iter ( Ctype . limited_generalize rv ) params ; limited_generalize rv typ ; let ( obj_params ' , obj_type ) = Ctype . instance_class params typ in let constr = Ctype . newconstr ( Path . Pident obj_id ) obj_params in begin let ty = Ctype . self_type obj_type in Ctype . hide_private_methods ty ; if not ( Ctype . close_object ty ) then raise ( Error ( cl . pci_loc , env , Closing_self_type ty ) ) ; begin try List . iter2 ( Ctype . unify env ) obj_params obj_params ' with Ctype . Unify _ -> raise ( Error ( cl . pci_loc , env , Bad_parameters ( obj_id , constr , Ctype . newconstr ( Path . Pident obj_id ) obj_params ' ) ) ) end ; begin try Ctype . unify env ty constr with Ctype . Unify _ -> raise ( Error ( cl . pci_loc , env , Abbrev_type_clash ( constr , ty , Ctype . expand_head env constr ) ) ) end end ; begin let ( cl_params ' , cl_type ) = Ctype . instance_class params typ in let ty = Ctype . self_type cl_type in Ctype . hide_private_methods ty ; Ctype . set_object_name obj_id ( Ctype . row_variable ty ) cl_params ty ; begin try List . iter2 ( Ctype . unify env ) cl_params cl_params ' with Ctype . Unify _ -> raise ( Error ( cl . pci_loc , env , Bad_parameters ( cl_id , Ctype . newconstr ( Path . Pident cl_id ) cl_params , Ctype . newconstr ( Path . Pident cl_id ) cl_params ' ) ) ) end ; begin try Ctype . unify env ty cl_ty with Ctype . Unify _ -> let constr = Ctype . newconstr ( Path . Pident cl_id ) params in raise ( Error ( cl . pci_loc , env , Abbrev_type_clash ( constr , ty , cl_ty ) ) ) end end ; begin try Ctype . unify env ( constructor_type constr obj_type ) ( Ctype . instance constr_type ) with Ctype . Unify trace -> raise ( Error ( cl . pci_loc , env , Constructor_type_mismatch ( cl . pci_name . txt , trace ) ) ) end ; let cty_variance = List . map ( fun _ -> Variance . full ) params in let cltydef = { clty_params = params ; clty_type = class_body typ ; clty_variance = cty_variance ; clty_path = Path . Pident obj_id ; clty_loc = cl . pci_loc ; clty_attributes = cl . pci_attributes ; } and clty = { cty_params = params ; cty_type = typ ; cty_variance = cty_variance ; cty_path = Path . Pident obj_id ; cty_new = begin match cl . pci_virt with | Virtual -> None | Concrete -> Some constr_type end ; cty_loc = cl . pci_loc ; cty_attributes = cl . pci_attributes ; } in dummy_class . cty_type <- typ ; let env = Env . add_cltype ty_id cltydef ( if define_class then Env . add_class id clty env else env ) in if cl . pci_virt = Concrete then begin let sign = Ctype . signature_of_class_type typ in let mets = virtual_methods sign in let vals = Vars . fold ( fun name ( _mut , vr , _ty ) l -> if vr = Virtual then name :: l else l ) sign . csig_vars [ ] in if mets <> [ ] || vals <> [ ] then raise ( Error ( cl . pci_loc , env , Virtual_class ( define_class , false , mets , vals ) ) ) ; end ; let arity = Ctype . class_type_arity typ in let pub_meths = let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields ( Ctype . expand_head env obj_ty ) ) in List . map ( function ( lab , _ , _ ) -> lab ) fields in let ( params ' , typ ' ) = Ctype . instance_class params typ in let cltydef = { clty_params = params ' ; clty_type = class_body typ ' ; clty_variance = cty_variance ; clty_path = Path . Pident obj_id ; clty_loc = cl . pci_loc ; clty_attributes = cl . pci_attributes ; } and clty = { cty_params = params ' ; cty_type = typ ' ; cty_variance = cty_variance ; cty_path = Path . Pident obj_id ; cty_new = begin match cl . pci_virt with | Virtual -> None | Concrete -> Some ( Ctype . instance constr_type ) end ; cty_loc = cl . pci_loc ; cty_attributes = cl . pci_attributes ; } in let obj_abbr = { type_params = obj_params ; type_arity = List . length obj_params ; type_kind = Type_abstract ; type_private = Public ; type_manifest = Some obj_ty ; type_variance = List . map ( fun _ -> Variance . full ) obj_params ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = cl . pci_loc ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } in let ( cl_params , cl_ty ) = Ctype . instance_parameterized_type params ( Ctype . self_type typ ) in Ctype . hide_private_methods cl_ty ; Ctype . set_object_name obj_id ( Ctype . row_variable cl_ty ) cl_params cl_ty ; let cl_abbr = { type_params = cl_params ; type_arity = List . length cl_params ; type_kind = Type_abstract ; type_private = Public ; type_manifest = Some cl_ty ; type_variance = List . map ( fun _ -> Variance . full ) cl_params ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_loc = cl . pci_loc ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } in ( ( cl , id , clty , ty_id , cltydef , obj_id , obj_abbr , cl_id , cl_abbr , ci_params , arity , pub_meths , List . rev ! coercion_locs , expr ) :: res , env ) |
let final_decl env define_class ( cl , id , clty , ty_id , cltydef , obj_id , obj_abbr , cl_id , cl_abbr , ci_params , arity , pub_meths , coe , expr ) = begin try Ctype . collapse_conj_params env clty . cty_params with Ctype . Unify trace -> raise ( Error ( cl . pci_loc , env , Non_collapsable_conjunction ( id , clty , trace ) ) ) end ; begin let self_type = Ctype . self_type clty . cty_type in let methods , _ = Ctype . flatten_fields ( Ctype . object_fields ( Ctype . expand_head env self_type ) ) in List . iter ( fun ( lab , kind , _ ) -> if lab = dummy_method then match Btype . field_kind_repr kind with Fvar r -> Btype . set_kind r Fabsent | _ -> ( ) ) methods end ; List . iter Ctype . generalize clty . cty_params ; generalize_class_type true clty . cty_type ; Option . iter Ctype . generalize clty . cty_new ; List . iter Ctype . generalize obj_abbr . type_params ; Option . iter Ctype . generalize obj_abbr . type_manifest ; List . iter Ctype . generalize cl_abbr . type_params ; Option . iter Ctype . generalize cl_abbr . type_manifest ; if not ( closed_class clty ) then raise ( Error ( cl . pci_loc , env , Non_generalizable_class ( id , clty ) ) ) ; begin match Ctype . closed_class clty . cty_params ( Ctype . signature_of_class_type clty . cty_type ) with None -> ( ) | Some reason -> let printer = if define_class then function ppf -> Printtyp . class_declaration id ppf clty else function ppf -> Printtyp . cltype_declaration id ppf cltydef in raise ( Error ( cl . pci_loc , env , Unbound_type_var ( printer , reason ) ) ) end ; { id ; clty ; ty_id ; cltydef ; obj_id ; obj_abbr ; cl_id ; cl_abbr ; arity ; pub_meths ; coe ; expr ; id_loc = cl . pci_name ; req = { ci_loc = cl . pci_loc ; ci_virt = cl . pci_virt ; ci_params = ci_params ; ci_id_name = cl . pci_name ; ci_id_class = id ; ci_id_class_type = ty_id ; ci_id_object = obj_id ; ci_id_typehash = cl_id ; ci_expr = expr ; ci_decl = clty ; ci_type_decl = cltydef ; ci_attributes = cl . pci_attributes ; } } |
let class_infos define_class kind ( cl , id , ty_id , obj_id , obj_params , obj_ty , cl_id , cl_params , cl_ty , constr_type , dummy_class ) ( res , env ) = Builtin_attributes . warning_scope cl . pci_attributes ( fun ( ) -> class_infos define_class kind ( cl , id , ty_id , obj_id , obj_params , obj_ty , cl_id , cl_params , cl_ty , constr_type , dummy_class ) ( res , env ) ) |
let extract_type_decls { clty ; cltydef ; obj_id ; obj_abbr ; cl_abbr ; req } decls = ( obj_id , obj_abbr , cl_abbr , clty , cltydef , req ) :: decls |
let merge_type_decls decl ( obj_abbr , cl_abbr , clty , cltydef ) = { decl with obj_abbr ; cl_abbr ; clty ; cltydef } |
let final_env define_class env { id ; clty ; ty_id ; cltydef ; obj_id ; obj_abbr ; cl_id ; cl_abbr } = Env . add_type ~ check : true obj_id ( Subst . type_declaration Subst . identity obj_abbr ) ( Env . add_type ~ check : true cl_id ( Subst . type_declaration Subst . identity cl_abbr ) ( Env . add_cltype ty_id ( Subst . cltype_declaration Subst . identity cltydef ) ( if define_class then Env . add_class id ( Subst . class_declaration Subst . identity clty ) env else env ) ) ) |
let check_coercions env { id ; id_loc ; clty ; ty_id ; cltydef ; obj_id ; obj_abbr ; cl_id ; cl_abbr ; arity ; pub_meths ; coe ; req } = begin match coe with [ ] -> ( ) | loc :: _ -> let cl_ty , obj_ty = match cl_abbr . type_manifest , obj_abbr . type_manifest with Some cl_ab , Some obj_ab -> let cl_params , cl_ty = Ctype . instance_parameterized_type cl_abbr . type_params cl_ab and obj_params , obj_ty = Ctype . instance_parameterized_type obj_abbr . type_params obj_ab in List . iter2 ( Ctype . unify env ) cl_params obj_params ; cl_ty , obj_ty | _ -> assert false in begin try Ctype . subtype env cl_ty obj_ty ( ) with Ctype . Subtype ( tr1 , tr2 ) -> raise ( Typecore . Error ( loc , env , Typecore . Not_subtype ( tr1 , tr2 ) ) ) end ; if not ( Ctype . opened_object cl_ty ) then raise ( Error ( loc , env , Cannot_coerce_self obj_ty ) ) end ; { cls_id = id ; cls_id_loc = id_loc ; cls_decl = clty ; cls_ty_id = ty_id ; cls_ty_decl = cltydef ; cls_obj_id = obj_id ; cls_obj_abbr = obj_abbr ; cls_typesharp_id = cl_id ; cls_abbr = cl_abbr ; cls_arity = arity ; cls_pub_methods = pub_meths ; cls_info = req } |
let type_classes define_class approx kind env cls = let scope = Ctype . create_scope ( ) in let cls = List . map ( function cl -> ( cl , Ident . create_scoped ~ scope cl . pci_name . txt , Ident . create_scoped ~ scope cl . pci_name . txt , Ident . create_scoped ~ scope cl . pci_name . txt , Ident . create_scoped ~ scope ( " " # ^ cl . pci_name . txt ) ) ) cls in Ctype . begin_class_def ( ) ; let ( res , env ) = List . fold_left ( initial_env define_class approx ) ( [ ] , env ) cls in let ( res , env ) = List . fold_right ( class_infos define_class kind ) res ( [ ] , env ) in Ctype . end_def ( ) ; let res = List . rev_map ( final_decl env define_class ) res in let decls = List . fold_right extract_type_decls res [ ] in let decls = try Typedecl_variance . update_class_decls env decls with Typedecl_variance . Error ( loc , err ) -> raise ( Typedecl . Error ( loc , Typedecl . Variance err ) ) in let res = List . map2 merge_type_decls res decls in let env = List . fold_left ( final_env define_class ) env res in let res = List . map ( check_coercions env ) res in ( res , env ) |
let class_num = ref 0 |
let class_declaration env sexpr = incr class_num ; let expr = class_expr ( Int . to_string ! class_num ) env env sexpr in ( expr , expr . cl_type ) |
let class_description env sexpr = let expr = class_type env sexpr in ( expr , expr . cltyp_type ) |
let class_declarations env cls = let info , env = type_classes true approx_declaration class_declaration env cls in let ids , exprs = List . split ( List . map ( fun ci -> ci . cls_id , ci . cls_info . ci_expr ) info ) in check_recursive_class_bindings env ids exprs ; info , env |
let class_descriptions env cls = type_classes true approx_description class_description env cls |
let class_type_declarations env cls = let ( decls , env ) = type_classes false approx_description class_description env cls in ( List . map ( fun decl -> { clsty_ty_id = decl . cls_ty_id ; clsty_id_loc = decl . cls_id_loc ; clsty_ty_decl = decl . cls_ty_decl ; clsty_obj_id = decl . cls_obj_id ; clsty_obj_abbr = decl . cls_obj_abbr ; clsty_typesharp_id = decl . cls_typesharp_id ; clsty_abbr = decl . cls_abbr ; clsty_info = decl . cls_info } ) decls , env ) |
let rec unify_parents env ty cl = match cl . cl_desc with Tcl_ident ( p , _ , _ ) -> begin try let decl = Env . find_class p env in let _ , body = Ctype . find_cltype_for_path env decl . cty_path in Ctype . unify env ty ( Ctype . instance body ) with Not_found -> ( ) | _exn -> assert false end | Tcl_structure st -> unify_parents_struct env ty st | Tcl_open ( _ , cl ) | Tcl_fun ( _ , _ , _ , cl , _ ) | Tcl_apply ( cl , _ ) | Tcl_let ( _ , _ , _ , cl ) | Tcl_constraint ( cl , _ , _ , _ , _ ) -> unify_parents env ty cl List . iter ( function | { cf_desc = Tcf_inherit ( _ , cl , _ , _ , _ ) } -> unify_parents env ty cl | _ -> ( ) ) st . cstr_fields |
let type_object env loc s = incr class_num ; let ( desc , sign ) = class_structure ( Int . to_string ! class_num ) true env env loc s in let sty = Ctype . expand_head env sign . csig_self in Ctype . hide_private_methods sty ; let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sty ) in let meths = List . map ( fun ( s , _ , _ ) -> s ) fields in unify_parents_struct env sign . csig_self desc ; ( desc , sign , meths ) |
let ( ) = Typecore . type_object := type_object |
let approx_class sdecl = let open Ast_helper in let self ' = Typ . any ( ) in let clty ' = Cty . signature ~ loc : sdecl . pci_expr . pcty_loc ( Csig . mk self ' [ ] ) in { sdecl with pci_expr = clty ' } |
let approx_class_declarations env sdecls = fst ( class_type_declarations env ( List . map approx_class sdecls ) ) |
let report_error env ppf = function | Repeated_parameter -> fprintf ppf " A type parameter occurs several times " | Unconsistent_constraint trace -> fprintf ppf " The class 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 " ) | Field_type_mismatch ( k , m , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " The % s % s @ has type " k m ) ( function ppf -> fprintf ppf " but is expected to have type " ) | Structure_expected clty -> fprintf ppf " [ @ This class expression is not a class structure ; it has type @ % a ] " @ Printtyp . class_type clty | Cannot_apply _ -> fprintf ppf " This class expression is not a class function , it cannot be applied " | Apply_wrong_label l -> let mark_label = function | Nolabel -> " out label " | l -> sprintf " label % s " ( Btype . prefixed_label_name l ) in fprintf ppf " This argument cannot be applied with % s " ( mark_label l ) | Pattern_type_clash ty -> fprintf ppf " [ @% s @ % a ] " @ " This pattern cannot match self : it only matches values of type " Printtyp . type_expr ty | Unbound_class_2 cl -> fprintf ppf " [ @ The class @ % a @ is not yet completely defined ] " @ Printtyp . longident cl | Unbound_class_type_2 cl -> fprintf ppf " [ @ The class type @ % a @ is not yet completely defined ] " @ Printtyp . longident cl | Abbrev_type_clash ( abbrev , actual , expected ) -> Printtyp . reset_and_mark_loops_list [ abbrev ; actual ; expected ] ; fprintf ppf " [ @ The abbreviation @ % a @ expands to type @ % a @ \ but is used with type @ % a ] " @ ! Oprint . out_type ( Printtyp . tree_of_typexp false abbrev ) ! Oprint . out_type ( Printtyp . tree_of_typexp false actual ) ! Oprint . out_type ( Printtyp . tree_of_typexp false expected ) | Constructor_type_mismatch ( c , trace ) -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " The expression " \ new % s " \ has type " c ) ( function ppf -> fprintf ppf " but is used with type " ) | Virtual_class ( cl , imm , mets , vals ) -> let print_mets ppf mets = List . iter ( function met -> fprintf ppf " @ % s " met ) mets in let missings = match mets , vals with [ ] , _ -> " variables " | _ , [ ] -> " methods " | _ -> " methods and variables " in let print_msg ppf = if imm then fprintf ppf " This object has virtual % s " missings else if cl then fprintf ppf " This class should be virtual " else fprintf ppf " This class type should be virtual " in fprintf ppf " [ @% t . @ [ @< 2 > The following % s are undefined :% a ] ] " @@ print_msg missings print_mets ( mets @ vals ) | Parameter_arity_mismatch ( lid , expected , provided ) -> fprintf ppf " [ @ The class constructor % a @ expects % i type argument ( s ) , @ \ but is here applied to % i type argument ( s ) ] " @ Printtyp . longident lid expected provided | Parameter_mismatch trace -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " The type parameter " ) ( function ppf -> fprintf ppf " does not meet its constraint : it should be " ) | Bad_parameters ( id , params , cstrs ) -> Printtyp . reset_and_mark_loops_list [ params ; cstrs ] ; fprintf ppf " [ @ The abbreviation % a @ is used with parameters @ % a @ \ which are incompatible with constraints @ % a ] " @ Printtyp . ident id ! Oprint . out_type ( Printtyp . tree_of_typexp false params ) ! Oprint . out_type ( Printtyp . tree_of_typexp false cstrs ) | Class_match_failure error -> Includeclass . report_error ppf error | Unbound_val lab -> fprintf ppf " Unbound instance variable % s " lab | Unbound_type_var ( printer , reason ) -> let print_common ppf kind ty0 real lab ty = let ty1 = if real then ty0 else Btype . newgenty ( Tobject ( ty0 , ref None ) ) in List . iter Printtyp . mark_loops [ ty ; ty1 ] ; fprintf ppf " The % s % s @ has type ; @< 1 2 >% a @ where @ % a @ is unbound " kind lab ! Oprint . out_type ( Printtyp . tree_of_typexp false ty ) ! Oprint . out_type ( Printtyp . tree_of_typexp false ty0 ) in let print_reason ppf = function | Ctype . CC_Method ( ty0 , real , lab , ty ) -> print_common ppf " method " ty0 real lab ty | Ctype . CC_Value ( ty0 , real , lab , ty ) -> print_common ppf " instance variable " ty0 real lab ty in Printtyp . reset ( ) ; fprintf ppf " [ @< v [ >@ Some type variables are unbound in this type ; :@< 1 2 >% t ] @@ \ [ @% a ] ] " @@ printer print_reason reason | Non_generalizable_class ( id , clty ) -> fprintf ppf " [ @ The type of this class , @ % a , @ \ contains type variables that cannot be generalized ] " @ ( Printtyp . class_declaration id ) clty | Cannot_coerce_self ty -> fprintf ppf " [ @ The type of self cannot be coerced to @ \ the type of the current class :@ % a . . @\ Some occurrences are contravariant ] " @ Printtyp . type_scheme ty | Non_collapsable_conjunction ( id , clty , trace ) -> fprintf ppf " [ @ The type of this class , @ % a , @ \ contains non - collapsible conjunctive types in constraints . @ % t ] " @ ( Printtyp . class_declaration id ) clty ( fun ppf -> Printtyp . report_unification_error ppf env trace ( fun ppf -> fprintf ppf " Type " ) ( fun ppf -> fprintf ppf " is not compatible with type " ) ) | Final_self_clash trace -> Printtyp . report_unification_error ppf env trace ( function ppf -> fprintf ppf " This object is expected to have type " ) ( function ppf -> fprintf ppf " but actually has type " ) | Mutability_mismatch ( _lab , mut ) -> let mut1 , mut2 = if mut = Immutable then " mutable " , " immutable " else " immutable " , " mutable " in fprintf ppf " [ @ The instance variable is % s ; @ it cannot be redefined as % s ] " @ mut1 mut2 | No_overriding ( _ , " " ) -> fprintf ppf " [ @ This inheritance does not override any method @ % s ] " @ " instance variable " | No_overriding ( kind , name ) -> fprintf ppf " [ @ The % s ` % s ' @ has no previous definition ] " @ kind name | Duplicate ( kind , name ) -> fprintf ppf " [ @ The % s ` % s ' @ has multiple definitions in this object ] " @ kind name | Closing_self_type self -> fprintf ppf " [ @ Cannot close type of object literal :@ % a , @\ it has been unified with the self type of a class that is not yet @ \ completely defined . ] " @ Printtyp . type_scheme self |
let report_error env ppf err = Printtyp . wrap_printing_env ~ error : true env ( fun ( ) -> report_error env ppf err ) |
let ( ) = Location . register_error_of_exn ( function | Error ( loc , env , err ) -> Some ( Location . error_of_printer ~ loc ( report_error env ) err ) | Error_forward err -> Some err | _ -> None ) |
type unary_interval = { upper_bound : Type . t ; lower_bound : Type . t ; } |
type callable_parameter_interval = | Top | Singleton of Type . Callable . parameters | Bottom |
type tuple_interval = | TopTuple | BottomTuple | SingletonTuple of Type . t Type . OrderedTypes . record |
type t = { unaries : unary_interval UnaryVariable . Map . t ; callable_parameters : callable_parameter_interval ParameterVariable . Map . t ; tuple_variadics : tuple_interval TupleVariable . Map . t ; have_fallbacks : Type . Variable . Set . t ; } |
let show_map map ~ show_key ~ show_data ~ short_name = if Map . is_empty map then " " else let show ~ key ~ data sofar = Printf . sprintf " % s => % s " ( show_key key ) ( show_data data ) :: sofar in Map . fold map ~ init [ ] : ~ f : show |> String . concat ~ sep " :\ n " |> Format . sprintf " % s : [ % s ] " short_name |
let pp format { unaries ; callable_parameters ; tuple_variadics ; have_fallbacks } = let unaries = show_map unaries ~ show_key : UnaryVariable . show ~ show_data : show_unary_interval ~ short_name " : un " in let callable_parameters = show_map callable_parameters ~ show_key : ParameterVariable . show ~ show_data : show_callable_parameter_interval ~ short_name " : cb " in let tuple_variadics = show_map tuple_variadics ~ show_key : TupleVariable . show ~ show_data : show_tuple_interval ~ short_name " : variadic_tuple " in let have_fallbacks = Set . to_list have_fallbacks |> List . to_string ~ f : Type . Variable . show |> Format . sprintf " \ nHave Fallbacks to Any : % s " in Format . fprintf format " { % s % s % s % s } " unaries callable_parameters tuple_variadics have_fallbacks |
let show annotation = Format . asprintf " % a " pp annotation |
let empty = { unaries = UnaryVariable . Map . empty ; callable_parameters = ParameterVariable . Map . empty ; tuple_variadics = TupleVariable . Map . empty ; have_fallbacks = Type . Variable . Set . empty ; } |
let exists_in_bounds { unaries ; callable_parameters ; tuple_variadics ; _ } ~ variables = let contains_variable annotation = let contains_unary = Type . Variable . GlobalTransforms . Unary . collect_all annotation |> List . exists ~ f ( : fun variable -> List . mem variables ( Type . Variable . Unary variable ) ~ equal : Type . Variable . equal ) in let contains_parameter_variadic = let parameter_variadic_contained_in_list variable = List . mem variables ( Type . Variable . ParameterVariadic variable ) ~ equal : Type . Variable . equal in Type . Variable . GlobalTransforms . ParameterVariadic . collect_all annotation |> List . exists ~ f : parameter_variadic_contained_in_list in let contains_tuple_variadic = Type . Variable . GlobalTransforms . TupleVariadic . collect_all annotation |> List . exists ~ f ( : fun variable -> List . mem variables ( Type . Variable . TupleVariadic variable ) ~ equal : Type . Variable . equal ) in contains_unary || contains_parameter_variadic || contains_tuple_variadic in let exists_in_interval_bounds { upper_bound ; lower_bound } = contains_variable upper_bound || contains_variable lower_bound in let exists_in_callable_parameter_interval_bounds = function | Singleton parameters -> Type . Callable . create ~ parameters ~ annotation : Type . Any ( ) |> contains_variable | _ -> false in let exists_in_tuple_interval_bound = function | SingletonTuple ordered_type -> Type . Tuple ordered_type |> contains_variable | _ -> false in UnaryVariable . Map . exists unaries ~ f : exists_in_interval_bounds || ParameterVariable . Map . exists callable_parameters ~ f : exists_in_callable_parameter_interval_bounds || TupleVariable . Map . exists tuple_variadics ~ f : exists_in_tuple_interval_bound |
module Solution = struct type t = { unaries : Type . t UnaryVariable . Map . t ; callable_parameters : Type . Callable . parameters ParameterVariable . Map . t ; tuple_variadics : Type . t Type . OrderedTypes . record TupleVariable . Map . t ; } let equal left right = UnaryVariable . Map . equal Type . equal left . unaries right . unaries && ParameterVariable . Map . equal Type . Callable . equal_parameters left . callable_parameters right . callable_parameters && TupleVariable . Map . equal ( Type . OrderedTypes . equal_record Type . equal ) left . tuple_variadics right . tuple_variadics let show { unaries ; callable_parameters ; tuple_variadics } = let unaries = show_map unaries ~ show_key : UnaryVariable . show ~ show_data : Type . show ~ short_name " : un " in let callable_parameters = show_map callable_parameters ~ show_key : ParameterVariable . show ~ show_data : Type . Callable . show_parameters ~ short_name " : cb " in let tuple_variadics = show_map tuple_variadics ~ show_key : TupleVariable . show ~ show_data ( : Type . OrderedTypes . show_record Type . pp ) ~ short_name " : variadic_tuple " in Format . sprintf " { % s % s % s } " unaries callable_parameters tuple_variadics let pp format solution = Format . fprintf format " % s " ( show solution ) let empty = { unaries = UnaryVariable . Map . empty ; callable_parameters = ParameterVariable . Map . empty ; tuple_variadics = TupleVariable . Map . empty ; } let instantiate { unaries ; callable_parameters ; tuple_variadics } annotation = let annotation = if UnaryVariable . Map . is_empty unaries then annotation else Type . Variable . GlobalTransforms . Unary . replace_all ( fun variable -> UnaryVariable . Map . find unaries variable ) annotation in let annotation = if ParameterVariable . Map . is_empty callable_parameters then annotation else Type . Variable . GlobalTransforms . ParameterVariadic . replace_all ( fun variable -> ParameterVariable . Map . find callable_parameters variable ) annotation in let annotation = if TupleVariable . Map . is_empty tuple_variadics then annotation else Type . Variable . GlobalTransforms . TupleVariadic . replace_all ( fun variable -> TupleVariable . Map . find tuple_variadics variable ) annotation in annotation let instantiate_single_variable { unaries ; _ } = UnaryVariable . Map . find unaries let instantiate_single_parameter_variadic { callable_parameters ; _ } = ParameterVariable . Map . find callable_parameters let instantiate_ordered_types solution ordered_type = match instantiate solution ( Type . Tuple ordered_type ) with | Type . Tuple instantiated_ordered_type -> instantiated_ordered_type | _ -> failwith " expected Tuple " let instantiate_callable_parameters solution parameters = match instantiate solution ( Type . Callable . create ~ parameters ~ annotation : Type . Any ( ) ) with | Type . Callable { implementation = { parameters ; _ } ; _ } -> parameters | _ -> failwith " instantiate is not preserving callables " let set ( { unaries ; callable_parameters ; tuple_variadics } as solution ) = function | Type . Variable . UnaryPair ( key , data ) -> { solution with unaries = UnaryVariable . Map . set unaries ~ key ~ data } | Type . Variable . ParameterVariadicPair ( key , data ) -> { solution with callable_parameters = ParameterVariable . Map . set callable_parameters ~ key ~ data ; } | Type . Variable . TupleVariadicPair ( key , data ) -> { solution with tuple_variadics = TupleVariable . Map . set tuple_variadics ~ key ~ data } let create = List . fold ~ f : set ~ init : empty end |
module type OrderedConstraintsType = sig type order val add_lower_bound : t -> order : order -> pair : Type . Variable . pair -> t option val add_upper_bound : t -> order : order -> pair : Type . Variable . pair -> t option val add_fallback_to_any : t -> Type . Variable . t -> t val solve : t -> order : order -> Solution . t option val extract_partial_solution : t -> order : order -> variables : Type . Variable . t list -> ( t * Solution . t ) option end |
module type OrderType = sig type t val always_less_or_equal : t -> left : Type . t -> right : Type . t -> bool val meet : t -> Type . t -> Type . t -> Type . t val join : t -> Type . t -> Type . t -> Type . t end |
module OrderedConstraints ( Order : OrderType ) = struct module IntervalContainer = struct module type Interval = sig module Variable : Type . Variable . VariableKind type t val create : ? upper_bound : Variable . domain -> ? lower_bound : Variable . domain -> unit -> t val intersection : t -> t -> order : Order . t -> t option val narrowest_valid_value : t -> order : Order . t -> variable : Variable . t -> Variable . domain option val merge_solution_in : t -> variable : Variable . t -> solution : Solution . t -> t val is_trivial : t -> variable : Variable . t -> bool val free_variables : t -> Type . Variable . t list end module Make ( Interval : Interval ) = struct let add_bound container ~ order ~ variable ~ bound ~ is_lower_bound = if Interval . Variable . equal_domain bound ( Interval . Variable . self_reference variable ) then Some container else let new_constraint = if is_lower_bound then Interval . create ~ lower_bound : bound ( ) else Interval . create ~ upper_bound : bound ( ) in let existing = Map . find container variable |> Option . value ~ default ( : Interval . create ( ) ) in Interval . intersection existing new_constraint ~ order >>= fun intersection -> Interval . narrowest_valid_value intersection ~ order ~ variable >>| fun _ -> Map . set container ~ key : variable ~ data : intersection let merge_solution container ~ solution = Map . mapi container ~ f ( : fun ~ key ~ data -> Interval . merge_solution_in data ~ variable : key ~ solution ) |> Map . filteri ~ f ( : fun ~ key ~ data -> not ( Interval . is_trivial data ~ variable : key ) ) let partition_independent_dependent container ~ with_regards_to = let contains_key { unaries ; callable_parameters ; tuple_variadics ; have_fallbacks } key = let has_constraints = match key with | Type . Variable . Unary unary -> Map . mem unaries unary | Type . Variable . ParameterVariadic parameters -> Map . mem callable_parameters parameters | Type . Variable . TupleVariadic variadic -> Map . mem tuple_variadics variadic in has_constraints || Set . mem have_fallbacks key in let is_independent target = Interval . free_variables target |> List . exists ~ f ( : contains_key with_regards_to ) |> not in Map . partition_tf container ~ f : is_independent let add_solution container partial_solution ~ order = let add_solution ~ key : variable ~ data : target = function | Some partial_solution -> Interval . narrowest_valid_value target ~ order ~ variable >>| ( fun value -> Interval . Variable . pair variable value ) >>| Solution . set partial_solution | None -> None in Map . fold container ~ f : add_solution ~ init ( : Some partial_solution ) end end module UnaryTypeInterval = struct module Variable = UnaryVariable type t = unary_interval let lower_bound { lower_bound ; _ } = lower_bound let upper_bound { upper_bound ; _ } = upper_bound let create ( ? upper_bound = Type . Top ) ( ? lower_bound = Type . Bottom ) ( ) = { upper_bound ; lower_bound } let intersection left right ~ order = Some { upper_bound = Order . meet order left . upper_bound right . upper_bound ; lower_bound = Order . join order left . lower_bound right . lower_bound ; } let narrowest_valid_value interval ~ order ~ variable { : UnaryVariable . constraints = exogenous_constraint ; _ } = let lowest_non_bottom_member interval ~ order = let non_empty { upper_bound ; lower_bound } ~ order = Order . always_less_or_equal order ~ left : lower_bound ~ right : upper_bound in Option . some_if ( non_empty interval ~ order ) ( lower_bound interval ) >>| function | Type . Bottom -> upper_bound interval | other -> other in match exogenous_constraint with | Explicit explicits -> let collect annotation sofar = let add_to_explicits_if_safe sofar candidate = match candidate with | { Type . Variable . Unary . constraints = Explicit left_constraints ; _ } as candidate -> let exists_in_explicits left_constraint = List . exists explicits ~ f ( : Type . equal left_constraint ) in if List . for_all left_constraints ~ f : exists_in_explicits then Type . Variable candidate :: sofar else sofar | _ -> sofar in Type . Variable . GlobalTransforms . Unary . collect_all annotation |> List . fold ~ f : add_to_explicits_if_safe ~ init : sofar in let explicits = collect ( lower_bound interval ) explicits |> collect ( upper_bound interval ) in let contains { upper_bound ; lower_bound } candidate ~ order = Order . always_less_or_equal order ~ left : candidate ~ right : upper_bound && Order . always_less_or_equal order ~ left : lower_bound ~ right : candidate in List . find ~ f ( : contains interval ~ order ) explicits | Bound exogenous_bound -> intersection interval ( create ~ upper_bound : exogenous_bound ( ) ) ~ order >>= lowest_non_bottom_member ~ order | Unconstrained -> lowest_non_bottom_member interval ~ order | LiteralIntegers -> ( let is_literal_integer = function | Type . Literal ( Type . Integer _ ) -> true | Variable { constraints = LiteralIntegers ; _ } -> true | _ -> false in let member = lowest_non_bottom_member interval ~ order in match member with | Some found_member when is_literal_integer found_member -> member | Some ( Type . Union union ) when List . for_all union ~ f : is_literal_integer -> member | _ -> None ) let merge_solution_in { upper_bound ; lower_bound } ~ variable ~ solution = let smart_instantiate annotation = let instantiated = Solution . instantiate solution annotation in Option . some_if ( not ( Type . equal instantiated ( Type . Variable variable ) ) ) instantiated in let upper_bound = smart_instantiate upper_bound in let lower_bound = smart_instantiate lower_bound in create ? upper_bound ? lower_bound ( ) let is_trivial interval ~ variable : _ = match interval with | { upper_bound = Type . Top ; lower_bound = Type . Bottom } -> true | _ -> false let free_variables { upper_bound ; lower_bound } = Type . Variable . all_free_variables upper_bound @ Type . Variable . all_free_variables lower_bound end module CallableParametersInterval = struct module Variable = ParameterVariable type t = callable_parameter_interval let create ? upper_bound ? lower_bound ( ) = match upper_bound , lower_bound with | None , None -> Bottom | Some only , None | None , Some only -> Singleton only | Some left , Some right when Type . Callable . equal_parameters left right -> Singleton left | Some _ , Some _ -> Top let narrowest_valid_value interval ~ order : _ ~ variable : _ = match interval with | Top | Bottom -> None | Singleton parameters -> Some parameters let intersection left right ~ order : _ = match left , right with | Top , _ | _ , Top -> Some Top | other , Bottom | Bottom , other -> Some other | Singleton left , Singleton right when Type . Callable . equal_parameters left right -> Some ( Singleton left ) | _ , _ -> Some Top let merge_solution_in target ~ variable : _ ~ solution = match target with | Top | Bottom -> target | Singleton parameters -> ( let callable = Type . Callable . create ~ parameters ~ annotation : Type . Any ( ) in match Solution . instantiate solution callable with | Type . Callable { implementation = { parameters = instantiated_parameters ; _ } ; _ } -> Singleton instantiated_parameters | _ -> failwith " impossible " ) let is_trivial interval ~ variable = match interval with | Singleton ( Type . Callable . ParameterVariadicTypeVariable { head = [ ] ; variable = target_variable } ) -> ParameterVariable . equal variable target_variable | _ -> false let free_variables = function | Top | Bottom -> [ ] | Singleton parameters -> Type . Callable . create ~ parameters ~ annotation : Type . Any ( ) |> Type . Variable . all_free_variables end module TupleInterval = struct module Variable = TupleVariable type t = tuple_interval let create ? upper_bound ? lower_bound ( ) = match lower_bound , upper_bound with | None , None -> BottomTuple | None , Some only | Some only , None -> SingletonTuple only | Some left , Some right when Type . OrderedTypes . equal_record Type . equal left right -> SingletonTuple left | _ -> TopTuple let intersection left right ~ order = match left , right with | TopTuple , _ | _ , TopTuple -> Some TopTuple | other , BottomTuple | BottomTuple , other -> Some other | SingletonTuple left , SingletonTuple right -> if Order . always_less_or_equal order ~ left ( : Type . Tuple left ) ~ right ( : Type . Tuple right ) then Some ( SingletonTuple right ) else if Order . always_less_or_equal order ~ left ( : Type . Tuple right ) ~ right ( : Type . Tuple left ) then Some ( SingletonTuple left ) else None let narrowest_valid_value interval ~ order : _ ~ variable : _ = match interval with | TopTuple | BottomTuple -> None | SingletonTuple ordered_type -> Some ordered_type let merge_solution_in target ~ variable : _ ~ solution = match target with | TopTuple | BottomTuple -> target | SingletonTuple ordered_type -> ( match Solution . instantiate solution ( Type . Tuple ordered_type ) with | Type . Tuple instantiated_ordered_type -> SingletonTuple instantiated_ordered_type | _ -> failwith " impossible " ) let is_trivial interval ~ variable = match interval with | SingletonTuple ( Type . OrderedTypes . Concatenation concatenation ) -> Type . OrderedTypes . Concatenation . extract_sole_variadic concatenation >>| ( fun variadic -> TupleVariable . equal variadic variable ) |> Option . value ~ default : false | _ -> false let free_variables = function | TopTuple | BottomTuple -> [ ] | SingletonTuple ordered_type -> Type . Variable . all_free_variables ( Type . Tuple ordered_type ) end module CallableParametersIntervalContainer = IntervalContainer . Make ( CallableParametersInterval ) module UnaryIntervalContainer = IntervalContainer . Make ( UnaryTypeInterval ) module TupleIntervalContainer = IntervalContainer . Make ( TupleInterval ) type order = Order . t let add_bound ( { unaries ; callable_parameters ; tuple_variadics ; _ } as constraints ) ~ order ~ pair ~ is_lower_bound = match pair with | Type . Variable . UnaryPair ( variable , bound ) -> UnaryIntervalContainer . add_bound unaries ~ order ~ variable ~ bound ~ is_lower_bound >>| fun unaries -> { constraints with unaries } | Type . Variable . ParameterVariadicPair ( variable , bound ) -> CallableParametersIntervalContainer . add_bound callable_parameters ~ order ~ variable ~ bound ~ is_lower_bound >>| fun callable_parameters -> { constraints with callable_parameters } | Type . Variable . TupleVariadicPair ( variable , bound ) -> TupleIntervalContainer . add_bound tuple_variadics ~ order ~ variable ~ bound ~ is_lower_bound >>| fun tuple_variadics -> { constraints with tuple_variadics } let add_lower_bound = add_bound ~ is_lower_bound : true let add_upper_bound = add_bound ~ is_lower_bound : false let add_fallback_to_any ( { have_fallbacks ; _ } as constraints ) addition = { constraints with have_fallbacks = Set . add have_fallbacks addition } let merge_solution { unaries ; callable_parameters ; tuple_variadics ; have_fallbacks } solution = { unaries = UnaryIntervalContainer . merge_solution unaries ~ solution ; callable_parameters = CallableParametersIntervalContainer . merge_solution callable_parameters ~ solution ; tuple_variadics = TupleIntervalContainer . merge_solution tuple_variadics ~ solution ; have_fallbacks ; } let apply_fallbacks solution ~ have_fallbacks = let optional_add map key data = match Map . add map ~ key ~ data with | ` Ok map -> map | ` Duplicate -> map in let add_fallback ( { Solution . unaries ; callable_parameters ; tuple_variadics } as solution ) = function | Type . Variable . Unary variable -> { solution with unaries = optional_add unaries variable Type . Any } | Type . Variable . ParameterVariadic variable -> { solution with callable_parameters = optional_add callable_parameters variable Type . Callable . Undefined ; } | Type . Variable . TupleVariadic variadic -> { solution with tuple_variadics = optional_add tuple_variadics variadic TupleVariable . any ; } in Set . to_list have_fallbacks |> List . fold ~ init : solution ~ f : add_fallback let solve constraints ~ order = let rec build_solution ~ remaining_constraints ~ partial_solution = let independent_constraints , dependent_constraints = let independent_unaries , dependent_unaries = UnaryIntervalContainer . partition_independent_dependent remaining_constraints . unaries ~ with_regards_to : remaining_constraints in let independent_tuple_variadics , dependent_tuple_variadics = TupleIntervalContainer . partition_independent_dependent remaining_constraints . tuple_variadics ~ with_regards_to : remaining_constraints in let independent_parameters , dependent_parameters = CallableParametersIntervalContainer . partition_independent_dependent remaining_constraints . callable_parameters ~ with_regards_to : remaining_constraints in let independent_fallbacks , dependent_fallbacks = let matches = function | Type . Variable . Unary key -> not ( Map . mem dependent_unaries key ) | ParameterVariadic key -> not ( Map . mem dependent_parameters key ) | TupleVariadic key -> not ( Map . mem dependent_tuple_variadics key ) in Set . partition_tf remaining_constraints . have_fallbacks ~ f : matches in ( { unaries = independent_unaries ; callable_parameters = independent_parameters ; tuple_variadics = independent_tuple_variadics ; have_fallbacks = independent_fallbacks ; } , { unaries = dependent_unaries ; callable_parameters = dependent_parameters ; tuple_variadics = dependent_tuple_variadics ; have_fallbacks = dependent_fallbacks ; } ) in let handle_dependent_constraints partial_solution = let is_empty { unaries ; callable_parameters ; tuple_variadics ; have_fallbacks } = UnaryVariable . Map . is_empty unaries && ParameterVariable . Map . is_empty callable_parameters && TupleVariable . Map . is_empty tuple_variadics && Set . is_empty have_fallbacks in if is_empty dependent_constraints then Some partial_solution else if is_empty independent_constraints then None else let remaining_constraints = merge_solution dependent_constraints partial_solution in build_solution ~ remaining_constraints ~ partial_solution in UnaryIntervalContainer . add_solution independent_constraints . unaries partial_solution ~ order >>= CallableParametersIntervalContainer . add_solution independent_constraints . callable_parameters ~ order >>= TupleIntervalContainer . add_solution independent_constraints . tuple_variadics ~ order >>| apply_fallbacks ~ have_fallbacks : independent_constraints . have_fallbacks >>= handle_dependent_constraints in build_solution ~ remaining_constraints : constraints ~ partial_solution : Solution . empty let extract_partial_solution { unaries ; callable_parameters ; tuple_variadics ; have_fallbacks } ~ order ~ variables = let extracted_constraints , remaining_constraints = let unary_matches ~ key ~ data : _ = List . exists variables ~ f ( : Type . Variable . equal ( Type . Variable . Unary key ) ) in let callable_parameters_matches ~ key ~ data : _ = List . exists variables ~ f ( : Type . Variable . equal ( Type . Variable . ParameterVariadic key ) ) in let tuple_variadic_matches ~ key ~ data : _ = List . exists variables ~ f ( : Type . Variable . equal ( Type . Variable . TupleVariadic key ) ) in let extracted_unaries , remaining_unaries = UnaryVariable . Map . partitioni_tf unaries ~ f : unary_matches in let extracted_variadics , remaining_variadics = ParameterVariable . Map . partitioni_tf callable_parameters ~ f : callable_parameters_matches in let extracted_tuple_variadics , remaining_tuple_variadics = TupleVariable . Map . partitioni_tf tuple_variadics ~ f : tuple_variadic_matches in let extracted_fallbacks , remaining_fallbacks = let matches = function | Type . Variable . Unary key -> unary_matches ~ key ~ data ( ) : | ParameterVariadic key -> callable_parameters_matches ~ key ~ data ( ) : | TupleVariadic key -> tuple_variadic_matches ~ key ~ data ( ) : in Set . partition_tf have_fallbacks ~ f : matches in ( { unaries = extracted_unaries ; callable_parameters = extracted_variadics ; tuple_variadics = extracted_tuple_variadics ; have_fallbacks = extracted_fallbacks ; } , { unaries = remaining_unaries ; callable_parameters = remaining_variadics ; tuple_variadics = remaining_tuple_variadics ; have_fallbacks = remaining_fallbacks ; } ) in solve extracted_constraints ~ order >>| fun solution -> merge_solution remaining_constraints solution , solution end |
let empty_head variable = { Type . Callable . head = [ ] ; variable } |
let child = Type . Primitive " Child " |
let left_parent = Type . Primitive " left_parent " |
let right_parent = Type . Primitive " right_parent " |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.