text
stringlengths 0
601k
|
---|
type uint32 = float object method byteLength : int readonly_prop method slice : int -> int -> arrayBuffer t meth method slice_toEnd : int -> arrayBuffer t meth end |
let arrayBuffer : ( int -> arrayBuffer t ) constr = Js . Unsafe . global . ## _ArrayBuffer object method buffer : arrayBuffer t readonly_prop method byteOffset : int readonly_prop method byteLength : int readonly_prop end object inherit arrayBufferView method _BYTES_PER_ELEMENT : int readonly_prop method length : int readonly_prop method set_fromArray : ' a js_array t -> int -> unit meth method set_fromTypedArray : ( ' a , ' b ) typedArray t -> int -> unit meth method subarray : int -> int -> ( ' a , ' b ) typedArray t meth method subarray_toEnd : int -> ( ' a , ' b ) typedArray t meth method slice : int -> int -> ( ' a , ' b ) typedArray t meth method slice_toEnd : int -> ( ' a , ' b ) typedArray t meth method _content_type_ : ' b optdef readonly_prop end |
type int8Array = ( int , Bigarray . int8_signed_elt ) typedArray |
type uint8Array = ( int , Bigarray . int8_unsigned_elt ) typedArray |
type int16Array = ( int , Bigarray . int16_signed_elt ) typedArray |
type uint16Array = ( int , Bigarray . int16_unsigned_elt ) typedArray |
type int32Array = ( int32 , Bigarray . int32_elt ) typedArray |
type uint32Array = ( int32 , Bigarray . int32_elt ) typedArray |
type float32Array = ( float , Bigarray . float32_elt ) typedArray |
type float64Array = ( float , Bigarray . float64_elt ) typedArray = " caml_ba_kind_of_typed_array " ( ' a , ' b , Bigarray . c_layout ) Bigarray . Genarray . t -> ( ' a , ' b ) typedArray t = " caml_ba_to_typed_array " ( ' a , ' b ) typedArray t -> ( ' a , ' b , Bigarray . c_layout ) Bigarray . Genarray . t = " caml_ba_from_typed_array " |
let set : ( ' a , ' b ) typedArray t -> int -> ' a -> unit = fun a i v -> array_set ( Unsafe . coerce a ) i v |
let get : ( ' a , ' b ) typedArray t -> int -> ' a optdef = fun a i -> Js . Unsafe . get a i |
let unsafe_get : ( ' a , ' b ) typedArray t -> int -> ' a = fun a i -> Js . Unsafe . get a i object inherit arrayBufferView method getInt8 : int -> int meth method getUint8 : int -> int meth method getInt16 : int -> int meth method getInt16_ : int -> bool t -> int meth method getUint16 : int -> int meth method getUint16_ : int -> bool t -> int meth method getInt32 : int -> int meth method getInt32_ : int -> bool t -> int meth method getUint32 : int -> uint32 meth method getUint32_ : int -> bool t -> uint32 meth method getFloat32 : int -> float meth method getFloat32_ : int -> bool t -> float meth method getFloat64 : int -> float meth method getFloat64_ : int -> bool t -> float meth method setInt8 : int -> int -> unit meth method setUint8 : int -> int -> unit meth method setInt16 : int -> int -> unit meth method setInt16_ : int -> int -> bool t -> unit meth method setUint16 : int -> int -> unit meth method setUint16_ : int -> int -> bool t -> unit meth method setInt32 : int -> int -> unit meth method setInt32_ : int -> int -> bool t -> unit meth method setUint32 : int -> uint32 -> unit meth method setUint32_ : int -> uint32 -> bool t -> unit meth method setFloat32 : int -> float -> unit meth method setFloat32_ : int -> float -> bool t -> unit meth method setFloat64 : int -> float -> unit meth method setFloat64_ : int -> float -> bool t -> unit meth end |
module Bigstring = struct type t = ( char , Bigarray . int8_unsigned_elt , Bigarray . c_layout ) Bigarray . Array1 . t external to_arrayBuffer : t -> arrayBuffer Js . t = " bigstring_to_array_buffer " external to_uint8Array : t -> uint8Array Js . t = " bigstring_to_typed_array " external of_arrayBuffer : arrayBuffer Js . t -> t = " bigstring_of_array_buffer " external of_uint8Array : uint8Array Js . t -> t = " bigstring_of_typed_array " end |
module String = struct external of_uint8Array : uint8Array Js . t -> string = " caml_string_of_array " let of_arrayBuffer ab = let uint8 = new % js uint8Array_fromBuffer ab in of_uint8Array uint8 end |
module AnalysisErrorValue = struct type t = Error . t list let prefix = Prefix . make ( ) let description = " Raw analysis errors " end |
module LocalAnnotationsValue = struct type t = LocalAnnotationMap . ReadOnly . t let prefix = Prefix . make ( ) let description = " Node type resolution " end |
module RawErrors = Memory . FirstClass . NoCache . Make ( SharedMemoryKeys . ReferenceKey ) ( AnalysisErrorValue ) |
module LocalAnnotations = Memory . FirstClass . WithCache . Make ( SharedMemoryKeys . ReferenceKey ) ( LocalAnnotationsValue ) |
type t = { global_environment : AnnotatedGlobalEnvironment . t ; set_errors : Reference . t -> Error . t list -> unit ; set_local_annotations : Reference . t -> LocalAnnotationMap . ReadOnly . t -> unit ; invalidate : Reference . t list -> unit ; get_errors : Reference . t -> Error . t list ; get_local_annotations : Reference . t -> LocalAnnotationMap . ReadOnly . t option ; } |
let global_environment { global_environment ; _ } = global_environment |
let ast_environment { global_environment ; _ } = AnnotatedGlobalEnvironment . ast_environment global_environment |
let module_tracker type_environment = ast_environment type_environment |> AstEnvironment . module_tracker |
let set_errors { set_errors ; _ } = set_errors |
let get_errors { get_errors ; _ } = get_errors |
let set_local_annotations { set_local_annotations ; _ } = set_local_annotations |
let get_local_annotations { get_local_annotations ; _ } = get_local_annotations |
let invalidate { invalidate ; _ } = invalidate |
let create global_environment = let raw_errors = RawErrors . create ( ) in let local_annotations = LocalAnnotations . create ( ) in let get_errors reference = RawErrors . get raw_errors reference |> Option . value ~ default [ ] : in let set_errors = RawErrors . add raw_errors in let get_local_annotations = LocalAnnotations . get local_annotations in let set_local_annotations = LocalAnnotations . add local_annotations in let invalidate qualifiers = RawErrors . KeySet . of_list qualifiers |> RawErrors . remove_batch raw_errors ; LocalAnnotations . KeySet . of_list qualifiers |> LocalAnnotations . remove_batch local_annotations in { global_environment ; set_errors ; set_local_annotations ; invalidate ; get_errors ; get_local_annotations ; } |
module ReadOnly = struct type t = { global_environment : AnnotatedGlobalEnvironment . ReadOnly . t ; get_errors : Reference . t -> Error . t list ; get_local_annotations : Reference . t -> LocalAnnotationMap . ReadOnly . t option ; } let create ( ? get_errors = fun _ -> [ ] ) ( ? get_local_annotations = fun _ -> None ) global_environment = { global_environment ; get_errors ; get_local_annotations } let global_environment { global_environment ; _ } = global_environment let global_resolution { global_environment ; _ } = GlobalResolution . create global_environment let ast_environment { global_environment ; _ } = AnnotatedGlobalEnvironment . ReadOnly . ast_environment global_environment let unannotated_global_environment { global_environment ; _ } = AnnotatedGlobalEnvironment . ReadOnly . unannotated_global_environment global_environment let get_errors { get_errors ; _ } = get_errors let get_local_annotations { get_local_annotations ; _ } = get_local_annotations end |
let read_only { global_environment ; get_errors ; get_local_annotations ; _ } = ReadOnly . create ~ get_errors ~ get_local_annotations ( AnnotatedGlobalEnvironment . read_only global_environment ) |
let test_type_guard context = let assert_type_errors = assert_type_errors ~ context in let assert_default_type_errors = assert_default_type_errors ~ context in assert_default_type_errors { | from typing import Any , List , TypeGuard def is_str_list ( val : List [ Any ] ) -> TypeGuard [ List [ str ] ] : " " " Determines whether all objects in the list are strings " " " return all ( isinstance ( x , str ) for x in val ) def foo ( xs : List [ int | str ] ) -> None : if is_str_list ( xs ) : reveal_type ( xs ) else : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ typing . Union [ int , str ] ] ` . " ; ] ; assert_type_errors { | from typing import TypeVar , TypeGuard , Tuple _T = TypeVar ( " _T " ) def is_two_element_tuple ( val : Tuple [ _T , . . . ] ) -> TypeGuard [ Tuple [ _T , _T ] ] : return len ( val ) == 2 def func ( names : Tuple [ str , . . . ] ) -> None : if is_two_element_tuple ( names ) : reveal_type ( names ) # Tuple [ str , str ] else : reveal_type ( names ) # Tuple [ str , . . . ] } | [ " Revealed type [ - 1 ] : Revealed type for ` names ` is ` Tuple [ str , str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` names ` is ` typing . Tuple [ str , . . . ] ` . " ; ] ; assert_type_errors { | from typing import List , TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) class Foo ( ) : x : List [ int | str ] = [ 5 , " hello " ] def bar ( ) -> None : obj = Foo ( ) if is_str_list ( obj . x ) : reveal_type ( obj . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` obj . x ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import List , TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) x : List [ int | str ] = [ 5 , " hello " ] if is_str_list ( x ) : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import List , TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) class Foo ( ) : x : List [ int | str ] = [ 5 , " hello " ] obj = Foo ( ) if is_str_list ( obj . x ) : reveal_type ( obj . x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` obj . x ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import TypeGuard , List def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) def bar ( xs : List [ int | str ] ) -> None : if is_str_list ( val = xs ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ typing . Union [ int , str ] ] ` . " ] ; assert_default_type_errors { | from typing import List , TypeGuard , TypedDict , Any , Dict class Person ( TypedDict ) : name : str age : int def is_person ( val : Dict [ Any , Any ] ) -> " TypeGuard [ Person ] " : try : return isinstance ( val [ " name " ] , str ) and isinstance ( val [ " age " ] , int ) except KeyError : return False def print_age ( val : Dict [ Any , Any ] ) -> None : if is_person ( val ) : reveal_type ( val ) print ( f " Age : { val [ ' age ' ] } " ) else : print ( " Not a person " ) ! } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` Person ` . " ] ; assert_type_errors { | from typing import List , TypeGuard , TypedDict , Any , Dict def all_values_int ( d : Dict [ str , Any ] ) -> TypeGuard [ Dict [ str , int ] ] : return all ( isinstance ( val , int ) for val in d . values ( ) ) def foo ( x : Dict [ str , Any ] ) -> None : if all_values_int ( x ) : reveal_type ( x ) } | [ " Revealed type [ - 1 ] : Revealed type for ` x ` is ` Dict [ str , int ] ` . " ] ; ( ) |
let test_multiple_arguments 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 , List def is_str_list ( val : List [ int | str ] , allow_empty : bool ) -> TypeGuard [ List [ str ] ] : if len ( val ) == 0 : return allow_empty return all ( isinstance ( x , str ) for x in val ) def foo ( xs : List [ int | str ] ) -> None : if is_str_list ( xs , True ) : reveal_type ( xs ) elif is_str_list ( xs , False ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; ] ; assert_default_type_errors { | from typing import TypeGuard , List , TypeVar , Any , Type _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 ( xs : List [ int | str ] ) -> None : if is_list_of ( xs , int ) : reveal_type ( xs ) elif is_list_of ( xs , str ) : reveal_type ( xs ) else : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ int ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ typing . Union [ int , str ] ] ` . " ; ] ; ( ) |
let test_methods context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import List , TypeGuard class Foo : def is_str_list ( self , val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) def bar ( self , xs : List [ int | str ] ) -> None : if self . is_str_list ( xs ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import List , TypeGuard class Foo : def is_str_list ( self , val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) def bar ( xs : List [ int | str ] ) -> None : if Foo ( ) . is_str_list ( xs ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import TypeGuard , List class Foo : def is_str_list ( self , val : List [ int | str ] , allow_empty : bool ) -> TypeGuard [ List [ str ] ] : if len ( val ) == 0 : return allow_empty return all ( isinstance ( x , str ) for x in val ) def bar ( self , xs : List [ int | str ] ) -> None : if self . is_str_list ( xs , True ) : reveal_type ( xs ) elif self . is_str_list ( xs , False ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ; ] ; assert_type_errors { | from typing import TypeGuard , List class Foo : @ classmethod def is_str_list ( cls , val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) def bar ( xs : List [ int | str ] ) -> None : if Foo . is_str_list ( xs ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ] ; assert_type_errors { | from typing import TypeGuard , List class Foo : @ staticmethod def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) def bar ( xs : List [ int | str ] ) -> None : if Foo . is_str_list ( xs ) : reveal_type ( xs ) } | [ " Revealed type [ - 1 ] : Revealed type for ` xs ` is ` List [ str ] ` . " ] ; ( ) |
let test_callback 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 Callable , TypeGuard def simple_fn ( x : bool , is_int : Callable [ [ object ] , TypeGuard [ int ] ] ) -> None : val : int | str = 5 if x else " foo " if is_int ( val ) : reveal_type ( val ) } | [ " Revealed type [ - 1 ] : Revealed type for ` val ` is ` int ` . " ] ; assert_default_type_errors { | from typing import Callable , TypeGuard , TypeVar , Any , overload _T = TypeVar ( " _T " ) def returns_typeguard ( ) -> TypeGuard [ int ] : . . . def returns_bool ( ) -> bool : . . . def simple_fn ( callback : Callable [ [ ] , bool ] ) -> None : . . . @ overload def overloaded_fn ( callback : Callable [ [ ] , TypeGuard [ _T ] ] ) -> _T : . . . @ overload def overloaded_fn ( callback : Callable [ [ ] , bool ] ) -> None : . . . def overloaded_fn ( callback : Callable [ [ ] , Any ] ) -> Any : . . . x1 : None = simple_fn ( returns_typeguard ) x2 : None = simple_fn ( returns_bool ) x3 : int = overloaded_fn ( returns_typeguard ) x4 : None = overloaded_fn ( returns_bool ) } | [ ] ; ( ) |
let test_return_type 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 List , TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return all ( isinstance ( x , str ) for x in val ) } | [ ] ; assert_type_errors { | from typing import List , TypeGuard def is_str_list ( val : List [ int | str ] ) -> TypeGuard [ List [ str ] ] : return 5 } | [ " Incompatible return type [ 7 ] : Expected ` bool ` but got ` int ` . " ] ; assert_type_errors { | from typing import TypeGuard x : int = 5 def typeguard_parameter_should_be_a_type ( x : int ) -> TypeGuard [ x ] : return True } | [ " Undefined or invalid type [ 11 ] : Annotation ` x ` is not defined as a type . " ] ; assert_type_errors { | from typing import TypeGuard def typeguard_takes_only_one_parameter ( x : int ) -> TypeGuard [ int , int ] : return True } | [ " Invalid type parameters [ 24 ] : Generic type ` TypeGuard ` expects 1 type parameter , received 2 . " ] ; assert_type_errors { | from typing import TypeGuard def typeguard_needs_a_parameter ( x : int ) -> TypeGuard : return True } | [ " Invalid type parameters [ 24 ] : Generic type ` TypeGuard ` expects 1 type parameter . " ] ; assert_default_type_errors { | from typing import TypeGuard , List , TypeVar , Any , Type _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 is_str_list ( val : List [ Any ] ) -> TypeGuard [ List [ str ] ] : return is_list_of ( val , str ) } | [ ] ; ( ) |
let test_walrus_operator context = let assert_type_errors = assert_type_errors ~ context in assert_type_errors { | from typing import TypeGuard def typeguard_fn ( val : int | str ) -> TypeGuard [ int ] : return True def foo ( x : int | str ) -> None : if typeguard_fn ( bar := x ) : reveal_type ( bar ) } | [ " Revealed type [ - 1 ] : Revealed type for ` bar ` is ` typing . Union [ int , str ] ` . " ] ; ( ) |
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 [ ] : |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.