text
stringlengths
12
786k
let test_boolean_operators context = let assert_type_errors = assert_type_errors ~ context in let assert_default_type_errors = assert_default_type_errors ~ context in assert_type_errors { | from typing import TypeGuard def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def foo ( val : int | str ) -> None : if True and typeguard_fn ( val ) : reveal_type ( val ) if False and typeguard_fn ( val ) : reveal_type ( val ) if typeguard_fn ( val ) and True : reveal_type ( val ) if typeguard_fn ( val ) and False : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val ` is ` int ` . " ; ] ; assert_type_errors { | from typing import TypeGuard def int_or_str ( val : int | str | bool ) -> TypeGuard [ int | str ] : return True def str_or_bool ( val : int | str | bool ) -> TypeGuard [ str | bool ] : return True def foo ( val : int | str | bool ) -> None : if int_or_str ( val ) and str_or_bool ( val ) : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` str ` . " ] ; assert_type_errors { | from typing import TypeGuard def is_int ( val : int | str | bool ) -> TypeGuard [ int ] : return True def is_str ( val : int | str | bool ) -> TypeGuard [ str ] : return True def foo ( val : int | str | bool ) -> None : if is_int ( val ) or is_str ( val ) : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` typing . Union [ int , str ] ` . " ] ; assert_default_type_errors { | from typing import TypeGuard , List , TypeVar , Any , Type , Union _T = TypeVar ( " _T " ) def is_list_of ( val : List [ Any ] , type : Type [ _T ] ) -> TypeGuard [ List [ _T ] ] : return all ( isinstance ( x , type ) for x in val ) def foo ( val : List [ Any ] ) -> None : if is_list_of ( val , int ) or is_list_of ( val , str ) : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Union [ List [ int ] , List [ str ] ] ` . " ] ; assert_type_errors { | from typing import TypeGuard , Union def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def foo ( val : int | str ) -> None : if True or typeguard_fn ( val ) : reveal_type ( val ) if False or typeguard_fn ( val ) : reveal_type ( val ) if typeguard_fn ( val ) or True : reveal_type ( val ) if typeguard_fn ( val ) or False : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Union [ int , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Union [ int , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Union [ int , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Union [ int , str ] ` . " ; ] ; assert_type_errors { | from typing import TypeGuard , Union def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def foo ( val1 : int | str , val2 : int | str ) -> None : if typeguard_fn ( val1 ) and typeguard_fn ( val2 ) : reveal_type ( val1 ) reveal_type ( val2 ) if typeguard_fn ( val1 ) or typeguard_fn ( val2 ) : reveal_type ( val1 ) reveal_type ( val2 ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val1 ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val2 ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val1 ` is ` Union [ int , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` val2 ` is ` Union [ int , str ] ` . " ; ] ; ( )
let test_misc context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import TypeGuard , Union def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def bool_fn ( val : int | str ) -> bool : return True def first_int ( x : int | str ) -> None : y = x if typeguard_fn ( x ) else 5 reveal_type ( y ) z = x if bool_fn ( x ) else 5 reveal_type ( z ) } | [ " Revealed type [ - 1 ] : Revealed type for ` y ` is ` int ` . " ; " Revealed type [ - 1 ] : Revealed type for ` z ` is ` Union [ int , str ] ` . " ; ] ; assert_type_errors { | from typing import TypeGuard def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def foo ( val : int | str ) -> None : assert typeguard_fn ( val ) reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` int ` . " ] ; assert_type_errors { | from typing import TypeGuard from dataclasses import dataclass def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True @ dataclass ( frozen = True ) class Bar ( ) : field : int | str = 5 def foo ( obj : Bar ) -> None : if typeguard_fn ( obj . field ) : reveal_type ( obj . field ) } | [ " Revealed type [ - 1 ] : Revealed type for ` obj . field ` is ` int ` . " ] ; assert_type_errors { | from typing import List from typing_extensions import TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) } | [ ] ; ( )
let ( ) = " type_guard " >::: [ " test_type_guard " >:: test_type_guard ; " test_multiple_arguments " >:: test_multiple_arguments ; " test_methods " >:: test_methods ; " test_callback " >:: test_callback ; " test_return_type " >:: test_return_type ; " test_walrus_operator " >:: test_walrus_operator ; " test_boolean_operators " >:: test_boolean_operators ; " test_misc " >:: test_misc ; ] |> Test . run
let filters : ( Sigs_util . plugin_name , Sigs_util . plugin ) Hashtbl . t = Hashtbl . create 30
let show_code = ref false
let print_collect_mtyps = ref false
let register ? filter ? position = function | ( name , transform ) -> if Hashtbl . mem filters name then eprintf " Warning :% s filter already exists . " !@ name else Hashtbl . add filters name { transform ; position ; filter }
let show_modules = function | ( ) -> ( Hashtbl . iter ( function | key -> ( function | _ -> Format . printf " % s @ " key ) ) filters ; print_newline ( ) )
let plugin_add = function | plugin -> ( ( try let v = Hashtbl . find filters plugin in function | ( ) -> if not @@ ( List . exists ( function | ( n , _ ) -> n = plugin ) ( ! State . current_filters ) ) then Ref . modify State . current_filters ( function | x -> cons ( plugin , v ) x ) else eprintf " < Warning > plugin % s has already been loaded " plugin with | Not_found -> ( function | ( ) -> ( show_modules ( ) ; failwithf " plugins % s not found " plugin ) ) ) ) ( )
let plugin_remove = function | plugin -> Ref . modify State . current_filters ( function | x -> Listf . remove plugin x ) object inherit Objs . map method get_cur_mtyps : Sigs_util . mtyps method get_cur_and_types : Sigs_util . and_types method update_cur_and_types : ( Sigs_util . and_types -> Sigs_util . and_types ) -> unit method update_cur_mtyps : ( Sigs_util . mtyps -> Sigs_util . mtyps ) -> unit end
let make_filter = function | ( s , code ) -> let f = function | ( ` StExp ( _loc , ` Lid ( _ , s ' ) ) : Astf . stru ) when s = s ' -> Fill . stru _loc code | e -> e in ( ( " filter_ " ^ s ) , ( ( Objs . map_stru f ) # stru ) )
let iterate_code = function | sloc -> ( function | mtyps -> ( function | ( _ , ( x : Sigs_util . plugin ) ) -> ( function | acc -> let mtyps = match x . filter with | Some x -> Sigs_util . apply_filter x mtyps | None -> mtyps in let code = x . transform mtyps in ( match ( ( x . position ) , code ) with | ( Some x , Some code ) -> let ( name , f ) = make_filter ( x , code ) in ( Ast_filters . register_stru_filter ( name , f ) ; Ast_filters . use_implem_filter name ; acc ) | ( None , Some code ) -> let code = Fill . stru sloc code in ( ` Sem ( sloc , ( acc :> Astf . stru ) , ( code :> Astf . stru ) ) :> Astf . stru ) | ( _ , None ) -> acc ) ) ) )
let traversal = function | ( ) -> ( object ( self : ' self_type ) inherit Objs . map as super val mtyps_stack = ( Stack . create ( ) : Sigs_util . mtyps Stack . t ) val mutable cur_and_types = ( [ ] : Sigs_util . and_types ) val mutable and_group = false method get_cur_mtyps : Sigs_util . mtyps = Stack . top mtyps_stack method update_cur_mtyps = ( function | f -> let open Stack in push ( f ( pop mtyps_stack ) ) mtyps_stack ) method private in_module = Stack . push [ ] mtyps_stack method private out_module = ignore ( Stack . pop mtyps_stack ) method private in_and_types = ( and_group <- true ; cur_and_types <- [ ] ) method private out_and_types = ( and_group <- false ; cur_and_types <- [ ] ) method private is_in_and_types = and_group method get_cur_and_types = cur_and_types method update_cur_and_types = ( function | f -> cur_and_types <- f cur_and_types ) method ! mexp = ( function | ( ` Struct ( sloc , u ) : Astf . mexp ) -> ( self # in_module ; ( let res = self # stru u in let mtyps = List . rev self # get_cur_mtyps in let ( ) = if ! print_collect_mtyps then eprintf " [ @% a ] . " @@ pp_print_mtyps mtyps in let result = List . fold_right ( iterate_code sloc mtyps ) ( ! State . current_filters ) ( if ! State . keep then res else ( ` StExp ( sloc , ( ` Unit sloc ) ) :> Astf . stru ) ) in self # out_module ; ( ` Struct ( sloc , ( result :> Astf . stru ) ) :> Astf . mexp ) ) ) | x -> super # mexp x ) method ! stru = ( function | ( ` Type ( _loc , ` And ( _ , _ , _ ) ) : Astf . stru ) as x -> ( self # in_and_types ; ( let _ = super # stru x in self # update_cur_mtyps ( function | lst -> ( ` Mutual ( List . rev self # get_cur_and_types ) ) :: lst ) ; self # out_and_types ; if ! State . keep then x else ( ` StExp ( _loc , ( ` Unit _loc ) ) :> Astf . stru ) ) ) | ` TypeWith ( _loc , typedecl , _ ) -> self # stru ( ` Type ( _loc , typedecl ) ) | ( ` Type ( _loc , ( ` TyDcl ( _ , ` Lid ( _ , name ) , _ , _ , _ ) as t ) ) : Astf . stru ) as x -> let item = ` Single ( name , ( Strip . typedecl t ) ) in let ( ) = if ! print_collect_mtyps then eprintf " Came across [ @% a ] . " @@ pp_print_types item in ( self # update_cur_mtyps ( function | lst -> item :: lst ) ; x ) | ( ` Value ( _loc , ` Negative _ , _ ) : Astf . stru ) ( ` | ModuleType ( _loc , _ , _ ) : Astf . stru ) ( ` | Include ( _loc , _ ) : Astf . stru ) ( ` | External ( _loc , _ , _ , _ ) : Astf . stru ) ( ` | StExp ( _loc , _ ) : Astf . stru ) ( ` | Exception ( _loc , _ ) : Astf . stru ) ( ` | Directive ( _loc , _ , _ ) : Astf . stru ) as x -> x | x -> super # stru x ) method ! typedecl = ( function | ` TyDcl ( _ , ` Lid ( _ , name ) , _ , _ , _ ) as t -> ( if self # is_in_and_types then self # update_cur_and_types ( function | lst -> ( name , ( Strip . typedecl t ) ) :: lst ) ; t ) | t -> super # typedecl t ) end : traversal )
let genenrate_type_code = function | _loc -> ( function | tdl -> ( function | ( ns : Astf . strings ) -> ( let x : Astf . stru = ` Type ( _loc , tdl ) in let ns = list_of_app ns [ ] in let filters = List . map ( function | ` Str ( sloc , n ) -> ( match Hashtblf . find_opt filters n with | None -> Locf . failf sloc " % s not found " n | Some p -> ( n , p ) ) | ` Ant _ -> Locf . raise _loc ( Failure " antiquotation not expected here " ) | _ -> assert false ) ns in let code = Ref . protect2 ( State . current_filters , filters ) ( State . keep , false ) ( function | _ -> ( match ( traversal ( ) ) # mexp ( ` Struct ( _loc , x ) : Astf . mexp ) with | ( ` Struct ( _loc , s ) : Astf . mexp ) -> s | _ -> assert false ) ) in ` Sem ( _loc , x , code ) : Astf . stru ) ) )
let ( ) = Ast2pt . generate_type_code := genenrate_type_code
let printf_output = if ( try Sys . getenv " DEBUG " = " 1 " with Not_found -> false ) then Format . std_formatter else Format . make_formatter ( fun _ _ _ -> ( ) ) ( fun ( ) -> ( ) )
let printf x = Format . fprintf printf_output x
let type_implicit_instance : ( Env . t -> Typedtree . module_expr -> Path . t -> Longident . t list -> type_expr list -> Typedtree . module_expr * type_expr list ) ref = ref ( fun _ -> assert false ) ) *
type pending_implicit = { implicit_id : Ident . t ; implicit_env : Env . t ; implicit_loc : Location . t ; implicit_type : Path . t * Longident . t list * type_expr list ; mutable implicit_constraints : ( type_expr * type_expr ) list ; implicit_argument : argument ; }
let unlink env unlink_on = let path_table = Hashtbl . create 7 in let add_constraint register path ty tyvar = let instance_list = try Hashtbl . find path_table path with Not_found -> [ ] in try let eq_args ( ty ' , _tyvar ' ) = TypeOps . equal ty ty ' || Ctype . equal env false [ ty ] [ ty ' ] in let _ty ' , tyvar ' = List . find eq_args instance_list in link_type tyvar tyvar ' with Not_found -> Hashtbl . replace path_table path ( ( ty , tyvar ) :: instance_list ) ; register ty tyvar in let rec it_type_expr shadow_tbl it ty = let ty = repr ty in match ty . desc with | Tconstr ( path , args , _ ) -> let ident = Path . head path in begin match unlink_on ident with | None -> ( ) | Some register when Ident . mem ident shadow_tbl -> ( ) | Some register -> let ty ' = newvar ~ name " : imp " # ( ) in let { desc = desc ; level = lv } = ty in let { desc = desc ' ; level = lv ' } = ty ' in ty . desc <- desc ' ; ty . level <- lv ' ; ty ' . desc <- desc ; ty ' . level <- lv ; add_constraint register path ty ' ty end ; type_iterators . it_type_expr it ty | Tarrow ( Tarr_implicit id , lhs , rhs , _ ) -> mark_type_node ty ; it . it_type_expr it lhs ; let shadow_tbl = Ident . add id ( ) shadow_tbl in let it = { it with it_type_expr = it_type_expr shadow_tbl } in it . it_type_expr it rhs | _ -> type_iterators . it_type_expr it ty in { type_iterators with it_type_expr = it_type_expr Ident . empty }
let pending_implicits : pending_implicit list list ref = ref [ ]
let rec has_implicit ty = match ( repr ty ) . desc with | Tarrow ( Tarr_implicit id , _ , _ , _ ) -> true | Tarrow ( _ , _ , rhs , _ ) -> has_implicit rhs | _ -> false
let instantiate_one_implicit loc env id ty_arg ty_res = let inst = match ( repr ty_arg ) . desc with | Tpackage ( p , nl , tl ) -> { implicit_id = id ; implicit_env = env ; implicit_loc = loc ; implicit_type = ( p , nl , tl ) ; implicit_constraints = [ ] ; implicit_argument = { arg_flag = Tapp_implicit ; arg_expression = None } ; } | _ -> assert false in let add_constraint ty tyvar = inst . implicit_constraints <- ( ty , tyvar ) :: inst . implicit_constraints in let unlink_ident ident = if Ident . same id ident then Some add_constraint else None in let unlink_it = unlink env unlink_ident in List . iter ( unlink_it . it_type_expr unlink_it ) ty_res ; List . iter unmark_type ty_res ; inst
let pack_implicit_ref : ( pending_implicit -> Path . t -> Typedtree . expression ) ref = ref ( fun _ _ -> assert false )
let pack_implicit inst path = ! pack_implicit_ref inst path
module Link = struct let to_path inst path = let subst = Subst . add_module inst . implicit_id path Subst . identity in List . iter ( fun ( ty , tyvar ) -> let ty = Subst . type_expr subst ty in let tyvar = Subst . type_expr subst tyvar in unify inst . implicit_env ty tyvar ) inst . implicit_constraints ; let expr = pack_implicit inst path in inst . implicit_argument . arg_expression <- Some expr let to_expr inst expr = let rec mod_path me = match me . mod_desc with | Tmod_ident ( path , _ ) -> path | Tmod_constraint ( me , _ , _ , _ ) -> mod_path me | _ -> assert false in let path = match expr . exp_desc with | Texp_pack me -> mod_path me | _ -> assert false in to_path inst path end
let reunify_constraint inst = let reunify ( ty , tyvar ) = try unify inst . implicit_env ty tyvar with _ -> ( ) in List . iter reunify inst . implicit_constraints
let reunify_constraints ( ) = List . iter ( List . iter reunify_constraint ) ! pending_implicits
let add_pending_implicits insts = pending_implicits := insts :: ! pending_implicits
let reset_pending_implicits ( ) = pending_implicits := [ ]
let generalize_implicits_ref : ( unit -> unit ) ref = ref ( fun ( ) -> assert false )
let generalize_implicits ( ) = ! generalize_implicits_ref ( )
let type_to_string type_ = type_ |> Format . asprintf " % a " Type . pp
let type_to_reference type_ = type_ |> type_to_string |> Reference . create
let expression_to_json expression = ` String ( expression |> Expression . sanitized |> Expression . show )
module SerializableReference = struct type t = Reference . t [ @@ deriving compare , sexp , hash , show ] let to_yojson reference = ` String ( Reference . show_sanitized reference ) module Map = Reference . Map . Tree module Set = Set . Make ( Reference ) end
module DefaultValue = struct type t = Expression . t option [ @@ deriving show ] let to_yojson value = value >>| expression_to_json |> Option . value ~ default ` : Null end
module AnnotationLocation = struct type t = { qualifier : SerializableReference . t ; path : string ; line : int ; } [ @@ deriving show , compare , to_yojson ] let create ~ lookup ~ qualifier ~ line = { qualifier ; path = lookup qualifier |> Option . value ~ default " " ; :* line } let from_location ~ lookup ~ qualifier Location . { start = { line ; _ } ; _ } = create ~ lookup ~ qualifier ~ line let from_location_with_module ~ lookup Location . WithModule . { module_reference = qualifier ; start = { line ; _ } ; _ } = create ~ lookup ~ qualifier ~ line end
module SerializableType = struct type t = Type . t [ @@ deriving show ] let to_yojson type_ = ` String ( type_to_string type_ ) end
module TypeAnnotation = struct type t = | Inferred of SerializableType . t | Given of Expression . t | Missing [ @@ deriving show ] let is_inferred = function | Inferred _ -> true | Given _ | Missing -> false let from_given maybe_expression = match maybe_expression with | Some expression -> Given expression | None -> Missing let from_inferred type_ = Inferred type_ let merge ~ f left right = match left , right with | Inferred left , Inferred right -> Inferred ( f left right ) | Inferred type_ , _ | _ , Inferred type_ -> Inferred type_ | Given expression , _ | _ , Given expression -> Given expression | Missing , Missing -> Missing let join ~ global_resolution = merge ~ f ( : GlobalResolution . join global_resolution ) let meet ~ global_resolution = merge ~ f ( : GlobalResolution . meet global_resolution ) let to_yojson = function | Inferred type_ -> SerializableType . to_yojson type_ | Given _ | Missing -> ` Null end
module AnnotationsByName = struct module Base = struct module type S = sig type t [ @@ deriving show , compare , to_yojson ] val identifying_name : t -> SerializableReference . t end module Make ( Value : S ) = struct type t = Value . t SerializableReference . Map . t let empty = SerializableReference . Map . empty let length = SerializableReference . Map . length let data map = SerializableReference . Map . data map |> List . sort ~ compare : Value . compare let show map = map |> data |> List . map ~ f : Value . show |> String . concat ~ sep " , " : |> Format . asprintf " [ % s ] " let to_yojson map = ` List ( map |> data |> List . map ~ f : Value . to_yojson ) let pp format map = show map |> Format . fprintf format " % s " let add_exn map value = let identifying_name = Value . identifying_name value in SerializableReference . Map . add_exn map ~ key : identifying_name ~ data : value let update_exn map name transform = let transform_or_raise = function | Some value -> transform value | None -> failwith ( Format . asprintf " Did not expect an update with name % a ( expected one of % a ) " Reference . pp name pp map ) in SerializableReference . Map . update map name ~ f : transform_or_raise let filter_not ~ f = SerializableReference . Map . filter ~ f ( : fun value -> not ( f value ) ) end end module Combineable = struct module type S = sig include Base . S val combine : global_resolution : GlobalResolution . t -> t -> t -> t end module Make ( Value : S ) = struct include Base . Make ( Value ) let add ~ global_resolution map value = let identifying_name = Value . identifying_name value in SerializableReference . Map . update map identifying_name ~ f ( : function | Some existing -> Value . combine ~ global_resolution value existing | None -> value ) let merge ~ global_resolution left right = let combine ~ key = function | ` Left value | ` Right value -> Some value | ` Both ( left , right ) -> ( try Some ( Value . combine ~ global_resolution left right ) with | Analysis . ClassHierarchy . Untracked annotation -> Statistics . event ~ name " : undefined type during type inference merge " ~ integers [ ] : ~ normals [ " : type " , annotation ; " reference " , SerializableReference . show key ] ( ) ; Some left ) in SerializableReference . Map . merge ~ f : combine left right end end include Combineable end
module GlobalAnnotation = struct module Value = struct type t = { name : SerializableReference . t ; location : AnnotationLocation . t ; annotation : SerializableType . t ; } [ @@ deriving show , to_yojson ] let compare { location = left ; _ } { location = right ; _ } = AnnotationLocation . compare left right let qualified_name { name ; location = { qualifier ; _ } ; _ } = [ qualifier ; name ] |> List . bind ~ f : Reference . as_list |> Reference . create_from_list let identifying_name = qualified_name let combine ~ global_resolution left right = { left with annotation = GlobalResolution . join global_resolution left . annotation right . annotation ; } end module ByName = AnnotationsByName . Make ( Value ) include Value let suppress { annotation ; _ } = Type . is_none annotation end
module AttributeAnnotation = struct module Value = struct type t = { parent : SerializableReference . t ; name : SerializableReference . t ; location : AnnotationLocation . t ; annotation : SerializableType . t ; } [ @@ deriving show , to_yojson ] let compare { location = left ; _ } { location = right ; _ } = AnnotationLocation . compare left right let qualified_name { parent ; name ; location = { qualifier ; _ } ; _ } = [ qualifier ; parent ; name ] |> List . bind ~ f : Reference . as_list |> Reference . create_from_list let identifying_name = qualified_name let combine ~ global_resolution left right = { left with annotation = GlobalResolution . join global_resolution left . annotation right . annotation ; } end module ByName = AnnotationsByName . Make ( Value ) include Value let suppress { annotation ; _ } = Type . is_none annotation end
module DefineAnnotation = struct module Parameters = struct module Value = struct type t = { name : SerializableReference . t ; annotation : TypeAnnotation . t ; value : DefaultValue . t ; index : int ; } [ @@ deriving show , to_yojson ] let compare { index = left ; _ } { index = right ; _ } = Int . compare left right let identifying_name parameter = parameter . name let is_inferred { annotation ; _ } = TypeAnnotation . is_inferred annotation let combine ~ global_resolution left right = let annotation = TypeAnnotation . meet ~ global_resolution left . annotation right . annotation in { left with annotation } end module ByName = AnnotationsByName . Make ( Value ) let any_inferred ( parameters : ByName . t ) : bool = Map . Tree . exists parameters ~ f : Value . is_inferred end type t = { name : SerializableReference . t ; parent : SerializableReference . t option ; return : TypeAnnotation . t ; [ @ compare . ignore ] parameters : Parameters . ByName . t ; [ @ compare . ignore ] location : AnnotationLocation . t ; async : bool ; } [ @@ deriving show , compare , to_yojson ] let is_inferred { return ; parameters ; _ } = TypeAnnotation . is_inferred return || Parameters . any_inferred parameters let add_inferred_return ~ global_resolution define type_ = { define with return = TypeAnnotation . join ~ global_resolution define . return ( TypeAnnotation . from_inferred type_ ) ; } let add_inferred_parameter define name type_ = let sanitized_name = name |> Reference . sanitized in { define with parameters = Parameters . ByName . update_exn define . parameters sanitized_name ( fun parameter -> { parameter with annotation = TypeAnnotation . from_inferred type_ } ) ; } end
module Inference = struct type target = | Return | Parameter of { name : Reference . t } | Global of { name : Reference . t ; location : Location . WithModule . t ; } | Attribute of { parent : Reference . t ; name : Reference . t ; location : Location . WithModule . t ; } [ @@ deriving show ] type raw = { type_ : Type . t ; target : target ; } [ @@ deriving show ] type t = raw option [ @@ deriving show ] let create { type_ = raw_type ; target } = let is_parameter = match target with | Parameter _ -> true | _ -> false in let sanitized_type = raw_type |> Type . Variable . mark_all_free_variables_as_escaped |> Type . Variable . convert_all_escaped_free_variables_to_anys |> Type . infer_transform in let ignore = Type . contains_unknown sanitized_type || Type . contains_undefined sanitized_type || Type . contains_prohibited_any sanitized_type || ( is_parameter && Type . equal sanitized_type NoneType ) in if ignore then None else Some { type_ = sanitized_type ; target } end
module LocalResult = struct type t = { globals : GlobalAnnotation . ByName . t ; attributes : AttributeAnnotation . ByName . t ; define : DefineAnnotation . t ; } [ @@ deriving show , to_yojson ] let define_name { define = { name ; _ } ; _ } = name let from_signature ~ global_resolution ~ lookup ~ qualifier { Node . value = { Statement . Define . signature = { name ; parameters ; return_annotation ; parent ; async ; _ } ; _ ; } ; Node . location = define_location ; } = let define = let open DefineAnnotation in let return = TypeAnnotation . from_given return_annotation in let parameters = let initialize_parameter index { Node . value = Expression . Parameter . { name ; annotation ; value } ; _ } = DefineAnnotation . Parameters . Value . { name = name |> Identifier . sanitized |> Reference . create ; annotation = TypeAnnotation . from_given annotation ; value ; index ; } in parameters |> List . mapi ~ f : initialize_parameter |> List . fold ~ init : Parameters . ByName . empty ~ f ( : Parameters . ByName . add ~ global_resolution ) in { name ; parent ; return ; parameters ; location = define_location |> AnnotationLocation . from_location ~ lookup ~ qualifier ; async ; } in { globals = GlobalAnnotation . ByName . empty ; attributes = AttributeAnnotation . ByName . empty ; define ; } let add_inference ~ global_resolution ~ lookup ( { globals ; attributes ; define ; _ } as result ) inference = let add_inferred_type Inference . { type_ ; target } = match target with | Inference . Return -> { result with define = DefineAnnotation . add_inferred_return ~ global_resolution define type_ ; } | Inference . Parameter { name } -> { result with define = DefineAnnotation . add_inferred_parameter define name type_ } | Inference . Global { name ; location } -> { result with globals = GlobalAnnotation . ByName . add ~ global_resolution globals { name ; annotation = type_ ; location = location |> AnnotationLocation . from_location_with_module ~ lookup ; } ; } | Inference . Attribute { parent ; name ; location } -> { result with attributes = AttributeAnnotation . ByName . add ~ global_resolution attributes { parent ; name ; annotation = type_ ; location = location |> AnnotationLocation . from_location_with_module ~ lookup ; } ; } in inference |> Option . map ~ f : add_inferred_type |> Option . value ~ default : result end
module GlobalResult = struct module DefineAnnotationsByName = struct module Value = struct type t = DefineAnnotation . t [ @@ deriving show , compare , to_yojson ] let identifying_name { DefineAnnotation . name ; _ } = name end include AnnotationsByName . Base . Make ( Value ) end type t = { globals : GlobalAnnotation . ByName . t ; attributes : AttributeAnnotation . ByName . t ; defines : DefineAnnotationsByName . t ; } [ @@ deriving show , to_yojson ] let inference_count { globals ; attributes ; defines } = GlobalAnnotation . ByName . length globals + AttributeAnnotation . ByName . length attributes + DefineAnnotationsByName . length defines let empty = { globals = GlobalAnnotation . ByName . empty ; attributes = AttributeAnnotation . ByName . empty ; defines = DefineAnnotationsByName . empty ; } let add_define ~ define_names ~ defines define = let name = DefineAnnotationsByName . Value . identifying_name define in if SerializableReference . Set . mem define_names name then define_names , SerializableReference . Map . remove defines name else let define_names = SerializableReference . Set . add define_names name in let defines = if DefineAnnotation . is_inferred define then DefineAnnotationsByName . add_exn defines define else defines in define_names , defines let add_local_result ~ global_resolution ( define_names , { globals ; attributes ; defines } ) { LocalResult . globals = globals_from_local ; LocalResult . attributes = attributes_from_local ; LocalResult . define ; _ ; } = let define_names , defines = add_define ~ define_names ~ defines define in ( define_names , { globals = GlobalAnnotation . ByName . merge ~ global_resolution globals globals_from_local ; attributes = AttributeAnnotation . ByName . merge ~ global_resolution attributes attributes_from_local ; defines ; } ) let suppress_unhelpful_types { globals ; attributes ; defines } = { globals = globals |> GlobalAnnotation . ByName . filter_not ~ f : GlobalAnnotation . suppress ; attributes = attributes |> AttributeAnnotation . ByName . filter_not ~ f : AttributeAnnotation . suppress ; defines ; } let from_local_results ~ global_resolution local_results = local_results |> List . fold ~ init ( : SerializableReference . Set . empty , empty ) ~ f ( : add_local_result ~ global_resolution ) |> snd |> suppress_unhelpful_types end
let environment_data scratch_project = let { ScratchProject . BuiltGlobalEnvironment . global_environment ; _ } = scratch_project |> ScratchProject . build_global_environment in global_environment , scratch_project . configuration
let type_inference_result ~ context ~ test_source = let scratch_project = ScratchProject . setup ~ context [ " test . py " , test_source ] in let global_environment , configuration = scratch_project |> environment_data in let scheduler = Test . mock_scheduler ( ) in let global_result = Service . Infer . run_infer ~ configuration ~ scheduler ~ filename_lookup ( : fun _ -> None ) ~ paths_to_modify : None Service . Infer . { global_environment = AnnotatedGlobalEnvironment . read_only global_environment ; qualifiers = [ Reference . create " test " ] ; } in global_result
let assert_json_equal ~ context ~ expected result = let expected = Yojson . Safe . from_string expected in assert_equal ~ ctxt : context ~ printer : Yojson . Safe . pretty_to_string ~ msg " : GlobalResult json " expected result
let assert_global_result ~ context ~ test_source ~ expected ( ) = let result = type_inference_result ~ context ~ test_source in result |> TypeInference . Data . GlobalResult . to_yojson |> assert_json_equal ~ context ~ expected
let serialization_test context = assert_global_result ~ context ~ test_source : { | import functools from sqlalchemy import Integer x = 1 + 1 class C : x = 1 + 1 def no_errors ( x : int ) -> int : return x @ functools . lru_cache ( 4 ) def needs_return ( y : C , x : Integer ) : return ( x , y ) } | ~ expected : { | { " globals " : [ { " name " : " x " , " location " : { " qualifier " : " test " , " path " : " " , * " line " : 5 } , " annotation " : " int " } ] , " attributes " : [ { " parent " : " test . C " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " " , * " line " : 8 } , " annotation " : " int " } ] , " defines " : [ { " name " : " test . needs_return " , " parent " : null , " return " : " typing . Tuple [ sqlalchemy . Integer , test . C ] " , " parameters " : [ { " name " : " y " , " annotation " : null , " value " : null , " index " : 0 } , { " name " : " x " , " annotation " : null , " value " : null , " index " : 1 } ] , " location " : { " qualifier " : " test " , " path " : " " , * " line " : 14 } , " async " : false } ] } } | ( )
let duplicate_define_test context = assert_global_result ~ context ~ test_source : { | import typing @ typing . overload def f ( x : int , y ) -> int : y = " y " return x @ typing . overload def f ( x : str , y ) -> str : y = " y " return x @ typing . overload def f ( x : float , y ) -> float : y = " y " return x } | ~ expected : { | { " globals " : [ ] , " attributes " : [ ] , " defines " : [ ] } } | ( ) ; assert_global_result ~ context ~ test_source : { | import typing @ typing . overload def f ( x : int ) -> int : return x @ typing . overload def f ( x : str ) -> str : return x @ typing . overload def f ( x ) -> float : return x } | ~ expected : { | { " globals " : [ ] , " attributes " : [ ] , " defines " : [ ] } } | ( ) ; ( )
let suppress_test context = assert_global_result ~ context ~ test_source { :| x = None class Foo : x = None } | ~ expected : { | { " globals " : [ ] , " attributes " : [ ] , " defines " : [ ] } } | ( )
let attribute_widen_test context = assert_global_result ~ context ~ test_source : { | class Foo : x = None def __init__ ( self ) -> None : self . x = 1 + 1 } | ~ expected : { | { " globals " : [ ] , " attributes " : [ { " parent " : " test . Foo " , " name " : " x " , " location " : { " qualifier " : " test " , " path " : " " , * " line " : 3 } , " annotation " : " typing . Optional [ int ] " } ] , " defines " : [ ] } } | ( )
let ( ) = " typeInferenceAnalysisTest " >::: [ " serialization " >:: serialization_test ; " duplicates " >:: duplicate_define_test ; " suppress " >:: suppress_test ; " attribute_widen " >:: attribute_widen_test ; ] |> Test . run
let refine_local ~ resolution ~ name ~ annotation = match name_to_reference name with | Some reference -> Resolution . refine_local resolution ~ reference ~ annotation | None -> resolution
module ErrorMap = struct type key = { location : Location . t ; kind : int ; } [ @@ deriving compare , sexp ] module Map = Map . Make ( struct type nonrec t = key let compare = compare_key let sexp_of_t = sexp_of_key let t_of_sexp = key_of_sexp end ) let add ~ errors ( { Error . location = { Location . WithModule . start ; stop ; _ } ; _ } as error ) = let location = { Location . start ; stop } in Map . set errors ~ key { : location ; kind = Error . code error } ~ data : error end
module type Context = sig val configuration : Configuration . Analysis . t val qualifier : Reference . t val define : Define . t Node . t val resolution_fixpoint : LocalAnnotationMap . t option val error_map : TypeCheck . LocalErrorMap . t option end
module type Signature = sig type t [ @@ deriving eq ] val create : ? bottom : bool -> resolution : Resolution . t -> unit -> t val initial : resolution : Resolution . t -> t val initial_forward : resolution : Resolution . t -> t val initial_backward : forward : t -> t val widen_resolution_with_snapshots : t -> t include Fixpoint . State with type t := t end
module State ( Context : Context ) = struct module TypeCheckContext = struct let qualifier = Context . qualifier let debug = Context . configuration . debug let constraint_solving_style = Configuration . Analysis . default_constraint_solving_style let define = Context . define let resolution_fixpoint = Context . resolution_fixpoint let error_map = Context . error_map module Builder = Callgraph . NullBuilder end module TypeCheckState = TypeCheck . State ( TypeCheckContext ) type non_bottom_t = { snapshot_resolution : Resolution . t ; resolution : Resolution . t ; errors : Error . t ErrorMap . Map . t ; } type t = | Bottom | Value of non_bottom_t let value_exn = function | Bottom -> failwith " expected value , got bottom " | Value value -> value let pp format = function | Bottom -> Format . fprintf format " Bottom : true \ n " | Value { snapshot_resolution ; resolution ; errors } -> let global_resolution = Resolution . global_resolution resolution in let expected = let parser = GlobalResolution . annotation_parser global_resolution in let { Node . value = { Define . signature ; _ } ; _ } = Context . define in Annotated . Callable . return_annotation_without_applying_decorators ~ signature ~ parser in let errors = let error_to_string error = let error = let lookup reference = GlobalResolution . ast_environment global_resolution |> fun ast_environment -> AstEnvironment . ReadOnly . get_real_path_relative ast_environment reference in Error . instantiate ~ show_error_traces : true ~ lookup error in Format . asprintf " % a -> % s " Location . WithPath . pp ( Error . Instantiated . location error ) ( Error . Instantiated . description error ) in List . map ( Map . data errors ) ~ f : error_to_string |> String . concat ~ sep " :\ n " in Format . fprintf format " Expected return : % a \ n Resolution :\ n % a \ n Aggregate Resolution :\ n % a \ n Errors :\ n % s \ n " Type . pp expected Resolution . pp resolution Resolution . pp snapshot_resolution errors let show state = Format . asprintf " % a " pp state and equal left right = match left , right with | Bottom , Bottom -> true | Value left , Value right -> Resolution . refinements_equal left . resolution right . resolution | _ -> false let bottom = Bottom let create_with_errors ~ errors ~ resolution ~ snapshot_resolution = Value { snapshot_resolution ; resolution ; errors } let create ( ? bottom = false ) ~ resolution ( ) = if bottom then Bottom else create_with_errors ~ errors : ErrorMap . Map . empty ~ resolution ~ snapshot_resolution : ( Resolution . with_annotation_store resolution ~ annotation_store : Refinement . Store . empty ) let errors = function | Bottom -> [ ] | Value { resolution ; errors ; _ } -> let global_resolution = Resolution . global_resolution resolution in Map . data errors |> Error . deduplicate |> fun errors -> if Context . configuration . debug then errors else Error . filter ~ resolution : global_resolution errors let less_or_equal ~ left ~ right = match left , right with | Bottom , Bottom -> true | Bottom , Value _ -> true | Value _ , Bottom -> false | Value left , Value right -> let errors_subset = let left_errors = Map . data left . errors |> Error . Set . of_list in let right_errors = Map . data right . errors |> Error . Set . of_list in Set . is_subset left_errors ~ of_ : right_errors in errors_subset && let global_resolution = Resolution . global_resolution left . resolution in Refinement . Store . less_or_equal ~ global_resolution ~ left ( : Resolution . annotation_store left . resolution ) ~ right ( : Resolution . annotation_store right . resolution ) let widening_threshold = 3 let widen ~ previous ~ next ~ iteration = match previous , next with | Bottom , Bottom -> Bottom | Value _ , Bottom -> previous | Bottom , Value _ -> next | Value previous , Value next -> let combine_errors ~ key : _ left_error right_error = if iteration + 1 >= widening_threshold then { left_error with Error . kind = Error . Top } else Error . join ~ resolution ( : Resolution . global_resolution previous . resolution ) left_error right_error in Value { previous with errors = Map . merge_skewed previous . errors next . errors ~ combine : combine_errors ; resolution = Resolution . outer_widen_refinements ~ iteration ~ widening_threshold previous . resolution next . resolution ; snapshot_resolution = Resolution . outer_widen_refinements ~ iteration ~ widening_threshold previous . snapshot_resolution next . snapshot_resolution ; } let join left right = widen ~ previous : left ~ next : right ~ iteration : 0 let return_reference = Reference . create " $ return " let update_only_existing_annotations initial_state new_state = match initial_state , new_state with | ( Value ( { resolution = old_resolution ; _ } as initial ) , Value { resolution = new_resolution ; _ } ) -> let resolution = Resolution . update_existing_refinements ~ old_resolution ~ new_resolution in Value { initial with resolution } | _ -> new_state let widen_resolution_with_snapshots state = match state with | Bottom -> Bottom | Value ( { resolution ; snapshot_resolution ; _ } as state_value ) -> let resolution_without_unknowns = let filter _ ( annotation : Annotation . t ) = let resolved_type = Annotation . annotation annotation in not ( Type . is_top resolved_type || Type . is_any resolved_type ) in Resolution . update_refinements_with_filter ~ old_resolution : ( Resolution . with_annotation_store resolution ~ annotation_store : Refinement . Store . empty ) ~ new_resolution : resolution ~ filter in let resolution = Resolution . outer_join_refinements resolution_without_unknowns snapshot_resolution in Value { state_value with resolution } let check_entry = function | Bottom -> Bottom | Value ( { resolution ; errors ; _ } as state ) -> let { Node . value = { Define . signature = { parameters ; _ } ; _ } as define ; _ } = Context . define in let add_parameter_errors errors { Node . value = { Parameter . name ; annotation ; _ } ; location } = let add_missing_parameter_error ~ given_annotation = let reference = Reference . create name in Resolution . get_local resolution ~ reference >>= ( fun actual -> Option . some_if ( not ( Type . is_any ( Annotation . annotation actual ) ) ) actual ) >>| ( fun { Annotation . annotation ; _ } -> let error = Error . create ~ location ( : Location . with_module ~ module_reference : Context . qualifier location ) ~ kind : ( Error . MissingParameterAnnotation { name = reference ; annotation = Some annotation ; given_annotation ; evidence_locations = [ ] ; thrown_at_source = true ; } ) ~ define : Context . define in ErrorMap . add ~ errors error ) |> Option . value ~ default : errors in match annotation with | None -> add_missing_parameter_error ~ given_annotation : None | Some annotation when Type . is_any ( GlobalResolution . parse_annotation ( Resolution . global_resolution resolution ) annotation ) -> add_missing_parameter_error ~ given_annotation ( : Some Type . Any ) | _ -> errors in let parameters = if Define . is_method define && not ( Define . is_static_method define ) then List . tl parameters |> Option . value ~ default [ ] : else parameters in Value { state with errors = List . fold parameters ~ init : errors ~ f : add_parameter_errors } let initial ~ resolution = let empty_resolution = resolution in let state = TypeCheckState . initial ~ resolution in let resolution = TypeCheckState . resolution state |> Option . value ~ default : resolution in let errors = Context . error_map >>| TypeCheck . LocalErrorMap . all_errors |> Option . value ~ default [ ] : |> List . fold ~ init : ErrorMap . Map . empty ~ f ( : fun errors error -> ErrorMap . add ~ errors error ) in Value { snapshot_resolution = empty_resolution ; resolution ; errors } let initial_forward ~ resolution = let { Node . value = { Define . signature = { parameters ; parent ; _ } ; _ } as define ; _ } = Context . define in let ( { resolution ; snapshot_resolution ; _ } as state ) = value_exn ( initial ~ resolution ) in let update_parameter index ( resolution , snapshot_resolution ) { Node . value = { Parameter . name ; value ; annotation } ; _ } = match index , parent with | 0 , Some _ when Define . is_method define && not ( Define . is_static_method define ) -> resolution , snapshot_resolution | _ -> let create_new_local ~ resolution ~ annotation = let make_parameter_name name = name |> String . filter ~ f ( : function | ' ' * -> false | _ -> true ) |> Reference . create in Resolution . new_local resolution ~ reference ( : make_parameter_name name ) ~ annotation ( : Annotation . create_mutable annotation ) in let snapshot_resolution = value >>| Resolution . resolve_expression_to_type resolution >>| Type . weaken_literals >>| ( fun value_annotation -> create_new_local ~ resolution : snapshot_resolution ~ annotation : value_annotation ) |> Option . value ~ default : snapshot_resolution in let resolution = match annotation with | Some annotation when Type . is_any ( GlobalResolution . parse_annotation ( Resolution . global_resolution resolution ) annotation ) -> create_new_local ~ resolution ~ annotation : Type . Bottom | None -> create_new_local ~ resolution ~ annotation : Type . Bottom | _ -> resolution in resolution , snapshot_resolution in let resolution , snapshot_resolution = List . foldi ~ init ( : resolution , snapshot_resolution ) ~ f : update_parameter parameters in Value { state with resolution ; snapshot_resolution } let initial_backward ~ forward = match forward with | Bottom -> Bottom | Value { snapshot_resolution ; resolution ; errors } -> let resolution = let resolution_with_return = let expected_return = let parser = GlobalResolution . annotation_parser ( Resolution . global_resolution resolution ) in let { Node . value = { Define . signature ; _ } ; _ } = Context . define in Annotation . create_mutable ( Annotated . Callable . return_annotation_without_applying_decorators ~ signature ~ parser ) in Resolution . with_annotation_store resolution ~ annotation_store : Refinement . Store . empty |> Resolution . new_local ~ reference : return_reference ~ annotation : expected_return in let filter name ( annotation : Annotation . t ) = not ( Type . contains_undefined annotation . annotation || Type . is_not_instantiated annotation . annotation || Reference . equal name return_reference ) in Resolution . update_refinements_with_filter ~ old_resolution : resolution_with_return ~ new_resolution : resolution ~ filter in create_with_errors ~ errors ~ resolution ~ snapshot_resolution let forward ~ statement_key : _ state ~ statement ( { : Node . value ; _ } as statement ) = match state with | Bottom -> Bottom | Value ( { resolution ; errors ; _ } as state ) -> ( let global_resolution = Resolution . global_resolution resolution in let resolve annotation = Resolution . resolve_expression_to_type resolution annotation |> Type . weaken_literals in let validate_return ~ expression ~ actual = let create_missing_return_error expression actual = let { Node . location = define_location ; value = { Define . signature = { async ; return_annotation = return_annotation_expression ; _ } as signature ; _ ; } as define ; } = Context . define in let return_annotation = let annotation = let parser = GlobalResolution . annotation_parser global_resolution in Annotated . Callable . return_annotation_without_applying_decorators ~ signature ~ parser in if async then Type . coroutine_value annotation |> Option . value ~ default : Type . Top else annotation in let return_annotation = Type . Variable . mark_all_variables_as_bound return_annotation in let actual = GlobalResolution . resolve_mutable_literals global_resolution ~ resolve ( : Resolution . resolve_expression_to_type resolution ) ~ expression ~ resolved : actual ~ expected : return_annotation |> GlobalResolution . resolved_type in let contains_literal_any = return_annotation_expression >>| Type . expression_contains_any |> Option . value ~ default : false in if ( not ( Define . has_return_annotation define ) ) || ( contains_literal_any && Type . contains_prohibited_any return_annotation ) then let given_annotation = Option . some_if ( Define . has_return_annotation define ) return_annotation in Some ( Error . create ~ location : ( Location . with_module ~ module_reference : Context . qualifier define_location ) ~ define : Context . define ~ kind : ( Error . MissingReturnAnnotation { name = Reference . create " $ return_annotation " ; annotation = Some actual ; given_annotation ; evidence_locations = [ ] ; thrown_at_source = true ; } ) ) else None in match create_missing_return_error expression actual with | None -> state | Some error -> let emit_error errors ( { Error . location = { Location . WithModule . start ; stop ; _ } ; _ } as error ) = let error = let location = { Location . start ; stop } in match Map . find errors { ErrorMap . location ; kind = Error . code error } with | Some other_error -> Error . join ~ resolution : global_resolution error other_error | None -> error in ErrorMap . add ~ errors error in { state with errors = emit_error errors error } in match value with | Statement . Assign { value = { value = Dictionary { keywords = [ ] ; entries = [ ] } ; _ } ; target = { Node . value = Name name ; _ } ; _ ; } when is_simple_name name -> let resolution = refine_local ~ resolution ~ name ~ annotation : ( Annotation . create_mutable ( Type . dictionary ~ key : Type . Bottom ~ value : Type . Bottom ) ) in Value { state with resolution } | Statement . Assign { value = { value = List [ ] ; _ } ; target = { Node . value = Name name ; _ } ; _ } when is_simple_name name -> let resolution = refine_local ~ resolution ~ name ~ annotation ( : Annotation . create_mutable ( Type . list Type . Bottom ) ) in Value { state with resolution } | Statement . Expression { Node . value = Call { callee = { Node . value = Name ( Name . Attribute { attribute = " __setitem__ " ; base = { Node . value = Name name ; _ } as base ; _ ; } ) ; _ ; } ; arguments = [ { Call . Argument . value = key ; _ } ; { Call . Argument . value ; _ } ] ; } ; _ ; } when is_simple_name name && Type . is_dictionary ( resolve base ) -> let resolution = refine_local ~ resolution ~ name ~ annotation : ( Annotation . create_mutable ( Type . dictionary ~ key ( : resolve key ) ~ value ( : resolve value ) ) ) in Value { state with resolution } | Statement . Expression { Node . value = Call { callee = { Node . value = Name ( Name . Attribute { attribute = " append " ; base = { Node . value = Name name ; _ } as base ; _ ; } ) ; _ ; } ; arguments = [ { Call . Argument . value ; _ } ] ; } ; _ ; } when is_simple_name name && Type . is_list ( resolve base ) -> let base_element = match resolve base with | Type . Parametric { name = " list " ; parameters = [ Single parameter ] } -> parameter | base -> base in let annotation = GlobalResolution . join ( Resolution . global_resolution resolution ) ( resolve value ) base_element |> Type . list |> Annotation . create_mutable in Value { state with resolution = refine_local ~ resolution ~ name ~ annotation } | Statement . Expression { Node . value = Expression . Yield yielded ; _ } -> let { Node . value = { Define . signature = { async ; _ } ; _ } ; _ } = Context . define in let yield_type = match yielded with | Some expression -> Resolution . resolve_expression_to_type resolution expression | None -> Type . none in let actual = if async then Type . async_generator ~ yield_type ( ) else Type . generator ~ yield_type ( ) in Value ( validate_return ~ expression : None ~ actual ) | Statement . Expression { Node . value = Expression . YieldFrom yielded_from ; _ } -> let actual = Resolution . resolve_expression_to_type resolution yielded_from |> GlobalResolution . type_of_iteration_value ~ global_resolution |> Option . value ~ default : Type . Any in Value ( validate_return ~ expression : None ~ actual ) | Statement . Expression _ -> Value { state with resolution } | Statement . Return { Return . expression ; _ } -> let actual = Option . value_map expression ~ f ( : Resolution . resolve_expression_to_type resolution ) ~ default : Type . none in Value ( validate_return ~ expression ~ actual ) | _ -> ( match Resolution . resolve_statement resolution statement with | Resolution . Unreachable -> Bottom | Resolution . Reachable { resolution ; errors = statement_errors } -> Value { state with resolution ; errors = List . fold statement_errors ~ init : errors ~ f ( : fun errors error -> ErrorMap . add ~ errors error ) ; } ) ) let backward ~ statement_key : _ state ~ statement = match state with | Bottom -> Bottom | Value ( { resolution ; snapshot_resolution ; _ } as state ) -> Type . Variable . Namespace . reset ( ) ; let global_resolution = Resolution . global_resolution resolution in let resolve_usage value_type target_type = let target_type = Type . weaken_literals target_type in match value_type , target_type with | Type . Top , Type . Top -> None | Type . Top , target_type -> Some target_type | value_type , Type . Top -> Some value_type | _ -> Some ( GlobalResolution . meet global_resolution value_type target_type ) in let forward_expression ~ state { : resolution ; _ } ~ expression = Resolution . resolve_expression_to_type resolution expression in let annotate_call_accesses statement resolution = let propagate resolution { Call . callee ; arguments } = let callable = let resolved_callee = forward_expression ~ state ~ expression : callee in match resolved_callee with | Type . Callable callable -> Some callable | Type . Parametric { name = " BoundMethod " ; _ } -> ( GlobalResolution . attribute_from_annotation ( Resolution . global_resolution resolution ) ~ parent : resolved_callee ~ name " : __call__ " >>| Annotated . Attribute . annotation >>| Annotation . annotation >>= function | Type . Callable callable -> Some callable | _ -> None ) | _ -> None in match callable with | Some { Type . Callable . implementation = { Type . Callable . parameters = Type . Callable . Defined parameters ; _ } ; _ ; } -> let parameter_argument_mapping = let arguments = let process_argument argument = let expression , kind = Ast . Expression . Call . Argument . unpack argument in forward_expression ~ state ~ expression |> fun resolved -> { AttributeResolution . Argument . kind ; expression = Some expression ; resolved } in List . map arguments ~ f : process_argument in let open AttributeResolution in SignatureSelection . prepare_arguments_for_signature_selection ~ self_argument : None arguments |> SignatureSelection . get_parameter_argument_mapping ~ all_parameters ( : Type . Callable . Defined parameters ) ~ parameters ~ self_argument : None |> fun { ParameterArgumentMapping . parameter_argument_mapping ; _ } -> parameter_argument_mapping in let propagate_inferred_annotation resolution ~ parameter ~ arguments = let open Type . Callable in match parameter , arguments with | _ , [ ] | Parameter . Variable _ , _ -> resolution | Parameter . PositionalOnly { annotation = parameter_annotation ; _ } , arguments | Parameter . KeywordOnly { annotation = parameter_annotation ; _ } , arguments | Parameter . Named { annotation = parameter_annotation ; _ } , arguments | Parameter . Keywords parameter_annotation , arguments -> let refine_argument resolution argument = let rec refine resolution parameter_annotation argument_expression = match argument_expression , parameter_annotation with | ( { Node . value = Expression . Name name ; _ } as argument ) , _ when is_simple_name name && not ( Type . is_untyped parameter_annotation || Type . is_object parameter_annotation ) -> forward_expression ~ state ~ expression : argument |> resolve_usage parameter_annotation >>| ( fun refined -> Resolution . refine_local resolution ~ reference ( : name_to_reference_exn name ) ~ annotation ( : Annotation . create_mutable refined ) ) |> Option . value ~ default : resolution | ( { Node . value = Expression . Tuple argument_names ; _ } , Type . Tuple ( Concrete parameter_annotations ) ) when List . length argument_names = List . length parameter_annotations -> List . fold2_exn ~ init : resolution ~ f : refine parameter_annotations argument_names | _ -> resolution in match argument with | AttributeResolution . MatchedArgument { argument = { expression = Some expression ; _ } ; _ } -> refine resolution parameter_annotation expression | _ -> resolution in List . fold ~ f : refine_argument ~ init : resolution arguments in Map . fold ~ init : resolution ~ f ( : fun ~ key ~ data -> propagate_inferred_annotation ~ parameter : key ~ arguments : data ) parameter_argument_mapping | _ -> resolution in Visit . collect_calls statement |> List . map ~ f : Node . value |> List . fold ~ init : resolution ~ f : propagate in let resolution = match Node . value statement with | Statement . Assign { Assign . target ; value ; _ } -> ( let rec propagate_assign resolution target_annotation value = let state = { state with resolution } in match Node . value value with | Expression . Name ( Name . Identifier identifier ) -> let resolution = let resolved = forward_expression ~ state ~ expression : value in resolve_usage target_annotation resolved >>| ( fun refined -> Resolution . refine_local resolution ~ reference ( : Reference . create identifier ) ~ annotation ( : Annotation . create_mutable refined ) ) |> Option . value ~ default : resolution in annotate_call_accesses statement resolution | Call { callee = { value = Name ( Name . Attribute { attribute = " __iadd__ " ; base = { Node . value = Name name ; _ } ; _ } ) ; _ ; } ; arguments = [ { Call . Argument . value ; _ } ] ; } -> let resolution = resolve_usage target_annotation ( forward_expression ~ state ~ expression : value ) >>| ( fun refined -> refine_local ~ resolution ~ name ~ annotation ( : Annotation . create_mutable refined ) ) |> Option . value ~ default : resolution in annotate_call_accesses statement resolution | Call _ | Name _ -> annotate_call_accesses statement resolution | Tuple values -> let parameters = match target_annotation with | Type . Tuple ( Concrete parameters ) -> parameters | Type . Tuple ( Concatenation concatenation ) -> Type . OrderedTypes . Concatenation . extract_sole_unbounded_annotation concatenation >>| ( fun annotation -> List . map values ~ f ( : fun _ -> annotation ) ) |> Option . value ~ default [ ] : | _ -> [ ] in if List . length values = List . length parameters then List . fold2_exn ~ init : resolution ~ f : propagate_assign parameters values else resolution | _ -> resolution in match Node . value target , Node . value value with | Tuple targets , Tuple values when List . length targets = List . length values -> let target_annotations = let resolve expression = forward_expression ~ state { : state with resolution } ~ expression in List . map targets ~ f : resolve in List . fold2_exn ~ init : resolution ~ f : propagate_assign target_annotations values | _ , _ -> let resolved = forward_expression ~ state { : state with resolution } ~ expression : target in propagate_assign resolution resolved value ) | Return { Return . expression = Some { Node . value = Name name ; _ } ; _ } when is_simple_name name -> let return_annotation = Option . value_exn ( Resolution . get_local resolution ~ reference : return_reference ) in refine_local ~ resolution ~ name ~ annotation : return_annotation | Return { Return . expression = Some { Node . value = Tuple expressions ; _ } ; _ } -> ( let return_annotation = Option . value_exn ( Resolution . get_local resolution ~ reference : return_reference ) |> Annotation . annotation in match return_annotation with | Tuple ( Concrete parameters ) when Int . equal ( List . length parameters ) ( List . length expressions ) -> List . fold2_exn parameters expressions ~ init : resolution ~ f ( : fun resolution annotation expression -> match Node . value expression with | Name name when is_simple_name name -> refine_local ~ resolution ~ name ~ annotation ( : Annotation . create_mutable annotation ) | _ -> resolution ) | _ -> resolution ) | _ -> annotate_call_accesses statement resolution in let resolution , snapshot_resolution = match Node . value statement with | Statement . Assign { target = { Node . value = Name name ; _ } as target ; _ } when is_simple_name name -> let target_reference = Ast . Expression . name_to_reference_exn name in let wiped_resolution = Resolution . unset_local resolution ~ reference : target_reference in let augmented_snapshot_resolution = let existing_snapshot = forward_expression ~ state { : state with resolution = snapshot_resolution } ~ expression : target in let current_snapshot = forward_expression ~ state { : state with resolution } ~ expression : target |> Type . weaken_literals in let snapshot = match existing_snapshot , current_snapshot with | existing , current when Type . is_untyped existing && Type . is_untyped current -> None | existing , _ when Type . is_untyped existing -> Some current_snapshot | _ , current when Type . is_untyped current -> Some existing_snapshot | _ -> Some ( GlobalResolution . join global_resolution existing_snapshot current_snapshot ) in snapshot >>| Annotation . create_mutable >>| ( fun annotation -> Resolution . new_local snapshot_resolution ~ reference : target_reference ~ annotation ) |> Option . value ~ default : snapshot_resolution in wiped_resolution , augmented_snapshot_resolution | _ -> resolution , snapshot_resolution in Value { state with resolution ; snapshot_resolution } end
let infer_local ~ configuration ~ global_resolution ~ source { : Source . source_path = { ModulePath . qualifier ; _ } ; _ } ~ define : ( { Node . location ; value = { Define . signature = { name ; _ } ; _ } as define } as define_node ) = let module State = State ( struct let configuration = configuration let qualifier = qualifier let define = Node . create ~ location define let resolution_fixpoint = Some ( LocalAnnotationMap . empty ( ) ) let error_map = Some ( TypeCheck . LocalErrorMap . empty ( ) ) end ) in let resolution = TypeCheck . resolution global_resolution ( module State . TypeCheckContext ) in let module Fixpoint = Fixpoint . Make ( State ) in Log . log ~ section ` : Check " Checking % a " Reference . pp name ; let dump = Define . dump define in if dump then ( Log . dump " Checking ` % s ` . . . " ( Log . Color . yellow ( Reference . show name ) ) ; Log . dump " AST :\ n % s " ( Annotated . Define . create define_node |> Annotated . Define . show ) ) ; let print_state name state = if dump then Log . dump " % s state :\ n % a " name State . pp state ; state in let cfg = Cfg . create define in let backward_fixpoint ~ initial_state = let rec fixpoint iteration ~ initial_state = let final_state = Fixpoint . forward ~ cfg ~ initial : initial_state |> Fixpoint . exit >>| ( fun forward_exit_state -> State . initial_backward ~ forward : forward_exit_state ) |> Option . value ~ default : initial_state |> ( fun initial_backward_state -> Fixpoint . backward ~ cfg ~ initial : initial_backward_state ) |> Fixpoint . entry in let updated_initial_state = final_state >>| State . update_only_existing_annotations initial_state >>| ( fun post -> State . widen ~ previous : initial_state ~ next : post ~ iteration ) |> Option . value ~ default : initial_state in if State . less_or_equal ~ left : updated_initial_state ~ right : initial_state then final_state else fixpoint ( iteration + 1 ) ~ initial_state : updated_initial_state in fixpoint 0 ~ initial_state in let exit = backward_fixpoint ~ initial_state ( : State . initial_forward ~ resolution ) >>| State . widen_resolution_with_snapshots >>| print_state " Entry " >>| State . check_entry in exit >>| State . errors |> Option . value ~ default [ ] :
let infer_parameters_from_parent ~ global_resolution ~ source { : Source . source_path = { ModulePath . qualifier ; _ } ; _ } ~ define ( { : Node . value = { Define . signature = { parent ; parameters ; _ } ; _ } ; _ } as define ) = let overridden_callable = parent >>| Reference . show >>= GlobalResolution . overrides ~ resolution : global_resolution ~ name ( : Define . unqualified_name ( Node . value define ) ) in let missing_parameter_errors overridden_attribute = match Annotation . annotation ( Annotated . Attribute . annotation overridden_attribute ) with | Type . Parametric { name = " BoundMethod " ; parameters = [ Single ( Type . Callable { implementation = { parameters = Defined overridden_parameters ; _ } ; _ } ) ; _ ; ] ; } | Type . Callable { Type . Callable . implementation = { parameters = Defined overridden_parameters ; _ } ; _ } -> let should_annotate name = match Identifier . sanitized name with | " self " | " cls " -> false | _ -> true in let missing_parameter_error = function | ` Both ( overridden_parameter , overriding_parameter ) -> ( match ( Type . Callable . RecordParameter . annotation overridden_parameter , Type . Callable . RecordParameter . annotation overriding_parameter ) with | ( Some overridden_annotation , Some { Node . value = { Parameter . name ; annotation = None ; _ } ; location } ) when ( not ( Type . is_any overridden_annotation ) ) && ( not ( Type . contains_variable overridden_annotation ) ) && should_annotate name -> Some ( Error . create ~ location ( : Location . with_module ~ module_reference : qualifier location ) ~ kind : ( Error . MissingParameterAnnotation { name = Reference . create name ; annotation = Some overridden_annotation ; given_annotation = None ; evidence_locations = [ ] ; thrown_at_source = true ; } ) ~ define ) | _ -> None ) | ` Left _ -> None | ` Right _ -> None in let overriding_parameters = let to_type_parameter ( { Node . value = { Parameter . name ; _ } ; _ } as parameter ) = { Type . Callable . RecordParameter . name ; annotation = parameter ; default = false } in List . map parameters ~ f : to_type_parameter |> Type . Callable . Parameter . create in Type . Callable . Parameter . zip overridden_parameters overriding_parameters |> List . filter_map ~ f : missing_parameter_error | _ -> [ ] in overridden_callable >>| missing_parameter_errors |> Option . value ~ default [ ] :
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 " , [ ] ) ) ; }