text
stringlengths
0
601k
let merge_errors ~ global_resolution errors = errors |> List . map ~ f ( : fun ( { Error . kind ; _ } as error ) -> { error with kind = Error . weaken_literals kind } ) |> Error . join_at_source ~ resolution : global_resolution |> List . sort ~ compare : Error . compare
let legacy_infer_for_define ~ configuration ~ global_resolution ~ source ( { : Source . source_path = { ModulePath . qualifier ; relative ; _ } ; _ } as source ) ~ define ( { : Node . location ; value = { Define . signature = { name ; _ } ; _ } } as define ) = try let local_errors = infer_local ~ configuration ~ global_resolution ~ source ~ define in let global_errors = infer_parameters_from_parent ~ global_resolution ~ source ~ define in let errors = List . rev_append global_errors local_errors in merge_errors ~ global_resolution errors with | ClassHierarchy . Untracked annotation -> Statistics . event ~ name " : undefined type during type inference " ~ integers [ ] : ~ normals [ " : handle " , relative ; " define " , Reference . show name ; " type " , annotation ] ( ) ; if configuration . debug then [ Error . create ~ location ( : Location . with_module ~ module_reference : qualifier location ) ~ kind ( : Error . AnalysisFailure ( UnexpectedUndefinedType annotation ) ) ~ define ; ] else [ ]
let infer_for_define ~ configuration ~ global_resolution ~ source ~ qualifier ~ filename_lookup ~ define = let timer = Timer . start ( ) in let { Node . location ; value = { Define . signature ; _ } } = define in let abstract = Define . Signature . is_abstract_method signature in let error_to_inference { AnalysisError . location ; kind ; _ } = let open AnalysisError in match kind with | MissingReturnAnnotation { annotation = Some type_ ; _ } when not abstract -> Some Inference . { type_ ; target = Return } | MissingParameterAnnotation { name ; annotation = Some type_ ; _ } -> Some Inference . { type_ ; target = Parameter { name } } | MissingGlobalAnnotation { name ; annotation = Some type_ ; _ } -> Some Inference . { type_ ; target = Global { name ; location } } | MissingAttributeAnnotation { parent ; missing_annotation = { name ; annotation = Some type_ ; _ } } -> Some Inference . { type_ ; target = Attribute { parent = type_to_reference parent ; name ; location } } | _ -> None in let add_missing_annotation_error ~ global_resolution ~ lookup result error = match error_to_inference error with | None -> result | Some raw -> raw |> Inference . create |> LocalResult . add_inference ~ global_resolution ~ lookup result in let errors = legacy_infer_for_define ~ configuration ~ global_resolution ~ source ~ define in let result = List . fold ~ init : ( LocalResult . from_signature ~ global_resolution ~ lookup : filename_lookup ~ qualifier define ) ~ f ( : add_missing_annotation_error ~ global_resolution ~ lookup : filename_lookup ) errors in let number_of_lines = location . stop . line - location . start . line + 1 in Statistics . performance ~ flush : false ~ randomly_log_every : 1000 ~ always_log_time_threshold : 0 . 050 ~ section ` : Infer ~ name " : SingleDefineInfer " ~ timer ~ normals : [ " name " , Reference . show signature . name ; " path " , filename_lookup qualifier |> Option . value ~ default " " ; :* " request kind " , " SingleDefineInfer " ; ] ~ integers [ " : number of lines " , number_of_lines ; " line " , location . start . line ] ( ) ; result
let should_analyze_define ~ skip_annotated ~ global_resolution { Node . value = { Define . signature = { return_annotation ; parameters ; _ } ; _ } as define ; _ } = let alias_environment = GlobalResolution . alias_environment global_resolution in let is_missing_or_invalid maybe_expression = let resolve_type expression = expression |> AliasEnvironment . ReadOnly . parse_annotation_without_validating_type_parameters alias_environment in maybe_expression >>| resolve_type >>| Type . is_untyped |> Option . value ~ default : true in let is_parameter_missing_any_or_alias { Node . value = { Parameter . annotation ; _ } ; _ } = is_missing_or_invalid annotation in ( not skip_annotated ) || Define . is_toplevel define || Define . is_class_toplevel define || Define . is_constructor define || is_missing_or_invalid return_annotation || parameters |> List . exists ~ f : is_parameter_missing_any_or_alias
let empty_infer_for_define ~ global_resolution ~ qualifier ~ define = let lookup _ = None in TypeInferenceData . LocalResult . from_signature ~ global_resolution ~ lookup ~ qualifier define
let infer_for_module ( ? skip_annotated = true ) ~ configuration ~ global_resolution ~ filename_lookup ( { Ast . Source . source_path = { qualifier ; _ } as source_path ; _ } as source ) = Log . debug " Running infer for % s . . . " source_path . relative ; let check define = if should_analyze_define ~ skip_annotated ~ global_resolution define then infer_for_define ~ configuration ~ global_resolution ~ source ~ qualifier ~ filename_lookup ~ define else empty_infer_for_define ~ global_resolution ~ qualifier ~ define in source |> Preprocessing . defines ~ include_toplevels : true |> List . map ~ f : check
module Testing = struct let define_names_to_analyze ~ global_resolution source = source |> Preprocessing . defines ~ include_toplevels : true |> List . filter ~ f ( : should_analyze_define ~ skip_annotated : true ~ global_resolution ) |> List . map ~ f ( : fun define -> define |> Node . value |> Define . name ) end
let configuration = Configuration . Analysis . create ~ source_paths [ ] : ( )
let assert_backward ~ resolution precondition statement postcondition = let module State = State ( struct let qualifier = Reference . empty let configuration = configuration let define = + mock_define let resolution_fixpoint = Some ( LocalAnnotationMap . empty ( ) ) let error_map = Some ( TypeCheck . LocalErrorMap . empty ( ) ) end ) in let create annotations = let resolution = let annotation_store = let annotify ( name , annotation ) = let annotation = let create 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 ; } in Resolution . with_annotation_store resolution ~ annotation_store in State . create ~ resolution ( ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let parsed = parse statement |> function | { Source . statements ; _ } -> statements in assert_state_equal ( create postcondition ) ( List . fold_right ~ f ( : fun statement state -> State . backward ~ statement_key : Cfg . exit_index state ~ statement |> State . widen_resolution_with_snapshots ) ~ init ( : create precondition ) parsed )
let test_backward_resolution_handling context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let assert_backward = assert_backward ~ resolution in assert_backward [ " y " , Type . integer ] " pass " [ " y " , Type . integer ] ; assert_backward [ " x " , Type . integer ] " x = y " [ " x " , Type . integer ; " y " , Type . integer ] ; assert_backward [ " y " , Type . integer ] " x = z " [ " y " , Type . integer ] ; assert_backward [ " x " , Type . integer ] " x += 1 " [ " x " , Type . integer ] ; assert_backward [ " x " , Type . integer ] " x = y = z " [ " x " , Type . integer ; " z " , Type . integer ] ; assert_backward [ " x " , Type . Primitive " B " ; " y " , Type . Primitive " C " ] " x = y = z " [ " x " , Type . Primitive " B " ; " y " , Type . Primitive " C " ; " z " , Type . Bottom ] ; assert_backward [ " a " , Type . integer ] " a , b = c , d " [ " a " , Type . integer ; " c " , Type . integer ] ; assert_backward [ " a " , Type . Top ; " b " , Type . integer ] " a = b " [ " b " , Type . integer ] ; assert_backward [ " x " , Type . integer ; " y " , Type . string ] " x , y = z " [ " x " , Type . integer ; " y " , Type . string ; " z " , Type . tuple [ Type . integer ; Type . string ] ] ; assert_backward [ " x " , Type . tuple [ Type . integer ; Type . string ] ] " x = y , z " [ " x " , Type . tuple [ Type . integer ; Type . string ] ; " y " , Type . integer ; " z " , Type . string ] ; assert_backward [ ] " x = 1 . 0 " [ ] ; assert_backward [ ] " x = ' string ' " [ ] ; assert_backward [ " x " , Type . Primitive " Foo " ] " x = ' string ' " [ " x " , Type . Primitive " Foo " ] ; assert_backward [ " x " , Type . Primitive " Foo " ] " x = ' string ' " [ " x " , Type . Primitive " Foo " ] ; assert_backward [ ] " int_to_str ( x ) " [ " x " , Type . integer ] ; assert_backward [ ] " str_float_to_int ( x , y ) " [ " x " , Type . string ; " y " , Type . float ] ; assert_backward [ ] " str_float_tuple_to_int ( t ) " [ " t " , Type . tuple [ Type . string ; Type . float ] ] ; assert_backward [ " x " , Type . string ] " unknown_to_int ( x ) " [ " x " , Type . string ] ; assert_backward [ " x " , Type . float ] " x = int_to_str ( x ) " [ " x " , Type . integer ] ; assert_backward [ " y " , Type . float ] " y = int_to_str ( x ) " [ " y " , Type . float ; " x " , Type . integer ] ; assert_backward [ " y " , Type . integer ] " y = int_to_str ( x ) " [ " y " , Type . integer ; " x " , Type . integer ] ; assert_backward [ ] " str_float_to_int ( x ) " [ " x " , Type . string ] ; assert_backward [ ] " str_float_to_int ( x , 1 . 0 ) " [ " x " , Type . string ] ; assert_backward [ ] " ' a ' . substr ( x ) " [ " x " , Type . integer ] ; assert_backward [ " y " , Type . float ] " y = obj . static_int_to_str ( x ) " [ " y " , Type . float ; " x " , Type . integer ] ; assert_backward [ ] " str_float_tuple_to_int ( ( x , y ) ) " [ " x " , Type . string ; " y " , Type . float ] ; assert_backward [ ] " nested_tuple_to_int ( ( ( x , y ) , z ) ) " [ " x " , Type . string ; " y " , Type . float ; " z " , Type . float ] ; assert_backward [ ( " cb " , Type . Callable . create ~ parameters ( : Defined [ Named { name = " arg " ; annotation = Type . integer ; default = false } ] ) ~ annotation : Type . none ( ) ) ; ] " cb ( x ) " [ ( " cb " , Type . Callable . create ~ parameters ( : Defined [ Named { name = " arg " ; annotation = Type . integer ; default = false } ] ) ~ annotation : Type . none ( ) ) ; " x " , Type . integer ; ] ; assert_backward [ ( " cb " , Type . parametric " BoundMethod " [ Single ( Type . Callable . create ~ parameters : ( Defined [ Named { name = " self " ; annotation = Type . string ; default = false } ; Named { name = " arg " ; annotation = Type . integer ; default = false } ; ] ) ~ annotation : Type . none ( ) ) ; Single Type . string ; ] ) ; ] " cb ( x ) " [ ( " cb " , Type . parametric " BoundMethod " [ Single ( Type . Callable . create ~ parameters : ( Defined [ Named { name = " self " ; annotation = Type . string ; default = false } ; Named { name = " arg " ; annotation = Type . integer ; default = false } ; ] ) ~ annotation : Type . none ( ) ) ; Single Type . string ; ] ) ; " x " , Type . integer ; ] ; assert_backward [ ] " str_float_to_int assert_backward [ ] " str_float_to_int assert_backward [ ] " star_int_to_int check_inference_results { | def foo ( ) : pass } | ~ target " : test . foo " ~ expected { " :| None " } ; | check_inference_results { | def foo ( ) : return } | ~ target " : test . foo " ~ expected { " :| None " } ; | check_inference_results { | def foo ( ) : return None } | ~ target " : test . foo " ~ expected { " :| None " } ; | check_inference_results { | def foo ( ) : x = undefined } | ~ target " : test . foo " ~ expected { " :| None " } ; | check_inference_results { | def foo ( b : bool ) : if b : return 1 } | ~ target " : test . foo " ~ expected { " :| typing . Optional [ int ] " } ; | check_inference_results { | def foo ( x : int ) : return x } | ~ target " : test . foo " ~ expected { " :| int " } ; | check_inference_results { | def foo ( ) : x = 1 return x } | ~ target " : test . foo " ~ expected { " :| int " } ; | check_inference_results { | def other ( ) -> int : return 1 def foo ( ) : x = " string " x = other ( ) return x } | ~ target " : test . foo " ~ expected { " :| int " } ; | check_inference_results { | def foo ( b : bool ) : if b : return " hello " else : return 0 } | ~ target " : test . foo " ~ expected { " :| typing . Union [ int , str ] " } ; | check_inference_results { | def foo ( ) : if 1 > 2 : x = 2 else : assert not True return x } | ~ target " : test . foo " ~ expected { " :| int " } ; | check_inference_results { | def foo ( ) : return ( " " , " " , " " , " " ) } | ~ target " : test . foo " ~ expected { " :| typing . Tuple [ str , . . . ] " } ; | check_inference_results { | def foo ( ) : return ( " " , " " , " " , 2 ) } | ~ target " : test . foo " ~ expected { " :| typing . Tuple [ str , str , str , int ] " } ; | check_inference_results { | def foo ( ) : def bar ( x : int ) -> str : return " " return bar } | ~ target " : test . foo " ~ expected { " :| typing . Callable [ [ int ] , str ] " } ; | check_inference_results { | def foo ( ) : def bar ( x : int , y : str ) -> bool : pass return [ bar ] } | ~ target " : test . foo " ~ expected { " :| typing . List [ typing . Callable [ [ int , str ] , bool ] ] " } ; | check_inference_results { | class Test ( object ) : def ret_self ( self ) : return self } | ~ target " : test . Test . ret_self " ~ expected { " :| test . Test " } ; | check_inference_results { | def foo ( a ) : x , _ , z = a . b ( ' ' ) : return z , x } | ~ target " : test . foo " ~ expected { :| null } ; | check_inference_results { | def foo ( x ) : return x , " hello " } | ~ target " : test . foo " ~ expected { :| null } ; | check_inference_results { | class A : @ abstractmethod def foo ( ) : pass } | ~ target " : test . A . foo " ~ expected { :| null } ; | check_inference_results { | def foo ( ) : return [ 1 ] } | ~ target " : test . foo " ~ expected { " :| typing . List [ int ] " } ; | check_inference_results { | def foo ( ) : return 1 } | ~ target " : test . foo " ~ expected { " :| int " } ; | check_inference_results { | def foo ( y : bool ) : x = { } if y : x [ " a " ] = 1 return x } | ~ target " : test . foo " ~ expected { " :| typing . Dict [ str , int ] " } ; | check_inference_results { | def foo ( ) : y = { } list = [ 1 , 2 , 3 ] for num in list : y [ " a " ] = num return y } | ~ target " : test . foo " ~ expected { " :| typing . Dict [ str , int ] " } ; | check_inference_results { | def foo ( ) : x = [ ] x . append ( " " ) x . append ( 1 ) return x } | ~ target " : test . foo " ~ expected { " :| typing . List [ typing . Union [ int , str ] ] " } ; | check_inference_results { | def foo ( ) : return [ ] } | ~ target " : test . foo " ~ expected { :| null } ; | check_inference_results { | def foo ( ) : return { } } | ~ target " : test . foo " ~ expected { :| null } ; | check_inference_results { | from typing import Any def foo ( x : Any ) : return { 1 + 1 : x } } | ~ target " : test . foo " ~ expected { :| null } ; | check_inference_results { | from typing import Any def foo ( x : Any ) : return { " " : x } } | ~ target " : test . foo " ~ expected { " :| typing . Dict [ str , typing . Any ] " } ; | ( )
let test_inferred_function_parameters context = let check_inference_results = check_inference_results ~ field_path [ " : define " ; " parameters " ] ~ context in let single_parameter ( ? name = " x " ) ? default type_ = Format . asprintf { | [ { " name " : " % s " , " annotation " : " % s " , " value " : % s , " index " : 0 } ] } | name type_ ( option_to_json default ) in let no_inferences = { | [ { " name " : " x " , " annotation " : null , " value " : null , " index " : 0 } ] } | in let no_inferences_with_default ~ default = Format . asprintf { | [ { " name " : " x " , " annotation " : null , " value " : " % s " , " index " : 0 } ] } | default in check_inference_results { | def foo ( x ) -> int : return x } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x ) -> int : y = x return y } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | from typing import Optional def foo ( x ) -> Optional [ str ] : return x } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . Optional [ str ] " ) ; check_inference_results { | def foo ( x : typing . Any ) -> None : x = 5 } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x = 5 ) -> int : return x } | ~ target " : test . foo " ~ expected ( : single_parameter ~ default " : 5 " " int " ) ; check_inference_results { | def foo ( x = 5 ) -> None : return } | ~ target " : test . foo " ~ expected ( : single_parameter ~ default " : 5 " " int " ) ; check_inference_results { | def foo ( x : typing . Any = 5 ) -> None : pass } | ~ target " : test . foo " ~ expected ( : single_parameter ~ default " : 5 " " int " ) ; check_inference_results { | def foo ( x = None ) -> None : x = 1 return } | ~ target " : test . foo " ~ expected ( : single_parameter ~ default " : None " " typing . Optional [ int ] " ) ; check_inference_results { | def foo ( x ) -> None : y = 1 x = y } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x ) -> int : y = 5 x = y return x } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x ) -> int : x = unknown ( ) return x } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( y ) -> int : z = y x = y return x } | ~ target " : test . foo " ~ expected ( : single_parameter ~ name " : y " " int " ) ; check_inference_results { | def foo ( x ) -> int : x = y y = z return z } | ~ target " : test . foo " ~ expected : no_inferences ; check_inference_results { | def foo ( x ) -> int : y += x return y } | ~ target " : test . foo " ~ expected ( : single_parameter ~ name " : x " " int " ) ; check_inference_results { | def foo ( x ) -> int : x += 1 return x } | ~ target " : test . foo " ~ expected ( : single_parameter ~ name " : x " " int " ) ; check_inference_results { | def foo ( x , y ) -> int : b = 5 a , b = x , y a += b return a } | ~ target " : test . foo " ~ expected : { | [ { " name " : " x " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " y " , " annotation " : " int " , " value " : null , " index " : 1 } ] } ; | check_inference_results { | def foo ( x ) -> typing . Tuple [ int , float ] : y = x z = x return ( y , z ) } | ~ target " : test . foo " ~ expected ( : single_parameter ~ name " : x " " int " ) ; check_inference_results { | def foo ( x ) -> typing . Tuple [ int , str ] : y = x z = x return ( y , z ) } | ~ target " : test . foo " ~ expected : no_inferences ; check_inference_results { | def foo ( x ) -> typing . Tuple [ int , float ] : z = y x = y return ( x , z ) } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x , y , z ) -> typing . Tuple [ typing . Tuple [ str , int ] , bool ] : return ( ( x , y ) , z ) } | ~ target " : test . foo " ~ expected : { | [ { " name " : " x " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " y " , " annotation " : null , " value " : null , " index " : 1 } , { " name " : " z " , " annotation " : " bool " , " value " : null , " index " : 2 } ] } ; | check_inference_results { | def foo ( x = None ) -> None : z = x + 1 } | ~ target " : test . foo " ~ expected ( : no_inferences_with_default ~ default " : None " ) ; check_inference_results { | def foo ( x ) -> None : x += 1 } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | from typing import Optional def foo ( x : Optional [ str ] ) : return x def bar ( x = None ) -> None : foo ( x ) } | ~ target " : test . bar " ~ expected ( : single_parameter ~ default " : None " " typing . Optional [ str ] " ) ; check_inference_results { | def takes_int ( input : int ) -> None : . . . def takes_str ( input : str ) -> None : . . . def foo ( x ) -> None : x = 1 takes_int ( x ) x = " string " takes_str ( x ) } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . Union [ int , str ] " ) ; check_inference_results { | def takes_int ( input : int ) -> None : . . . def takes_float ( input : float ) -> None : . . . def foo ( x ) -> None : takes_int ( x ) takes_float ( x ) } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def takes_int ( input : int ) -> None : . . . def takes_unknown ( input ) -> None : . . . def foo ( x ) -> None : takes_int ( x ) takes_unknown ( x ) } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( a : int , b : str ) -> None : pass def bar ( a , b ) -> None : foo ( b = b , a = a ) } | ~ target " : test . bar " ~ expected : { | [ { " name " : " a " , " annotation " : " int " , " value " : null , " index " : 0 } , { " name " : " b " , " annotation " : " str " , " value " : null , " index " : 1 } ] } ; | check_inference_results { | def format ( * args : object , ** kwargs : object ) -> str : . . . def foo ( a , b ) -> None : format ( a = a , b = b ) } | ~ target " : test . foo " ~ expected : { | [ { " name " : " a " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " b " , " annotation " : null , " value " : null , " index " : 1 } ] } ; | check_inference_results { | from typing import Any , Dict , Optional , TypeVar # copied from typeshed _T = TypeVar ( " _T " ) def deepcopy ( x : _T , memo : Optional [ Dict [ int , Any ] ] = . . . , _nil : Any = . . . ) -> _T : . . . def foo ( x ) : return deepcopy ( x ) } | ~ target " : test . foo " ~ expected : { | [ { " name " : " x " , " annotation " : null , " value " : null , " index " : 0 } ] } ; | check_inference_results { | def foo ( x ) -> None : if type ( x ) is int : return } | ~ target " : test . foo " ~ expected ( : single_parameter " int " ) ; check_inference_results { | def foo ( x ) -> None : if type ( x ) is int : return elif type ( x ) is str : return } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . Union [ int , str ] " ) ; check_inference_results { | def foo ( x = None ) -> None : if x : x = " " } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . Optional [ str ] " ~ default " : None " ) ; check_inference_results { | def takes_int ( input : int ) -> None : . . . def takes_str ( input : str ) -> None : . . . def ret_bool ( ) -> bool : . . . def foo ( x ) -> None : if ret_bool ( ) : takes_int ( x ) else : takes_str ( x ) } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . Union [ int , str ] " ) ; check_inference_results { | def foo ( x ) -> None : x = [ ] x . append ( 1 ) } | ~ target " : test . foo " ~ expected ( : single_parameter " typing . List [ int ] " ) ; check_inference_results { | from typing import Optional def foo ( x ) -> None : y : List [ Any ] = [ ] x = y } | ~ target " : test . foo " ~ expected : no_inferences ; ( )
let test_inferred_method_parameters context = let check_inference_results = check_inference_results ~ context ~ field_path [ " : define " ; " parameters " ] in let single_parameter_method type_ = Format . asprintf { | [ { " name " : " self " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " x " , " annotation " : % s , " value " : null , " index " : 1 } ] } | ( option_to_json type_ ) in let no_inferences = single_parameter_method None in check_inference_results { | class A : def foo ( self , x : int ) -> None : . . . class B ( A ) : def foo ( self , x ) -> None : return x } | ~ target " : test . B . foo " ~ expected ( : single_parameter_method ( Some " int " ) ) ; check_inference_results { | class A : def foo ( self , x : " A " ) -> " A " : . . . class B ( A ) : def foo ( self , x ) : return x } | ~ target " : test . B . foo " ~ expected ( : single_parameter_method ( Some " test . A " ) ) ; check_inference_results { | from typing import Any class A : def foo ( self , x : Any ) -> int : . . . class B ( A ) : def foo ( self , x ) : return x } | ~ target " : test . B . foo " ~ expected : no_inferences ; check_inference_results { | class A : def foo ( self , x : int , y : str , z : int ) -> int : . . . class B ( A ) : def foo ( self , x , y : str , z : int ) : return x } | ~ target " : test . B . foo " ~ expected : { | [ { " name " : " self " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " x " , " annotation " : " int " , " value " : null , " index " : 1 } , { " name " : " y " , " annotation " : null , " value " : null , " index " : 2 } , { " name " : " z " , " annotation " : null , " value " : null , " index " : 3 } ] } ; | check_inference_results { | class A : def foo ( self , x : int ) -> int : . . . class B ( A ) : def foo ( self , x : str ) -> str : return x } | ~ target " : test . B . foo " ~ expected : no_inferences ; check_inference_results { | class A : def foo ( self : " A " ) -> str : . . . class B ( A ) : def foo ( self ) : return x } | ~ target " : test . B . foo " ~ expected { :| [ { " name " : " self " , " annotation " : null , " value " : null , " index " : 0 } ] } ; | check_inference_results { | class A : def foo ( self , * args : str , ** kwargs : float ) -> int : . . . class B ( A ) : def foo ( self , * args , ** kwargs ) : return x } | ~ target " : test . B . foo " ~ expected : { | [ { " name " : " self " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " * args " , " annotation " : " str " , " value " : null , " index " : 1 } , { " name " : " ** kwargs " , " annotation " : " float " , " value " : null , " index " : 2 } ] } ; | check_inference_results { | from typing import TypeVar T = TypeVar ( " T " ) class A : def foo ( self , x : T ) -> T : . . . class B ( A ) : def foo ( self , x ) : return x } | ~ target " : test . B . foo " ~ expected : no_inferences ; check_inference_results { | class A : def foo ( self , x : int ) -> int : . . . class B ( A ) : def foo ( self , x ) : return x class C ( B ) : def foo ( self , x ) : return x + 1 } | ~ target " : test . C . foo " ~ expected : no_inferences ; ( )
let test_inferred_globals context = let check_inference_results = check_inference_results ~ context ~ field_path [ " : globals " ] in check_inference_results { | def foo ( ) -> int : return 1234 x = foo ( ) } | ~ target " : test . $ toplevel " ~ expected : { | [ { " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 4 } , " annotation " : " int " } ] } ; | check_inference_results { | x = 1 + 1 } | ~ target " : test . $ toplevel " ~ expected : { | [ { " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 2 } , " annotation " : " int " } ] } ; | check_inference_results { | x = unknown def foo ( ) -> int : return x } | ~ target " : test . $ toplevel " ~ expected { [ ] } ; :|| check_inference_results { | x = unknown def foo ( ) -> None : global x x = 1 } | ~ target " : test . $ toplevel " ~ expected { [ ] } ; :|| check_inference_results { | foo = [ ] } | ~ target " : test . $ toplevel " ~ expected { :| [ ] } ; | check_inference_results { | foo = None } | ~ target " : test . $ toplevel " ~ expected : { | [ { " name " : " foo " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 2 } , " annotation " : " None " } ] } ; | ( )
let test_inferred_attributes context = let check_inference_results = check_inference_results ~ context ~ field_path [ " : attributes " ] in check_inference_results { | def foo ( ) -> int : return 1 class Foo : x = foo ( ) } | ~ target " : test . Foo . $ class_toplevel " ~ expected : { | [ { " parent " : " test . Foo " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 5 } , " annotation " : " int " } ] } ; | check_inference_results { | class Foo : x = 1 + 1 } | ~ target " : test . Foo . $ class_toplevel " ~ expected : { | [ { " parent " : " test . Foo " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 3 } , " annotation " : " int " } ] } ; | check_inference_results { | class Foo : def __init__ ( self ) -> None : self . x = 1 + 1 } | ~ target " : test . Foo . __init__ " ~ expected : { | [ { " parent " : " test . Foo " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 4 } , " annotation " : " int " } ] } ; | check_inference_results { | class Foo : def __init__ ( self ) -> None : self . x = self . foo ( ) def foo ( self ) -> int : return 1 } | ~ target " : test . Foo . __init__ " ~ expected : { | [ { " parent " : " test . Foo " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 4 } , " annotation " : " int " } ] } ; | check_inference_results { | class Foo : x = unknown ( ) def test ( f : Foo ) -> None : f . x = 1 } | ~ target " : test . Foo . $ class_toplevel " ~ expected { [ ] } ; :|| check_inference_results { | class Foo : foo = None } | ~ target " : test . Foo . $ class_toplevel " ~ expected : { | [ { " parent " : " test . Foo " , " name " : " foo " , " location " : { " qualifier " : " test " , " path " : " test . py " , " line " : 3 } , " annotation " : " None " } ] } ; | ( )
let ( ) = " typeInferenceLocalTest " >::: [ " test_backward_resolution_handling " >:: test_backward_resolution_handling ; " test_should_analyze_define " >:: test_should_analyze_define ; " test_inferred_returns " >:: test_inferred_returns ; " test_inferred_function_parameters " >:: test_inferred_function_parameters ; " test_inferred_method_parameters " >:: test_inferred_method_parameters ; " test_inferred_globals " >:: test_inferred_globals ; " test_inferred_attributes " >:: test_inferred_attributes ; ] |> Test . run
type conversion_function = JavaAST . expression -> JavaAST . expression
type t = { ocaml_type : Path . t option ; java_type : JavaAST . type_ ; java_of_ocaml : conversion_function ; ocaml_of_java : conversion_function ; }
let make_simple ident = let path = Path . Pident ident in let name = Ident . name ident in let info = { ocaml_type = Some path ; java_type = JavaAST . Reference ( name , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( name , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; } in path , info
let type_int = { ocaml_type = Some Predef . path_int ; java_type = JavaAST . Long ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asLong " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createLong " , [ e ] e ) e ) e ; }
let type_int_boxed = { ocaml_type = Some Predef . path_int ; java_type = JavaAST . Reference ( " OCamlInt " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlInt " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_char = { ocaml_type = Some Predef . path_char ; java_type = JavaAST . Int ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asCastedInt " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createLong " , [ e ] e ) e ) e ; }
let type_char_boxed = { ocaml_type = Some Predef . path_char ; java_type = JavaAST . Reference ( " OCamlChar " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlChar " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_string = { ocaml_type = Some Predef . path_string ; java_type = JavaAST . Reference ( " String " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asString " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createString " , [ e ] e ) e ) e ; }
let type_string_boxed = { ocaml_type = Some Predef . path_string ; java_type = JavaAST . Reference ( " OCamlString " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlString " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_byte_array = { ocaml_type = Some Predef . path_string ; java_type = JavaAST . Array JavaAST . Byte ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " getBytesForModification " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createString " , [ e ] e ) e ) e ; }
let type_float = { ocaml_type = Some Predef . path_float ; java_type = JavaAST . Double ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asDouble " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createDouble " , [ e ] e ) e ) e ; }
let type_float_boxed = { ocaml_type = Some Predef . path_float ; java_type = JavaAST . Reference ( " OCamlFloat " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlFloat " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_bool = { ocaml_type = Some Predef . path_bool ; java_type = JavaAST . Boolean ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlWrappers " , " asBool " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " OCamlWrappers " , " createBool " , [ e ] e ) e ) e ; }
let type_bool_boxed = { ocaml_type = Some Predef . path_bool ; java_type = JavaAST . Reference ( " OCamlBool " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlBool " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_unit_boxed = { ocaml_type = Some Predef . path_unit ; java_type = JavaAST . Reference ( " OCamlUnit " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlUnit " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_nativeint = { ocaml_type = Some Predef . path_nativeint ; java_type = JavaAST . Long ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asNativeInt " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createNativeInt " , [ e ] e ) e ) e ; }
let type_nativeint_boxed = { ocaml_type = Some Predef . path_nativeint ; java_type = JavaAST . Reference ( " OCamlNativeInt " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlNativeInt " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_int32 = { ocaml_type = Some Predef . path_int32 ; java_type = JavaAST . Int ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asInt32 " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createInt32 " , [ e ] e ) e ) e ; }
let type_int32_boxed = { ocaml_type = Some Predef . path_int32 ; java_type = JavaAST . Reference ( " OCamlInt32 " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlInt32 " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_int64 = { ocaml_type = Some Predef . path_int64 ; java_type = JavaAST . Long ; java_of_ocaml = ( fun e -> JavaAST . Call ( e , " asInt64 " , [ ] ) ) ; ocaml_of_java = ( fun e -> JavaAST . Static_call ( " Value " , " createInt64 " , [ e ] e ) e ) e ; }
let type_int64_boxed = { ocaml_type = Some Predef . path_int64 ; java_type = JavaAST . Reference ( " OCamlInt64 " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlInt64 " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_array = { ocaml_type = Some Predef . path_array ; java_type = JavaAST . Reference ( " OCamlArray " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlArray " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_list = { ocaml_type = Some Predef . path_list ; java_type = JavaAST . Reference ( " OCamlList " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlList " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_option = { ocaml_type = Some Predef . path_option ; java_type = JavaAST . Reference ( " OCamlOption " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlOption " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_lazy = { ocaml_type = Some Predef . path_lazy_t ; java_type = JavaAST . Reference ( " OCamlLazy " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlLazy " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_ref = let path_pervasives = Path . Pident ( Ident . create_persistent " Pervasives ) " in let path = Path . Pdot ( path_pervasives , " ref " , 0 ) 0 in { ocaml_type = Some path ; java_type = JavaAST . Reference ( " OCamlRef " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlRef " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_in_channel = let path_pervasives = Path . Pident ( Ident . create_persistent " Pervasives ) " in let path = Path . Pdot ( path_pervasives , " in_channel " , 0 ) 0 in { ocaml_type = Some path ; java_type = JavaAST . Reference ( " OCamlInChannel " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlInChannel " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_out_channel = let path_pervasives = Path . Pident ( Ident . create_persistent " Pervasives ) " in let path = Path . Pdot ( path_pervasives , " out_channel " , 0 ) 0 in { ocaml_type = Some path ; java_type = JavaAST . Reference ( " OCamlOutChannel " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlOutChannel " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let type_exn = { ocaml_type = Some Predef . path_exn ; java_type = JavaAST . Reference ( " OCamlExn " , [ ] ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlExn " , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; }
let always_predefined_types = [ type_array ; type_list ; type_option ; type_lazy ; type_ref ; type_in_channel ; type_out_channel ; type_exn ; ]
let boxed_only_predefined_types = [ type_int_boxed ; type_char_boxed ; type_float_boxed ; type_bool_boxed ; type_unit_boxed ; type_nativeint_boxed ; type_int32_boxed ; type_int64_boxed ; ]
let unboxed_only_predefined_types = [ type_int ; type_char ; type_float ; type_bool ; type_nativeint ; type_int32 ; type_int64 ; ]
let boxed_predefined_types = type_string_boxed :: ( boxed_only_predefined_types @ always_predefined_types ) always_predefined_types
let unboxed_predefined_types = ref None
let predefined_types boxed = if boxed then boxed_predefined_types else begin match ! unboxed_predefined_types with | Some cache -> cache | None -> let res = ( match ! Args . string_mapping with | Args . Java_string -> type_string | Args . OCamlString -> type_string_boxed | Args . Byte_array -> type_byte_array ) type_byte_array :: ( unboxed_only_predefined_types @ always_predefined_types ) always_predefined_types in unboxed_predefined_types := Some res ; res end
module HashedPath = struct type t = Path . t let equal x y = Path . same x y let rec hash = function | Path . Pident id -> Hashtbl . hash ( Ident . name id ) id | Path . Pdot ( p , s , _ ) _ -> ( hash p ) p + ( Hashtbl . hash s ) s | Path . Papply ( p1 , p2 ) p2 -> ( hash p1 ) p1 + ( hash p2 ) p2 end
module Definitions = Hashtbl . Make ( HashedPath ) HashedPath
type definitions = ( TypeInfo . t * bool ) bool Definitions . t
let defined : definitions = Definitions . create 17
let locally_defined : definitions = Definitions . create 17
let is_defined_and_doesnt_expand path = try snd ( Definitions . find defined path ) path with Not_found -> try snd ( Definitions . find locally_defined path ) path with _ -> false
let add_local ident dont_expand = let path , info = TypeInfo . make_simple ident in Definitions . add locally_defined path ( info , dont_expand ) dont_expand
let promote modname = let modpath = Path . Pident ( Ident . create_persistent modname ) modname in Definitions . iter ( fun path ( info , dont_expand ) dont_expand -> let otyp = Path . Pdot ( modpath , Path . name path , 0 ) 0 in let jtyp , name = match info . TypeInfo . java_type with | JavaAST . Reference ( cn , l ) l -> let class_name = Args . class_of_module modname in let name = class_name ^ " . " ^ ( JavaAST . checked_name cn ) cn in JavaAST . Reference ( name , l ) l , name | x -> x , " class " in let info = { TypeInfo . ocaml_type = Some otyp ; java_type = jtyp ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( name , " wrap " , [ e ] e ) e ) e ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; } in Definitions . add defined otyp ( info , dont_expand ) dont_expand ) dont_expand locally_defined ; Definitions . clear locally_defined
let find_predefined boxed path = List . find ( fun x -> match x . TypeInfo . ocaml_type with | Some p -> Path . same p path | None -> false ) false ( TypeInfo . predefined_types boxed ) boxed
let find_defined path = try try fst ( Definitions . find defined path ) path with Not_found -> fst ( Definitions . find locally_defined path ) path with Not_found -> ( match path with | Path . Pident id -> snd ( TypeInfo . make_simple id ) id | _ -> raise Not_found ) Not_found
let find_from_constructor boxed path = try find_predefined boxed path with Not_found -> find_defined path
let rec make_wrapper generics i = match i with | JavaAST . Reference ( cn , l ) l -> if TypeParametersTable . mem cn generics then begin match TypeParametersTable . find cn generics with | TypeParametersTable . Parameter path -> let path = List . rev path in begin match path with | param :: accesses -> let base = JavaAST . Identifier ( Printf . sprintf " p % d " param ) param in List . fold_left ( fun acc elem -> JavaAST . Call ( acc , " getWrapper " , [ JavaAST . Int_literal ( Int32 . of_int elem ) elem ] elem ) elem ) elem base accesses | [ ] -> assert false end | TypeParametersTable . Field id -> JavaAST . Identifier id | TypeParametersTable . Nowhere -> JavaAST . Identifier ( Printf . sprintf " w % s " cn ) cn end else JavaAST . Static_call ( cn , " wrapper " , List . map ( make_wrapper generics ) generics l ) l | _ -> assert false
let augment_with_type_parameters generics res l = let l ' ' = List . map ( fun x -> x . TypeInfo . java_type ) java_type l in let jt = match res . TypeInfo . java_type with | JavaAST . Reference ( cn , [ ] ) -> JavaAST . Reference ( cn , l ' ' ) l ' ' | _ -> assert false in let joo e = let l = List . map ( fun i -> make_wrapper generics i . TypeInfo . java_type ) java_type l in match res . TypeInfo . java_of_ocaml e with | JavaAST . Static_call ( cn , " wrap " , [ e ] e ) e -> let tmp = JavaAST . Static_call ( cn , " wrap " , l @ [ e ] e ) e in tmp | _ -> assert false in { res with TypeInfo . java_type = jt ; java_of_ocaml = joo }
let rec string_of_type_expr te = string_of_type_desc te . Types . desc let open Types in match td with | Tvar None -> " ' " ? | Tvar ( Some s ) s -> " ' " ^ s | Tarrow ( _ , te1 , te2 , _ ) _ -> ( string_of_type_expr te1 ) te1 ^ " -> " ^ ( string_of_type_expr te2 ) te2 | Ttuple l -> string_of_type_expr_list l | Tconstr ( p , [ ] , _ ) _ -> Path . name p | Tconstr ( p , l , _ ) _ -> ( string_of_type_expr_list l ) l ^ " " ^ ( Path . name p ) p | Tobject _ -> " < . . " > | Tfield ( s , _ , _ , _ ) _ -> s | Tnil -> " nil " | Tlink te -> string_of_type_expr te | Tsubst te -> string_of_type_expr te | Tvariant { row_fields ; _ } -> let string_of_row_field ( lbl , _ ) _ = lbl in [ " " ^ ( String . concat " | " ( List . map string_of_row_field row_fields ) row_fields ) row_fields ^ ] " " | Tunivar None -> " ' " ? | Tunivar ( Some s ) s -> " ' " ^ s | Tpoly ( te , tl ) tl -> ( string_of_type_expr te ) te ^ " . " ^ ( string_of_type_expr_list tl ) tl | Tpackage ( p , _ , _ ) _ -> ( " module " ^ ( Path . name p ) p ^ ) " " String . concat " * " ( List . map string_of_type_expr l ) l
let rec find ( ? generics = TypeParametersTable . empty ) empty boxed t = let open Types in match t . desc with | Tlink t ' -> find ~ generics boxed t ' | Tobject ( _ , { contents = Some ( path , l ) l } ) | Tconstr ( path , l , _ ) _ when is_defined_and_doesnt_expand path -> let res = find_defined path in let l = List . map ( find ~ generics true ) true l in augment_with_type_parameters generics res l | _ -> let t = try Ctype . full_expand ! State . environment ( Ctype . repr t ) t with _ -> t in match t . desc with | Tlink t ' -> find ~ generics boxed t ' | Tvar ( Some id ) id when TypeParametersTable . mem id generics -> { TypeInfo . ocaml_type = None ; java_type = JavaAST . Reference ( id , [ ] ) ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( Printf . sprintf " w % s " id , " wrap " , [ e ] e ) e ) e ; } | Tvar _ | Tunivar _ -> { TypeInfo . ocaml_type = None ; java_type = JavaAST . Reference ( " OCamlValue " , [ ] ) ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " value " , [ ] ) ) ; java_of_ocaml = ( fun e -> JavaAST . Static_call ( " OCamlValue " , " wrap " , [ e ] e ) e ) e ; } | Ttuple l -> if ( List . length l ) l > 8 then Wrap_common ( . fail ( Tuple_is_too_large ( List . length l ) l ) l ) l ; let class_name = Printf . sprintf " OCamlTuple % d " ( List . length l ) l in let l = List . map ( find ~ generics true ) true l in let java_of_ocaml e = let l = List . map ( fun i -> make_wrapper generics i . TypeInfo . java_type ) java_type l in let tmp = JavaAST . Static_call ( class_name , " wrap " , l @ [ e ] e ) e in if l = [ ] then tmp else JavaAST . Cast ( JavaAST . Reference ( class_name , [ ] ) , tmp ) tmp in let ocaml_of_java e = JavaAST . Call ( e , " value " , [ ] ) in let java_type = JavaAST . Reference ( class_name , ( List . map ( fun x -> x . TypeInfo . java_type ) java_type l ) l ) l in { TypeInfo . ocaml_type = None ; java_type ; java_of_ocaml ; ocaml_of_java ; } | Tconstr ( path , [ ] , _ ) _ -> find_from_constructor boxed path | Tconstr ( path , l , _ ) _ -> let res = find_from_constructor boxed path in let l = List . map ( find ~ generics true ) true l in augment_with_type_parameters generics res l | Tarrow _ -> let return , parameters = Wrap_common . flatten_arrow_not_tuple t in let return_type = find ~ generics true return in let parameter_types = List . map ( find ~ generics true ) true parameters in let wrappers = List . map ( fun param -> let w = make_wrapper generics param . TypeInfo . java_type in let c = JavaAST . Reference ( " Wrapper " , [ param . TypeInfo . java_type ] java_type ) java_type in JavaAST . Cast ( c , w ) w ) w parameter_types in let class_name = match List . length parameters with | 1 -> " OCamlFunction " | ( 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ) 10 as x -> Printf . sprintf " OCamlFunction % d " x | n -> Wrap_common ( . fail ( Function_arity_is_too_large n ) n ) n in let java_type = JavaAST . Reference ( class_name , ( ( List . map ( fun x -> x . TypeInfo . java_type ) java_type parameter_types ) parameter_types @ [ return_type . TypeInfo . java_type ] java_type ) java_type ) java_type in let wrap e = let rec mk_wrapper java_type = match java_type with | JavaAST . Reference ( cn , l ) l -> JavaAST . Static_call ( cn , " wrapper " , ( List . map mk_wrapper l ) l ) l | _ -> assert false in let wrappers = List . map ( fun param -> mk_wrapper param . TypeInfo . java_type ) java_type ( parameter_types @ [ return_type ] return_type ) return_type in let res = JavaAST . Static_call ( class_name , " wrap " , wrappers @ [ e ] e ) e in JavaAST . Cast ( java_type , res ) res in { TypeInfo . ocaml_type = None ; java_type = java_type ; java_of_ocaml = wrap ; ocaml_of_java = ( fun e -> JavaAST . Call ( e , " getClosure " , wrappers ) wrappers ) wrappers ; } | _ -> Wrap_common ( . fail ( Cannot_map_type ( string_of_type_expr t ) t ) t ) t
let find ( ? generics = TypeParametersTable . empty ) empty boxed t = try find ~ generics boxed t with Not_found -> Wrap_common ( . fail ( Cannot_find_type ( string_of_type_expr t ) t ) t ) t
module Sig_component_kind = struct type t = | Value | Type | Module | Module_type | Extension_constructor | Class | Class_type let to_string = function | Value -> " value " | Type -> " type " | Module -> " module " | Module_type -> " module type " | Extension_constructor -> " extension constructor " | Class -> " class " | Class_type -> " class type " let can_appear_in_types = function | Value | Extension_constructor -> false | Type | Module | Module_type | Class | Class_type -> true end
type hiding_error = | Illegal_shadowing of { shadowed_item_id : Ident . t ; shadowed_item_kind : Sig_component_kind . t ; shadowed_item_loc : Location . t ; shadower_id : Ident . t ; user_id : Ident . t ; user_kind : Sig_component_kind . t ; user_loc : Location . t ; } | Appears_in_signature of { opened_item_id : Ident . t ; opened_item_kind : Sig_component_kind . t ; user_id : Ident . t ; user_kind : Sig_component_kind . t ; user_loc : Location . t ; }
type error = Cannot_apply of module_type | Not_included of Includemod . error list | Cannot_eliminate_dependency of module_type | Signature_expected | Structure_expected of module_type | With_no_component of Longident . t | With_mismatch of Longident . t * Includemod . error list | With_makes_applicative_functor_ill_typed of Longident . t * Path . t * Includemod . error list | With_changes_module_alias of Longident . t * Ident . t * Path . t | With_cannot_remove_constrained_type | Repeated_name of Sig_component_kind . t * string | Non_generalizable of type_expr | Non_generalizable_class of Ident . t * class_declaration | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | Not_a_packed_module of type_expr | Incomplete_packed_module of type_expr | Scoping_pack of Longident . t * type_expr | Recursive_module_require_explicit_type | Apply_generative | Cannot_scrape_alias of Path . t | Badly_formed_signature of string * Typedecl . error | Cannot_hide_id of hiding_error | Invalid_type_subst_rhs
let rec path_concat head p = match p with Pident tail -> Pdot ( Pident head , Ident . name tail ) | Pdot ( pre , s ) -> Pdot ( path_concat head pre , s ) | Papply _ -> assert false
let extract_sig env loc mty = match Env . scrape_alias env mty with Mty_signature sg -> sg | Mty_alias path -> raise ( Error ( loc , env , Cannot_scrape_alias path ) ) | _ -> raise ( Error ( loc , env , Signature_expected ) )
let extract_sig_open env loc mty = match Env . scrape_alias env mty with Mty_signature sg -> sg | Mty_alias path -> raise ( Error ( loc , env , Cannot_scrape_alias path ) ) | mty -> raise ( Error ( loc , env , Structure_expected mty ) )
let type_open_ ? used_slot ? toplevel ovf env loc lid = let path = Env . lookup_module_path ~ load : true ~ loc : lid . loc lid . txt env in match Env . open_signature ~ loc ? used_slot ? toplevel ovf path env with | Some env -> path , env | None -> let md = Env . find_module path env in ignore ( extract_sig_open env lid . loc md . md_type ) ; assert false
let initial_env ~ loc ~ safe_string ~ initially_opened_module ~ open_implicit_modules = let env = if safe_string then Env . initial_safe_string else Env . initial_unsafe_string in let open_module env m = let open Asttypes in let lid = { loc ; txt = Longident . parse m } in snd ( type_open_ Override env lid . loc lid ) in let add_units env units = String . Set . fold ( fun name env -> Env . add_persistent_structure ( Ident . create_persistent name ) env ) units env in let units = List . rev_map Env . persistent_structures_of_dir ( Load_path . get ( ) ) in let env , units = match initially_opened_module with | None -> ( env , units ) | Some m -> let rec loop before after = match after with | [ ] -> None | units :: after -> if String . Set . mem m units then Some ( units , List . rev_append before after ) else loop ( units :: before ) after in let env , units = match loop [ ] units with | None -> ( env , units ) | Some ( units_containing_m , other_units ) -> ( add_units env units_containing_m , other_units ) in ( open_module env m , units ) in let env = List . fold_left add_units env units in List . fold_left open_module env open_implicit_modules
let type_open_descr ? used_slot ? toplevel env sod = let ( path , newenv ) = Builtin_attributes . warning_scope sod . popen_attributes ( fun ( ) -> type_open_ ? used_slot ? toplevel sod . popen_override env sod . popen_loc sod . popen_expr ) in let od = { open_expr = ( path , sod . popen_expr ) ; open_bound_items = [ ] ; open_override = sod . popen_override ; open_env = newenv ; open_attributes = sod . popen_attributes ; open_loc = sod . popen_loc ; } in ( od , newenv )
let rm node = Stypes . record ( Stypes . Ti_mod node ) ; node
let type_module_type_of_fwd : ( Env . t -> Parsetree . module_expr -> Typedtree . module_expr * Types . module_type ) ref = ref ( fun _env _m -> assert false )
let check_recmod_typedecls env decls = let recmod_ids = List . map fst decls in List . iter ( fun ( id , md ) -> List . iter ( fun path -> Typedecl . check_recmod_typedecl env md . Types . md_loc recmod_ids path ( Env . find_type path env ) ) ( Mtype . type_paths env ( Pident id ) md . Types . md_type ) ) decls
let rec add_rec_types env = function Sig_type ( id , decl , Trec_next , _ ) :: rem -> add_rec_types ( Env . add_type ~ check : true id decl env ) rem | _ -> env
let check_type_decl env loc id row_id newdecl decl rs rem = let env = Env . add_type ~ check : true id newdecl env in let env = match row_id with | None -> env | Some id -> Env . add_type ~ check : false id newdecl env in let env = if rs = Trec_not then env else add_rec_types env rem in Includemod . type_declarations ~ loc env id newdecl decl ; Typedecl . check_coherence env loc ( Path . Pident id ) newdecl
let update_rec_next rs rem = match rs with Trec_next -> rem | Trec_first | Trec_not -> match rem with Sig_type ( id , decl , Trec_next , priv ) :: rem -> Sig_type ( id , decl , rs , priv ) :: rem | Sig_module ( id , pres , mty , Trec_next , priv ) :: rem -> Sig_module ( id , pres , mty , rs , priv ) :: rem | _ -> rem
let make_variance p n i = let open Variance in set May_pos p ( set May_neg n ( set May_weak n ( set Inj i null ) ) )
let rec iter_path_apply p ~ f = match p with | Pident _ -> ( ) | Pdot ( p , _ ) -> iter_path_apply p ~ f | Papply ( p1 , p2 ) -> iter_path_apply p1 ~ f ; iter_path_apply p2 ~ f ; f p1 p2
let path_is_strict_prefix = let rec list_is_strict_prefix l ~ prefix = match l , prefix with | [ ] , [ ] -> false | _ :: _ , [ ] -> true | [ ] , _ :: _ -> false | s1 :: t1 , s2 :: t2 -> String . equal s1 s2 && list_is_strict_prefix t1 ~ prefix : t2 in fun path ~ prefix -> match Path . flatten path , Path . flatten prefix with | ` Contains_apply , _ | _ , ` Contains_apply -> false | ` Ok ( ident1 , l1 ) , ` Ok ( ident2 , l2 ) -> Ident . same ident1 ident2 && list_is_strict_prefix l1 ~ prefix : l2
let iterator_with_env env = let env = ref ( lazy env ) in let super = Btype . type_iterators in env , { super with Btype . it_signature = ( fun self sg -> let env_before = ! env in env := lazy ( Env . add_signature sg ( Lazy . force env_before ) ) ; super . Btype . it_signature self sg ; env := env_before ) ; Btype . it_module_type = ( fun self -> function | Mty_functor ( param , mty_body ) -> let env_before = ! env in begin match param with | Unit -> ( ) | Named ( param , mty_arg ) -> self . Btype . it_module_type self mty_arg ; match param with | None -> ( ) | Some id -> env := lazy ( Env . add_module ~ arg : true id Mp_present mty_arg ( Lazy . force env_before ) ) end ; self . Btype . it_module_type self mty_body ; env := env_before ; | mty -> super . Btype . it_module_type self mty ) }
let retype_applicative_functor_type ~ loc env funct arg = let mty_functor = ( Env . find_module funct env ) . md_type in let mty_arg = ( Env . find_module arg env ) . md_type in let mty_param = match Env . scrape_alias env mty_functor with | Mty_functor ( Named ( _ , mty_param ) , _ ) -> mty_param | _ -> assert false in Includemod . check_modtype_inclusion ~ loc env mty_arg arg mty_param
let check_usage_of_path_of_substituted_item paths env signature ~ loc ~ lid = let iterator = let env , super = iterator_with_env env in { super with Btype . it_signature_item = ( fun self -> function | Sig_module ( id , _ , { md_type = Mty_alias aliased_path ; _ } , _ , _ ) when List . exists ( fun path -> path_is_strict_prefix path ~ prefix : aliased_path ) paths -> let e = With_changes_module_alias ( lid . txt , id , aliased_path ) in raise ( Error ( loc , Lazy . force ! env , e ) ) | sig_item -> super . Btype . it_signature_item self sig_item ) ; Btype . it_path = ( fun referenced_path -> iter_path_apply referenced_path ~ f ( : fun funct arg -> if List . exists ( fun path -> path_is_strict_prefix path ~ prefix : arg ) paths then let env = Lazy . force ! env in try retype_applicative_functor_type ~ loc env funct arg with Includemod . Error explanation -> raise ( Error ( loc , env , With_makes_applicative_functor_ill_typed ( lid . txt , referenced_path , explanation ) ) ) ) ) ; } in iterator . Btype . it_signature iterator signature ; Btype . unmark_iterators . Btype . it_signature Btype . unmark_iterators signature
let rec extract_next_modules = function | Sig_module ( id , _ , mty , Trec_next , _ ) :: rem -> let ( id_mty_l , rem ) = extract_next_modules rem in ( ( id , mty ) :: id_mty_l , rem ) | sg -> ( [ ] , sg )
let check_well_formed_module env loc context mty = let open Btype in let iterator = let rec check_signature env = function | [ ] -> ( ) | Sig_module ( id , _ , mty , Trec_first , _ ) :: rem -> let ( id_mty_l , rem ) = extract_next_modules rem in begin try check_recmod_typedecls ( Lazy . force env ) ( ( id , mty ) :: id_mty_l ) with Typedecl . Error ( _ , err ) -> raise ( Error ( loc , Lazy . force env , Badly_formed_signature ( context , err ) ) ) end ; check_signature env rem | _ :: rem -> check_signature env rem in let env , super = iterator_with_env env in { super with it_type_expr = ( fun _self _ty -> ( ) ) ; it_signature = ( fun self sg -> let env_before = ! env in let env = lazy ( Env . add_signature sg ( Lazy . force env_before ) ) in check_signature env sg ; super . it_signature self sg ) ; } in iterator . it_module_type iterator mty
let ( ) = Env . check_well_formed_module := check_well_formed_module
let type_decl_is_alias sdecl = match sdecl . ptype_manifest with | Some { ptyp_desc = Ptyp_constr ( lid , stl ) } when List . length stl = List . length sdecl . ptype_params -> begin match List . iter2 ( fun x ( y , _ ) -> match x , y with { ptyp_desc = Ptyp_var sx } , { ptyp_desc = Ptyp_var sy } when sx = sy -> ( ) | _ , _ -> raise Exit ) stl sdecl . ptype_params ; with | exception Exit -> None | ( ) -> Some lid end | _ -> None ; ;
let params_are_constrained = let rec loop = function | [ ] -> false | hd :: tl -> match ( Btype . repr hd ) . desc with | Tvar _ -> List . memq hd tl || loop tl | _ -> true in loop ; ;
let merge_constraint initial_env remove_aliases loc sg constr = let lid = match constr with | Pwith_type ( lid , _ ) | Pwith_module ( lid , _ ) | Pwith_typesubst ( lid , _ ) | Pwith_modsubst ( lid , _ ) -> lid in let destructive_substitution = match constr with | Pwith_type _ | Pwith_module _ -> false | Pwith_typesubst _ | Pwith_modsubst _ -> true in let real_ids = ref [ ] in let rec merge env sg namelist row_id = match ( sg , namelist , constr ) with ( [ ] , _ , _ ) -> raise ( Error ( loc , env , With_no_component lid . txt ) ) | ( Sig_type ( id , decl , rs , priv ) :: rem , [ s ] , Pwith_type ( _ , ( { ptype_kind = Ptype_abstract } as sdecl ) ) ) when Ident . name id = s && Typedecl . is_fixed_type sdecl -> let decl_row = { type_params = List . map ( fun _ -> Btype . newgenvar ( ) ) sdecl . ptype_params ; type_arity = List . length sdecl . ptype_params ; type_kind = Type_abstract ; type_private = Private ; type_manifest = None ; type_variance = List . map ( fun ( _ , v ) -> let ( c , n ) = match v with | Covariant -> true , false | Contravariant -> false , true | Invariant -> false , false in make_variance ( not n ) ( not c ) false ) sdecl . ptype_params ; type_loc = sdecl . ptype_loc ; type_is_newtype = false ; type_expansion_scope = Btype . lowest_level ; type_attributes = [ ] ; type_immediate = Unknown ; type_unboxed = unboxed_false_default_false ; } and id_row = Ident . create_local ( s " ^# row " ) in let initial_env = Env . add_type ~ check : false id_row decl_row initial_env in let tdecl = Typedecl . transl_with_constraint initial_env id ( Some ( Pident id_row ) ) decl sdecl in let newdecl = tdecl . typ_type in check_type_decl env sdecl . ptype_loc id row_id newdecl decl rs rem ; let decl_row = { decl_row with type_params = newdecl . type_params } in let rs ' = if rs = Trec_first then Trec_not else rs in ( Pident id , lid , Twith_type tdecl ) , Sig_type ( id_row , decl_row , rs ' , priv ) :: Sig_type ( id , newdecl , rs , priv ) :: rem | ( Sig_type ( id , decl , rs , priv ) :: rem , [ s ] , Pwith_type ( _ , sdecl ) ) when Ident . name id = s -> let tdecl = Typedecl . transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl . typ_type in check_type_decl env sdecl . ptype_loc id row_id newdecl decl rs rem ; ( Pident id , lid , Twith_type tdecl ) , Sig_type ( id , newdecl , rs , priv ) :: rem | ( Sig_type ( id , _ , _ , _ ) :: rem , [ s ] , ( Pwith_type _ | Pwith_typesubst _ ) ) when Ident . name id = s ^ " # row " -> merge env rem namelist ( Some id ) | ( Sig_type ( id , decl , rs , _priv ) :: rem , [ s ] , Pwith_typesubst ( _ , sdecl ) ) when Ident . name id = s -> let tdecl = Typedecl . transl_with_constraint initial_env id None decl sdecl in let newdecl = tdecl . typ_type in check_type_decl env sdecl . ptype_loc id row_id newdecl decl rs rem ; real_ids := [ Pident id ] ; ( Pident id , lid , Twith_typesubst tdecl ) , update_rec_next rs rem | ( Sig_module ( id , pres , md , rs , priv ) :: rem , [ s ] , Pwith_module ( _ , lid ' ) ) when Ident . name id = s -> let path , md ' = Env . lookup_module ~ loc lid ' . txt initial_env in let mty = md ' . md_type in let mty = Mtype . scrape_for_type_of ~ remove_aliases env mty in let md ' ' = { md ' with md_type = mty } in let newmd = Mtype . strengthen_decl ~ aliasable : false env md ' ' path in ignore ( Includemod . modtypes ~ loc env newmd . md_type md . md_type ) ; ( Pident id , lid , Twith_module ( path , lid ' ) ) , Sig_module ( id , pres , newmd , rs , priv ) :: rem | ( Sig_module ( id , _ , md , rs , _ ) :: rem , [ s ] , Pwith_modsubst ( _ , lid ' ) ) when Ident . name id = s -> let path , md ' = Env . lookup_module ~ loc lid ' . txt initial_env in let aliasable = not ( Env . is_functor_arg path env ) in let newmd = Mtype . strengthen_decl ~ aliasable env md ' path in ignore ( Includemod . modtypes ~ loc env newmd . md_type md . md_type ) ; real_ids := [ Pident id ] ; ( Pident id , lid , Twith_modsubst ( path , lid ' ) ) , update_rec_next rs rem | ( Sig_module ( id , _ , ( { md_type = Mty_alias _ } as md ) , _ , _ ) as item :: rem , s :: namelist , ( Pwith_module _ | Pwith_type _ ) ) when Ident . name id = s -> let ( ( path , _ , tcstr ) , _ ) = merge env ( extract_sig env loc md . md_type ) namelist None in let path = path_concat id path in real_ids := path :: ! real_ids ; ( path , lid , tcstr ) , item :: rem | ( Sig_module ( id , _ , md , rs , priv ) :: rem , s :: namelist , _ ) when Ident . name id = s -> let ( ( path , _path_loc , tcstr ) , newsg ) = merge env ( extract_sig env loc md . md_type ) namelist None in let path = path_concat id path in real_ids := path :: ! real_ids ; let newmd = { md with md_type = Mty_signature newsg } in let item = Sig_module ( id , Mp_present , newmd , rs , priv ) in ( path , lid , tcstr ) , item :: rem | ( item :: rem , _ , _ ) -> let ( cstr , items ) = merge ( Env . add_item item env ) rem namelist row_id in cstr , item :: items in try let names = Longident . flatten lid . txt in let ( tcstr , sg ) = merge initial_env sg names None in if destructive_substitution then ( match List . rev ! real_ids with | [ ] -> assert false | last :: rest -> assert ( match last with Pident _ -> true | _ -> false ) ; match rest with | [ ] -> ( ) | _ :: _ -> check_usage_of_path_of_substituted_item rest initial_env sg ~ loc ~ lid ; ) ; let sg = match tcstr with | ( _ , _ , Twith_typesubst tdecl ) -> let how_to_extend_subst = let sdecl = match constr with | Pwith_typesubst ( _ , sdecl ) -> sdecl | _ -> assert false in match type_decl_is_alias sdecl with | Some lid -> let replacement , _ = try Env . find_type_by_name lid . txt initial_env with Not_found -> assert false in fun s path -> Subst . add_type_path path replacement s | None -> let body = Option . get tdecl . typ_type . type_manifest in let params = tdecl . typ_type . type_params in if params_are_constrained params then raise ( Error ( loc , initial_env , With_cannot_remove_constrained_type ) ) ; fun s path -> Subst . add_type_function path ~ params ~ body s in let sub = List . fold_left how_to_extend_subst Subst . identity ! real_ids in Subst . signature Make_local sub sg | ( _ , _ , Twith_modsubst ( real_path , _ ) ) -> let sub = List . fold_left ( fun s path -> Subst . add_module_path path real_path s ) Subst . identity ! real_ids in Subst . signature Make_local sub sg | _ -> sg in check_well_formed_module initial_env loc " this instantiated signature " ( Mty_signature sg ) ; ( tcstr , sg ) with Includemod . Error explanation -> raise ( Error ( loc , initial_env , With_mismatch ( lid . txt , explanation ) ) )
let map_rec fn decls rem = match decls with | [ ] -> rem | d1 :: dl -> fn Trec_first d1 :: map_end ( fn Trec_next ) dl rem
let map_rec_type ~ rec_flag fn decls rem = match decls with | [ ] -> rem | d1 :: dl -> let first = match rec_flag with | Recursive -> Trec_first | Nonrecursive -> Trec_not in fn first d1 :: map_end ( fn Trec_next ) dl rem
let rec map_rec_type_with_row_types ~ rec_flag fn decls rem = match decls with | [ ] -> rem | d1 :: dl -> if Btype . is_row_name ( Ident . name d1 . typ_id ) then fn Trec_not d1 :: map_rec_type_with_row_types ~ rec_flag fn dl rem else map_rec_type ~ rec_flag fn decls rem
let map_ext fn exts rem = match exts with | [ ] -> rem | d1 :: dl -> fn Text_first d1 :: map_end ( fn Text_next ) dl rem
let rec approx_modtype env smty = match smty . pmty_desc with Pmty_ident lid -> let ( path , _info ) = Env . lookup_modtype ~ use : false ~ loc : smty . pmty_loc lid . txt env in Mty_ident path | Pmty_alias lid -> let path = Env . lookup_module_path ~ use : false ~ load : false ~ loc : smty . pmty_loc lid . txt env in Mty_alias ( path ) | Pmty_signature ssg -> Mty_signature ( approx_sig env ssg ) | Pmty_functor ( param , sres ) -> let ( param , newenv ) = match param with | Unit -> Types . Unit , env | Named ( param , sarg ) -> let arg = approx_modtype env sarg in match param . txt with | None -> Types . Named ( None , arg ) , env | Some name -> let rarg = Mtype . scrape_for_functor_arg env arg in let scope = Ctype . create_scope ( ) in let ( id , newenv ) = Env . enter_module ~ scope ~ arg : true name Mp_present rarg env in Types . Named ( Some id , arg ) , newenv in let res = approx_modtype newenv sres in Mty_functor ( param , res ) | Pmty_with ( sbody , constraints ) -> let body = approx_modtype env sbody in List . iter ( fun sdecl -> match sdecl with | Pwith_type _ -> ( ) | Pwith_typesubst _ -> ( ) | Pwith_module ( _ , lid ' ) -> ignore ( Env . lookup_module ~ use : false ~ loc : lid ' . loc lid ' . txt env ) | Pwith_modsubst ( _ , lid ' ) -> ignore ( Env . lookup_module ~ use : false ~ loc : lid ' . loc lid ' . txt env ) ) constraints ; body | Pmty_typeof smod -> let ( _ , mty ) = ! type_module_type_of_fwd env smod in mty | Pmty_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) { Types . md_type = approx_modtype env pmd . pmd_type ; md_attributes = pmd . pmd_attributes ; md_loc = pmd . pmd_loc ; } match ssg with [ ] -> [ ] | item :: srem -> match item . psig_desc with | Psig_type ( rec_flag , sdecls ) -> let decls = Typedecl . approx_type_decl sdecls in let rem = approx_sig env srem in map_rec_type ~ rec_flag ( fun rs ( id , info ) -> Sig_type ( id , info , rs , Exported ) ) decls rem | Psig_typesubst _ -> approx_sig env srem | Psig_module { pmd_name = { txt = None ; _ } ; _ } -> approx_sig env srem | Psig_module pmd -> let scope = Ctype . create_scope ( ) in let md = approx_module_declaration env pmd in let pres = match md . Types . md_type with | Mty_alias _ -> Mp_absent | _ -> Mp_present in let id , newenv = Env . enter_module_declaration ~ scope ( Option . get pmd . pmd_name . txt ) pres md env in Sig_module ( id , pres , md , Trec_not , Exported ) :: approx_sig newenv srem | Psig_modsubst pms -> let scope = Ctype . create_scope ( ) in let _ , md = Env . lookup_module ~ use : false ~ loc : pms . pms_manifest . loc pms . pms_manifest . txt env in let pres = match md . Types . md_type with | Mty_alias _ -> Mp_absent | _ -> Mp_present in let _ , newenv = Env . enter_module_declaration ~ scope pms . pms_name . txt pres md env in approx_sig newenv srem | Psig_recmodule sdecls -> let scope = Ctype . create_scope ( ) in let decls = List . filter_map ( fun pmd -> Option . map ( fun name -> Ident . create_scoped ~ scope name , approx_module_declaration env pmd ) pmd . pmd_name . txt ) sdecls in let newenv = List . fold_left ( fun env ( id , md ) -> Env . add_module_declaration ~ check : false id Mp_present md env ) env decls in map_rec ( fun rs ( id , md ) -> Sig_module ( id , Mp_present , md , rs , Exported ) ) decls ( approx_sig newenv srem ) | Psig_modtype d -> let info = approx_modtype_info env d in let scope = Ctype . create_scope ( ) in let ( id , newenv ) = Env . enter_modtype ~ scope d . pmtd_name . txt info env in Sig_modtype ( id , info , Exported ) :: approx_sig newenv srem | Psig_open sod -> let _ , env = type_open_descr env sod in approx_sig env srem | Psig_include sincl -> let smty = sincl . pincl_mod in let mty = approx_modtype env smty in let scope = Ctype . create_scope ( ) in let sg , newenv = Env . enter_signature ~ scope ( extract_sig env smty . pmty_loc mty ) env in sg @ approx_sig newenv srem | Psig_class sdecls | Psig_class_type sdecls -> let decls = Typeclass . approx_class_declarations env sdecls in let rem = approx_sig env srem in map_rec ( fun rs decl -> let open Typeclass in [ Sig_class_type ( decl . clsty_ty_id , decl . clsty_ty_decl , rs , Exported ) ; Sig_type ( decl . clsty_obj_id , decl . clsty_obj_abbr , rs , Exported ) ; Sig_type ( decl . clsty_typesharp_id , decl . clsty_abbr , rs , Exported ) ; ] ) decls [ rem ] |> List . flatten | _ -> approx_sig env srem { mtd_type = Option . map ( approx_modtype env ) sinfo . pmtd_type ; mtd_attributes = sinfo . pmtd_attributes ; mtd_loc = sinfo . pmtd_loc ; }
let approx_modtype env smty = Warnings . without_warnings ( fun ( ) -> approx_modtype env smty )
module Signature_names : sig type t type info = [ | ` Exported | ` From_open | ` Shadowable of Ident . t * Location . t | ` Substituted_away of Subst . t ] val create : unit -> t val check_value : ? info : info -> t -> Location . t -> Ident . t -> unit val check_type : ? info : info -> t -> Location . t -> Ident . t -> unit val check_typext : ? info : info -> t -> Location . t -> Ident . t -> unit val check_module : ? info : info -> t -> Location . t -> Ident . t -> unit val check_modtype : ? info : info -> t -> Location . t -> Ident . t -> unit val check_class : ? info : info -> t -> Location . t -> Ident . t -> unit val check_class_type : ? info : info -> t -> Location . t -> Ident . t -> unit val check_sig_item : ? info : info -> t -> Location . t -> Types . signature_item -> unit val simplify : Env . t -> t -> Types . signature -> Types . signature type bound_info = [ | ` Exported | ` Shadowable of Ident . t * Location . t ] type info = [ | ` From_open | ` Substituted_away of Subst . t | bound_info ] type hide_reason = | From_open | Shadowed_by of Ident . t * Location . t type to_be_removed = { mutable subst : Subst . t ; mutable hide : ( Sig_component_kind . t * Location . t * hide_reason ) Ident . Map . t ; } type names_infos = ( string , bound_info ) Hashtbl . t type names = { values : names_infos ; types : names_infos ; modules : names_infos ; modtypes : names_infos ; typexts : names_infos ; classes : names_infos ; class_types : names_infos ; } let new_names ( ) = { values = Hashtbl . create 16 ; types = Hashtbl . create 16 ; modules = Hashtbl . create 16 ; modtypes = Hashtbl . create 16 ; typexts = Hashtbl . create 16 ; classes = Hashtbl . create 16 ; class_types = Hashtbl . create 16 ; } type t = { bound : names ; to_be_removed : to_be_removed ; } let create ( ) = { bound = new_names ( ) ; to_be_removed = { subst = Subst . identity ; hide = Ident . Map . empty ; } ; } let check cl loc ( tbl : names_infos ) id ( info : info ) to_be_removed = match info with | ` Substituted_away s -> to_be_removed . subst <- Subst . compose s to_be_removed . subst | ` From_open -> to_be_removed . hide <- Ident . Map . add id ( cl , loc , From_open ) to_be_removed . hide | # bound_info as bound_info -> let name = Ident . name id in match Hashtbl . find_opt tbl name with | None -> Hashtbl . add tbl name bound_info | Some ( ` Shadowable ( shadowed_id , shadowed_loc ) ) -> Hashtbl . replace tbl name bound_info ; let reason = Shadowed_by ( id , loc ) in to_be_removed . hide <- Ident . Map . add shadowed_id ( cl , shadowed_loc , reason ) to_be_removed . hide | Some ` Exported -> raise ( Error ( loc , Env . empty , Repeated_name ( cl , name ) ) ) let check_value ? info t loc id = let info = match info with | Some i -> i | None -> ` Shadowable ( id , loc ) in check Sig_component_kind . Value loc t . bound . values id info t . to_be_removed let check_type ( ? info ` = Exported ) t loc id = check Sig_component_kind . Type loc t . bound . types id info t . to_be_removed let check_module ( ? info ` = Exported ) t loc id = check Sig_component_kind . Module loc t . bound . modules id info t . to_be_removed let check_modtype ( ? info ` = Exported ) t loc id = check Sig_component_kind . Module_type loc t . bound . modtypes id info t . to_be_removed let check_typext ( ? info ` = Exported ) t loc id = check Sig_component_kind . Extension_constructor loc t . bound . typexts id info t . to_be_removed let check_class ( ? info ` = Exported ) t loc id = check Sig_component_kind . Class loc t . bound . classes id info t . to_be_removed let check_class_type ( ? info ` = Exported ) t loc id = check Sig_component_kind . Class_type loc t . bound . class_types id info t . to_be_removed let check_sig_item ? info names loc component = let info id loc = match info with | None -> ` Shadowable ( id , loc ) | Some i -> i in match component with | Sig_type ( id , _ , _ , _ ) -> check_type names loc id ~ info ( : info id loc ) | Sig_module ( id , _ , _ , _ , _ ) -> check_module names loc id ~ info ( : info id loc ) | Sig_modtype ( id , _ , _ ) -> check_modtype names loc id ~ info ( : info id loc ) | Sig_typext ( id , _ , _ , _ ) -> check_typext names loc id ~ info ( : info id loc ) | Sig_value ( id , _ , _ ) -> check_value names loc id ~ info ( : info id loc ) | Sig_class ( id , _ , _ , _ ) -> check_class names loc id ~ info ( : info id loc ) | Sig_class_type ( id , _ , _ , _ ) -> check_class_type names loc id ~ info ( : info id loc ) let simplify env t sg = let to_remove = t . to_be_removed in let ids_to_remove = Ident . Map . fold ( fun id ( kind , _ , _ ) lst -> if Sig_component_kind . can_appear_in_types kind then id :: lst else lst ) to_remove . hide [ ] in let aux component sg = let user_kind , user_id , user_loc = let open Sig_component_kind in match component with | Sig_value ( id , v , _ ) -> Value , id , v . val_loc | Sig_type ( id , td , _ , _ ) -> Type , id , td . type_loc | Sig_typext ( id , te , _ , _ ) -> Extension_constructor , id , te . ext_loc | Sig_module ( id , _ , md , _ , _ ) -> Module , id , md . md_loc | Sig_modtype ( id , mtd , _ ) -> Module_type , id , mtd . mtd_loc | Sig_class ( id , c , _ , _ ) -> Class , id , c . cty_loc | Sig_class_type ( id , ct , _ , _ ) -> Class_type , id , ct . clty_loc in if Ident . Map . mem user_id to_remove . hide then sg else begin let component = if to_remove . subst == Subst . identity then component else Subst . signature_item Keep to_remove . subst component in let component = match ids_to_remove with | [ ] -> component | ids -> try Mtype . nondep_sig_item env ids component with | Ctype . Nondep_cannot_erase removed_item_id -> let ( removed_item_kind , removed_item_loc , reason ) = Ident . Map . find removed_item_id to_remove . hide in let err_loc , hiding_error = match reason with | From_open -> removed_item_loc , Appears_in_signature { opened_item_kind = removed_item_kind ; opened_item_id = removed_item_id ; user_id ; user_kind ; user_loc ; } | Shadowed_by ( shadower_id , shadower_loc ) -> shadower_loc , Illegal_shadowing { shadowed_item_kind = removed_item_kind ; shadowed_item_id = removed_item_id ; shadowed_item_loc = removed_item_loc ; shadower_id ; user_id ; user_kind ; user_loc ; } in raise ( Error ( err_loc , env , Cannot_hide_id hiding_error ) ) in component :: sg end in List . fold_right aux sg [ ] end