text
stringlengths
12
786k
let get_replace typ = match ( repr typ ) . type_desc with Treplace typ -> Some typ | _ -> None
let get_rev_arrow_args typ = let rec go args typ = let typ = repr typ in match typ . type_desc with | Tarrow ( typ1 , typ2 , explicit , label ) -> go ( ( typ1 , explicit , label ) :: args ) typ2 | _ -> ( args , typ ) in go [ ] typ
let rec get_rev_implicits acc typ = match typ . type_desc with | Tarrow ( typ1 , typ2 , Implicit , label ) -> get_rev_implicits ( ( label , typ1 ) :: acc ) typ2 | _ -> ( acc , typ )
let get_implicits typ = let implicits , typ = get_rev_implicits [ ] typ in ( List . rev implicits , typ )
let get_rev_implicits typ = get_rev_implicits [ ] typ
let contains typ ~ in_ = let typ = repr typ in let equal in_ = phys_equal typ ( repr in_ ) in let rec contains in_ = let in_ = repr in_ in match in_ . type_desc with | Tvar _ -> false | Ttuple typs -> List . exists ~ f : equal typs || List . exists ~ f : contains typs | Tarrow ( typ1 , typ2 , _explicit , _label ) -> equal typ1 || equal typ2 || contains typ1 || contains typ2 | Tctor variant -> List . exists ~ f : equal variant . var_params || List . exists ~ f : contains variant . var_params | Tpoly ( typs , typ ) -> List . exists ~ f : equal typs || equal typ || List . exists ~ f : contains typs || contains typ | Tconv typ ' -> let typ ' = get_mode typ . type_mode typ ' in equal typ ' || contains typ ' | Topaque typ ' -> equal typ ' || contains typ ' | Tother_mode typ ' -> equal typ ' || contains typ ' | Tref _ -> assert false | Treplace _ -> assert false | Trow { row_tags ; row_closed = _ ; row_rest ; row_presence_proxy = _ } -> Map . exists row_tags ~ f ( : fun ( _ , _ , args ) -> List . exists ~ f : equal args ) || equal row_rest || Map . exists row_tags ~ f ( : fun ( _ , _ , args ) -> List . exists ~ f : contains args ) || contains row_rest in contains in_
let rec get_same_mode typ1 typ2 = let typ1 = repr typ1 in let typ2 = repr typ2 in match ( typ1 . type_desc , typ2 . type_desc ) with | Tother_mode typ1 ' , Tother_mode typ2 ' -> ( match ( typ1 . type_mode , typ2 . type_mode ) with | Checked , Checked | Prover , Prover -> get_same_mode typ1 ' typ2 ' | Checked , Prover -> get_same_mode typ1 typ2 ' | Prover , Checked -> get_same_mode typ1 ' typ2 ) | Tother_mode typ1 , _ when equal_mode typ1 . type_mode typ2 . type_mode -> ( repr typ1 , typ2 ) | _ , Tother_mode typ2 when equal_mode typ1 . type_mode typ2 . type_mode -> ( typ1 , repr typ2 ) | _ -> ( typ1 , typ2 )
let rec remove_opaques typ = let typ = repr typ in match typ . type_desc with Topaque typ -> remove_opaques typ | _ -> typ
let rec remove_mode_changes typ = let typ = repr typ in match typ . type_desc with | Tother_mode typ -> remove_mode_changes typ | _ -> typ
module Decl = struct let decl_id = ref 0 let next_id ( ) = incr decl_id ; ! decl_id let mk ~ name ~ params desc = incr decl_id ; let tdec_ret = Mk . ctor ~ mode ( : Ident . mode name ) 10000 ( Path . Pident name ) params in { tdec_params = params ; tdec_desc = desc ; tdec_id = ! decl_id ; tdec_ret } end
let report_error ppf = function | Mk_wrong_mode ( kind , typs , mode , typ ) -> fprintf ppf " [ @< hov > Internal error : Could not make a type % s from types ; @\ [ @< hov2 >% a ] ; @@\ The type % a was expected to have mode % a . ] " @ kind ( pp_print_list ~ pp_sep : pp_print_newline Debug_print . type_expr ) typs Debug_print . type_expr typ pp_mode mode | Mk_invalid ( kind , typs , typ ) -> fprintf ppf " [ @< hov > Internal error : Could not make a type % s from types ; @\ [ @< hov2 >% a ] ; @@\ The type % a was invalid . ] " @ kind ( pp_print_list ~ pp_sep : pp_print_newline Debug_print . type_expr_alts ) typs Debug_print . type_expr_alts typ
let ( ) = Location . register_error_of_exn ( function | Error ( loc , err ) -> Some ( Location . error_of_printer loc report_error err ) | _ -> None )
let shared_computation = Bonsai_web_ui_typeahead . Typeahead . create ( module Data ) ~ all_options ( : Value . return Data . all ) ~ placeholder " : Select a value " ~ to_string ( : Bonsai . Value . return Data . to_string ) ; ;
let view_computation = let % sub _ , view , _ = shared_computation in return view ; ;
let view_and_inject_computation = let % sub _ , view , inject = shared_computation in return ( Value . both view inject ) ; ;
let view_and_result_computation = let % sub result , view , _ = shared_computation in return ( Value . both view result ) ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; let before = [ % expect . output ] in Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string Data . Option_C ) ; Handle . show handle ; let after = [ % expect . output ] in Expect_test_patdiff . print_patdiff before after ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( module struct type incoming = Data . t option type t = Vdom . Node . t * ( Data . t option -> unit Ui_effect . t ) let view ( vdom , _ ) = let module V = ( val Result_spec . vdom Fn . id ) in V . view vdom ; ; let incoming ( _ , inject ) = inject end ) view_and_inject_computation in Handle . show handle ; let _before = [ % expect . output ] in Handle . do_actions handle [ Some Data . Option_A ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " -| value " " = +| value " = Option A " -| # value " " = +| # value " = Option A " onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] ; | Handle . do_actions handle [ None ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " -| value " = Option A " +| value " " = -| # value " = Option A " +| # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . sexp ( module struct type t = Vdom . Node . t * Data . t option let sexp_of_t ( _view , result ) = [ % sexp_of : Data . t option ] result end ) ) view_and_result_computation in Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : O " ; Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : C " ; Handle . show handle ; [ % expect { | ( Option_C ) } ] | ; ;
let shared_computation = Bonsai_web_ui_typeahead . Typeahead . create_multi ( module Data ) ~ all_options ( : Value . return Data . all ) ~ placeholder " : Select a value " ~ to_string : Data . to_string ~ split ( : String . split ~ on ' , ' ) : ; ;
let view_computation = let % sub _ , vdom , _ = shared_computation in return vdom ; ;
let view_and_set_computation = let % sub _ , vdom , set = shared_computation in return ( Value . both vdom set ) ; ;
let view_and_result_computation = let % sub result , vdom , _ = shared_computation in return ( Value . both vdom result ) ; ;
let input_value handle value = Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string value ) ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . show handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . store_view handle ; input_value handle Data . Option_B ; input_value handle Data . Option_C ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in input_value handle Data . Option_B ; input_value handle Data . Option_C ; Handle . store_view handle ; Handle . click_on handle ~ get_vdom : Fn . id ~ selector " [ : data - value = Option B ] " ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > </ datalist > < div class " = bonsai - web - ui - typeahead - pills " > < span tabindex " = 0 " data - value " = Option C " onclick onkeyup > Option C × </ span > </ div > </ div > } ] | ; ; let handle = Handle . create ( module struct type incoming = Data . Set . t type t = Vdom . Node . t * ( Data . Set . t -> unit Ui_effect . t ) let view ( vdom , _ ) = let module V = ( val Result_spec . vdom Fn . id ) in V . view vdom ; ; let incoming ( _ , inject ) = inject end ) view_and_set_computation in Handle . store_view handle ; Handle . do_actions handle [ Data . Set . of_list [ Data . Option_C ] ] ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > < option value " = Option A " > Option A </ option > < option value " = Option B " > Option B </ option > </ datalist > </ div > } ] | ; ; let handle = Handle . create ( Result_spec . sexp ( module struct type t = Vdom . Node . t * Data . Set . t let sexp_of_t ( _view , result ) = [ % sexp_of : Data . Set . t ] result end ) ) view_and_result_computation in Handle . show handle ; [ % expect { | ( ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : b " ; Handle . show handle ; [ % expect { | ( Option_B ) } ] ; | Handle . input_text handle ~ get_vdom : Tuple2 . get1 ~ selector " : input " ~ text " : C " ; Handle . show handle ; [ % expect { | ( Option_B Option_C ) } ] | ; ; let handle = Handle . create ( Result_spec . vdom Fn . id ) view_computation in Handle . store_view handle ; Handle . input_text handle ~ get_vdom : Fn . id ~ selector " : input " ~ text ( : Data . to_string Data . Option_A ^ " , " ^ Data . to_string Data . Option_B ) ; Handle . show_diff handle ; [ % expect { | < div > < input type " = text " list " = bonsai_path_replaced_in_test " placeholder " = Select a value " value " " = # value " " = onchange > </ input > < datalist id " = bonsai_path_replaced_in_test " > -| < option value " = Option A " > Option A </ option > -| < option value " = Option B " > Option B </ option > < option value " = Option C " > Option C </ option > </ datalist > +| < div class " = bonsai - web - ui - typeahead - pills " > +| < span tabindex " = 0 " data - value " = Option A " onclick onkeyup > Option A × </ span > +| < span tabindex " = 0 " data - value " = Option B " onclick onkeyup > Option B × </ span > +| </ div > </ div > } ] | ; ;
let preprocess ~ pp ~ ext text = let sourcefile = Filename . temp_file " caml " ext in begin try let oc = open_out_bin sourcefile in output_string oc text ; flush oc ; close_out oc with _ -> failwith " Preprocessing error " end ; let tmpfile = Filename . temp_file " camlpp " ext in let comm = Printf . sprintf " % s % s > % s " pp sourcefile tmpfile in if Ccomp . command comm <> 0 then begin Sys . remove sourcefile ; Sys . remove tmpfile ; failwith " Preprocessing error " end ; Sys . remove sourcefile ; tmpfile
let parse_pp ~ parse ~ wrap ~ ext text = match ! Clflags . preprocessor with None -> parse ( Lexing . from_string text ) | Some pp -> let tmpfile = preprocess ~ pp ~ ext text in let ast_magic = if ext = " . ml " then Config . ast_impl_magic_number else Config . ast_intf_magic_number in let ic = open_in_bin tmpfile in let ast = try let buffer = String . create ( String . length ast_magic ) in really_input ic buffer 0 ( String . length ast_magic ) ; if buffer = ast_magic then begin ignore ( input_value ic ) ; wrap ( input_value ic ) end else if String . sub buffer 0 9 = String . sub ast_magic 0 9 then raise Outdated_version else raise Exit with Outdated_version -> close_in ic ; Sys . remove tmpfile ; failwith " Ocaml and preprocessor have incompatible versions " | _ -> seek_in ic 0 ; parse ( Lexing . from_channel ic ) in close_in ic ; Sys . remove tmpfile ; ast
let nowarnings = ref false
let f txt = let error_messages = ref [ ] in let text = Jg_text . get_all txt . tw and env = ref ( Env . open_pers_signature " Pervasives " Env . initial ) in let tl , ew , end_message = Jg_message . formatted ~ title " : Warnings " ~ ppf : Format . err_formatter ( ) in Text . tag_remove txt . tw ~ tag " : error " ~ start : tstart ~ stop : tend ; txt . structure <- [ ] ; txt . type_info <- [ ] ; txt . signature <- [ ] ; txt . psignature <- [ ] ; ignore ( Stypes . get_info ( ) ) ; Clflags . annotations := true ; begin try if Filename . check_suffix txt . name " . mli " then let psign = parse_pp text ~ ext " . : mli " ~ parse : Parse . interface ~ wrap ( : fun x -> x ) in txt . psignature <- psign ; txt . signature <- Typemod . transl_signature ! env psign else let psl = parse_pp text ~ ext " . : ml " ~ parse : Parse . use_file ~ wrap ( : fun x -> [ Parsetree . Ptop_def x ] ) in List . iter psl ~ f : begin function Ptop_def pstr -> let str , sign , env ' = Typemod . type_structure ! env pstr Location . none in txt . structure <- txt . structure @ str ; txt . signature <- txt . signature @ sign ; env := env ' | Ptop_dir _ -> ( ) end ; txt . type_info <- Stypes . get_info ( ) ; with Lexer . Error _ | Syntaxerr . Error _ | Typecore . Error _ | Typemod . Error _ | Typeclass . Error _ | Typedecl . Error _ | Typetexp . Error _ | Includemod . Error _ | Env . Error _ | Ctype . Tags _ | Failure _ as exn -> txt . type_info <- Stypes . get_info ( ) ; let et , ew , end_message = Jg_message . formatted ~ title " : Error " ! ( ) in error_messages := et :: ! error_messages ; let range = match exn with Lexer . Error ( err , l ) -> Lexer . report_error Format . std_formatter err ; l | Syntaxerr . Error err -> Syntaxerr . report_error Format . std_formatter err ; begin match err with Syntaxerr . Unclosed ( l , _ , _ , _ ) -> l | Syntaxerr . Other l -> l end | Typecore . Error ( l , err ) -> Typecore . report_error Format . std_formatter err ; l | Typeclass . Error ( l , err ) -> Typeclass . report_error Format . std_formatter err ; l | Typedecl . Error ( l , err ) -> Typedecl . report_error Format . std_formatter err ; l | Typemod . Error ( l , err ) -> Typemod . report_error Format . std_formatter err ; l | Typetexp . Error ( l , err ) -> Typetexp . report_error Format . std_formatter err ; l | Includemod . Error errl -> Includemod . report_error Format . std_formatter errl ; Location . none | Env . Error err -> Env . report_error Format . std_formatter err ; Location . none | Ctype . Tags ( l , l ' ) -> Format . printf " In this program , @ variant constructors @ ` % s and ` % s @ have same hash value . . " @ l l ' ; Location . none | Failure s -> Format . printf " % s . . " @ s ; Location . none | _ -> assert false in end_message ( ) ; let s = range . loc_start . Lexing . pos_cnum in let e = range . loc_end . Lexing . pos_cnum in if s < e then Jg_text . tag_and_see txt . tw ~ start ( : tpos s ) ~ stop ( : tpos e ) ~ tag " : error " end ; end_message ( ) ; if ! nowarnings || Text . index ew ~ index : tend = ` Linechar ( 2 , 0 ) then destroy tl else begin error_messages := tl :: ! error_messages ; Text . configure ew ~ state ` : Disabled ; bind ew ~ events [ ` : Modified ( [ ` Double ] , ` ButtonReleaseDetail 1 ) ] ~ action ( : fun _ -> try let start , ende = Text . tag_nextrange ew ~ tag " : sel " ~ start ( : tpos 0 ) in let s = Text . get ew ~ start ( : start , [ ] ) ~ stop ( : ende , [ ] ) in let n = int_of_string s in Text . mark_set txt . tw ~ index ( : tpos n ) ~ mark " : insert " ; Text . see txt . tw ~ index ( ` : Mark " insert " , [ ] ) with _ -> ( ) ) end ; ! error_messages
type error = [ ` TypeMismatchError of string | ` UnboundRegularVarInsideBoxError of Location . t * string | Env . error ]
type ' e lerror = ( [ > error ] as ' e ) Location . located
let check_equal ty1 ty2 msg = Result . ok_if_true ( [ % equal : Type . t ] ty1 ty2 ) ~ error ( ` : TypeMismatchError msg )
let with_error_location loc r = Result . map_error r ~ f ( : fun e -> Location . locate ~ loc e )
let fail_in loc err = Result . fail @@ Location . locate ~ loc @@ err
let mk_unbound_regular_var_inside_box_error box_expr_loc var_loc var = let var_name = Id . R . to_string var in let msg = [ % string " regular variable " ( \$ var_name ) " \ is accessed in box expression \ ( ( $ Location . pp_column_range box_expr_loc ) ) at \ ( $ Location . pp_column_range var_loc ) " ] in fail_in var_loc @@ ` UnboundRegularVarInsideBoxError ( var_loc , msg )
let rec check_open delta gamma Location . { data = expr ; loc } typ = match expr with | Unit -> let exp_ty = PrettyPrinter . Str . of_type typ in with_error_location loc @@ check_equal typ Type . Unit [ % string " Expected $ exp_ty , but found Unit type " ] | Pair { e1 ; e2 } -> ( match typ with | Type . Prod { ty1 ; ty2 } -> let % map ( ) = check_open delta gamma e1 ty1 and ( ) = check_open delta gamma e2 ty2 in ( ) | _ -> let exp_ty = PrettyPrinter . Str . of_type typ in fail_in loc @@ ` TypeMismatchError [ % string " Expected $ exp_ty , but found product type " ] ) | Fst { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 ; ty2 = _ } -> with_error_location loc @@ check_equal typ ty1 " fst error : inferred type is different from the input one " | _ -> fail_in loc @@ ` TypeMismatchError " fst is applied to a non - product type " ) | Snd { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 = _ ; ty2 } -> with_error_location loc @@ check_equal typ ty2 " snd error : inferred type is different from the input one " | _ -> fail_in loc @@ ` TypeMismatchError " snd is applied to a non - product type " ) | Nat _ -> let exp_ty = PrettyPrinter . Str . of_type typ in with_error_location loc @@ check_equal typ Type . Nat [ % string " Expected $ exp_ty , but found Nat type " ] | BinOp { op = _ ; e1 ; e2 } -> let % map ( ) = check_open delta gamma e1 Type . Nat and ( ) = check_open delta gamma e2 Type . Nat in ( ) | VarR { idr } -> let % bind ty = with_error_location loc @@ Env . R . lookup gamma idr in with_error_location loc @@ check_equal typ ty " Unexpected regular variable type " | VarM { idm } -> let % bind ty = with_error_location loc @@ Env . M . lookup delta idm in with_error_location loc @@ check_equal typ ty " Unexpected modal variable type " | Fun { idr ; ty_id ; body } -> ( match typ with | Type . Arr { dom ; cod } -> let % bind ( ) = with_error_location loc @@ check_equal dom ty_id " Domain of arrow type is not the same as type of function \ parameter " in check_open delta ( Env . R . extend gamma idr dom ) body cod | _ -> fail_in loc @@ ` TypeMismatchError " Arrow type expected " ) | App { fe ; arge } -> ( let % bind ty = infer_open delta gamma fe in match ty with | Type . Arr { dom ; cod } -> let % bind ( ) = check_open delta gamma arge dom in with_error_location loc @@ check_equal typ cod " Unexpected function codomain " | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not an arrow type " ) | Box { e } -> ( match typ with | Type . Box { ty } -> ( match check_open delta Env . R . emp e ty with | Error { data = ` EnvUnboundRegularVarError ( var , _ ) ; loc = var_loc } when Result . is_ok ( Env . R . lookup gamma var ) -> mk_unbound_regular_var_inside_box_error loc var_loc var | x -> x ) | _ -> fail_in loc @@ ` TypeMismatchError " Error : unboxed type " ) | Let { idr ; bound ; body } -> let % bind ty = infer_open delta gamma bound in check_open delta ( Env . R . extend gamma idr ty ) body typ | Letbox { idm ; boxed ; body } -> ( let % bind ty = infer_open delta gamma boxed in match ty with | Type . Box { ty } -> check_open ( Env . M . extend delta idm ty ) gamma body typ | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not a box " ) | Match { matched ; zbranch ; pred ; sbranch } -> let % bind _ = check_open delta gamma matched Type . Nat in let % bind ty_empty = infer_open delta gamma zbranch in check_open delta ( Env . R . extend gamma pred Type . Nat ) sbranch ty_empty match expr with | Unit -> return Type . Unit | Pair { e1 ; e2 } -> let % map ty1 = infer_open delta gamma e1 and ty2 = infer_open delta gamma e2 in Type . Prod { ty1 ; ty2 } | Fst { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 ; ty2 = _ } -> return ty1 | _ -> fail_in loc @@ ` TypeMismatchError " fst is applied to a non - product type " ) | Snd { e } -> ( let % bind ty = infer_open delta gamma e in match ty with | Type . Prod { ty1 = _ ; ty2 } -> return ty2 | _ -> fail_in loc @@ ` TypeMismatchError " snd is applied to a non - product type " ) | Nat _ -> return Type . Nat | BinOp { op = _ ; e1 ; e2 } -> let % map ( ) = check_open delta gamma e1 Type . Nat and ( ) = check_open delta gamma e2 Type . Nat in Type . Nat | VarR { idr } -> with_error_location loc @@ Env . R . lookup gamma idr | VarM { idm } -> with_error_location loc @@ Env . M . lookup delta idm | Fun { idr ; ty_id ; body } -> let % map ty_body = infer_open delta ( Env . R . extend gamma idr ty_id ) body in Type . Arr { dom = ty_id ; cod = ty_body } | App { fe ; arge } -> ( let % bind ty = infer_open delta gamma fe in match ty with | Type . Arr { dom ; cod } -> let % bind ( ) = check_open delta gamma arge dom in return cod | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not an arrow type " ) | Box { e } -> let % map ty = match infer_open delta Env . R . emp e with | Error { data = ` EnvUnboundRegularVarError ( var , _ ) ; loc = var_loc } when Result . is_ok @@ Env . R . lookup gamma var -> mk_unbound_regular_var_inside_box_error loc var_loc var | x -> x in Type . Box { ty } | Let { idr ; bound ; body } -> let % bind ty = infer_open delta gamma bound in infer_open delta ( Env . R . extend gamma idr ty ) body | Letbox { idm ; boxed ; body } -> ( let % bind tyb = infer_open delta gamma boxed in match tyb with | Type . Box { ty } -> infer_open ( Env . M . extend delta idm ty ) gamma body | _ -> fail_in loc @@ ` TypeMismatchError " Inferred type is not a box " ) | Match { matched ; zbranch ; pred ; sbranch } -> let % bind _ = check_open delta gamma matched Type . Nat in let % bind ty_zero = infer_open delta gamma zbranch in let % bind ty_succ = infer_open delta ( Env . R . extend gamma pred Type . Nat ) sbranch in let % bind ( ) = with_error_location loc @@ check_equal ty_zero ty_succ " All branches of pattern matching must have the same type " in return ty_zero
let check expr typ = check_open Env . M . emp Env . R . emp expr typ
let infer expr = infer_open Env . M . emp Env . R . emp expr
type method_type = typ list * typ
type method_env = method_type SM . t
type attribute_env = typ SM . t
type class_type = attribute_env * method_env
type class_env = class_type SM . t
type variable_env = typ SM . t
let error ( location : ' a Location . t ) ( msg : string ) = raise ( Error ( sprintf " % s :\ n % s " ( Error . positions ( Location . startpos location ) ( Location . endpos location ) ) msg ) )
let errors ( locations : ' a Location . t list ) ( msg : string ) = raise ( Error ( sprintf " % s % s " ( List . fold_right ( fun location acc -> sprintf " % s :\ n % s " ( Error . positions ( Location . startpos location ) ( Location . endpos location ) ) acc ) locations " " ) msg ) )
let lookup ( msg : string ) ( id : identifier ) ( env : ' a SM . t ) = try SM . find ( Location . content id ) env with Not_found -> error id ( sprintf " % s % s is undefined " msg ( Location . content id ) )
let vlookup : identifier -> variable_env -> typ = lookup " variable "
let mlookup : identifier -> method_env -> method_type = lookup " method "
let alookup : identifier -> attribute_env -> typ = lookup " attribute "
let clookup : identifier -> class_env -> class_type = lookup " class "
let rec compatible ( typ1 : typ ) ( typ2 : typ ) ( instanceof : identifier -> identifier -> bool ) : bool = match typ1 , typ2 with | TypInt , TypInt | TypBool , TypBool | TypIntArray , TypIntArray -> true | Typ t1 , Typ t2 -> instanceof t1 t2 | _ , _ -> false
let rec type_to_string : typ -> string = function | TypInt -> " integer " | TypBool -> " boolean " | TypIntArray -> " int [ ] " | Typ t -> Location . content t
let rec typecheck_call ( cenv : class_env ) ( venv : variable_env ) ( vinit : S . t ) ( instanceof : identifier -> identifier -> bool ) ( o : expression ) ( callee : identifier ) ( expressions : expression list ) : typ = let o_type = typecheck_expression cenv venv vinit instanceof o in match o_type with | Typ t -> begin let _ , method_env = clookup t cenv in let ( formals : typ list ) , ( result : typ ) = mlookup callee method_env in try List . iter2 ( typecheck_expression_expecting cenv venv vinit instanceof ) formals expressions ; result with Invalid_argument _ -> error callee ( sprintf " Invalid function call , expected % d arguments , got % d " ( List . length formals ) ( List . length expressions ) ) end | _ -> error o ( sprintf " A class is expected , got % s " ( type_to_string o_type ) ) ( instanceof : identifier -> identifier -> bool ) ( typ1 : typ ) ( e : expression ) : unit = let typ2 = typecheck_expression cenv venv vinit instanceof e in if not ( compatible typ2 typ1 instanceof ) then error e ( sprintf " Type mismatch , expected % s , got % s " ( type_to_string typ1 ) ( type_to_string typ2 ) ) ( instanceof : identifier -> identifier -> bool ) ( e : expression ) : typ = match Location . content e with | EConst ( ConstBool _ ) -> TypBool | EConst ( ConstInt _ ) -> TypInt | EGetVar v -> let typ = vlookup v venv in let v ' = Location . content v in if not ( S . mem v ' vinit ) then error v ( sprintf " Variable % s has not been initialized " v ' ) ; typ | EUnOp ( op , e ) -> let expected , returned = match op with | UOpNot -> TypBool , TypBool in typecheck_expression_expecting cenv venv vinit instanceof expected e ; returned | EBinOp ( op , e1 , e2 ) -> let expected , returned = match op with | OpAdd | OpSub | OpMul -> TypInt , TypInt | OpLt -> TypInt , TypBool | OpAnd -> TypBool , TypBool in typecheck_expression_expecting cenv venv vinit instanceof expected e1 ; typecheck_expression_expecting cenv venv vinit instanceof expected e2 ; returned | EMethodCall ( o , callee , expressions ) -> typecheck_call cenv venv vinit instanceof o callee expressions | EArrayGet ( earray , eindex ) -> typecheck_expression_expecting cenv venv vinit instanceof TypInt eindex ; typecheck_expression_expecting cenv venv vinit instanceof TypIntArray earray ; TypInt | EArrayAlloc elength -> typecheck_expression_expecting cenv venv vinit instanceof TypInt elength ; TypIntArray | EArrayLength earray -> typecheck_expression_expecting cenv venv vinit instanceof TypIntArray earray ; TypInt | EThis -> vlookup ( Location . make ( Location . startpos e ) ( Location . endpos e ) " this " ) venv | EObjectAlloc id -> clookup id cenv |> ignore ; Typ id
let rec typecheck_instruction ( cenv : class_env ) ( venv : variable_env ) ( vinit : S . t ) ( instanceof : identifier -> identifier -> bool ) ( inst : instruction ) : S . t = match inst with | ISetVar ( v , e ) -> let vinit = S . add ( Location . content v ) vinit in typecheck_expression_expecting cenv venv vinit instanceof ( vlookup v venv ) e ; vinit | IArraySet ( earray , eindex , evalue ) -> typecheck_expression_expecting cenv venv vinit instanceof TypIntArray ( Location . make ( Location . startpos earray ) ( Location . endpos earray ) ( EGetVar earray ) ) ; typecheck_expression_expecting cenv venv vinit instanceof TypInt eindex ; typecheck_expression_expecting cenv venv vinit instanceof TypInt evalue ; vinit | IBlock instructions -> List . fold_left ( fun vinit inst -> typecheck_instruction cenv venv vinit instanceof inst ) vinit instructions | IIf ( cond , ithen , ielse ) -> typecheck_expression_expecting cenv venv vinit instanceof TypBool cond ; let vinit1 = typecheck_instruction cenv venv vinit instanceof ithen in let vinit2 = typecheck_instruction cenv venv vinit instanceof ielse in S . inter vinit1 vinit2 | IWhile ( cond , ibody ) -> typecheck_expression_expecting cenv venv vinit instanceof TypBool cond ; typecheck_instruction cenv venv vinit instanceof ibody | ISyso e -> typecheck_expression_expecting cenv venv vinit instanceof TypInt e ; vinit
let occurrences ( x : string ) ( bindings : ( identifier * ' a ) list ) : identifier list = List . map fst ( List . filter ( fun ( id , _ ) -> x = Location . content id ) bindings )
let map_of_association_list ( entity : string ) ( bindings : ( identifier * ' a ) list ) : ' a SM . t = try SM . of_association_list ( List . map ( fun ( id , data ) -> ( Location . content id , data ) ) bindings ) with SM . Duplicate x -> errors ( occurrences x bindings ) ( sprintf " % s % s is declared more than once " entity x )
let variable_map ( decls : ( identifier * typ ) list ) : variable_env = map_of_association_list " Variable " decls
let method_map ( decls : ( identifier * method_type ) list ) : method_env = map_of_association_list " Method " decls
let typecheck_method ( cenv : class_env ) ( venv : variable_env ) ( instanceof : identifier -> identifier -> bool ) ( m : metho ) : unit = let formals = m . formals and locals = m . locals in let mformals = variable_map formals and mlocals = variable_map locals in begin try let x = StringSet . choose ( StringSet . inter ( SM . domain mformals ) ( SM . domain mlocals ) ) in errors ( occurrences x formals @ occurrences x locals ) " A formal parameter and a local variable cannot carry the same name " with Not_found -> ( ) end ; let venv = SM . addm mformals venv |> SM . addm mlocals in let vinit = S . diff ( SM . domain venv ) ( SM . domain mlocals ) in let vinit = typecheck_instruction cenv venv vinit instanceof ( IBlock m . body ) in typecheck_expression_expecting cenv venv vinit instanceof m . result m . return
let typecheck_class ( cenv : class_env ) ( instanceof : identifier -> identifier -> bool ) ( ( name , c ) : identifier * clas ) : unit = let attribute_env , _ = clookup name cenv in let venv = SM . add " this " ( Typ name ) attribute_env in List . iter ( typecheck_method cenv venv instanceof ) ( List . map snd c . methods )
let extract_method_type ( m : metho ) : method_type = ( List . map snd m . formals , m . result )
let extract_class_type ( c : clas ) : class_type = ( variable_map c . attributes , method_map ( List . map ( fun ( id , m ) -> ( id , extract_method_type m ) ) c . methods ) )
let class_map ( decls : ( identifier * clas ) list ) : clas SM . t = map_of_association_list " Class " decls
let create_instanceof ( cmap : clas SM . t ) : identifier -> identifier -> bool = let rec instanceof id1 id2 = if id1 = id2 then true else try match ( SM . find id1 cmap ) . extends with | None -> false | Some id3 -> instanceof ( Location . content id3 ) id2 with Not_found -> false in fun id1 id2 -> instanceof ( Location . content id1 ) ( Location . content id2 )
let add_method ( cmap : clas SM . t ) ( instanceof : identifier -> identifier -> bool ) : clas SM . t = let test_compatible_signature ( ( name , m ) : identifier * metho ) ( ( name ' , m ' ) : identifier * metho ) : unit = let typecheck_params ( typ : typ ) ( typ ' : typ ) : unit = if not ( compatible typ typ ' ( fun t1 t2 -> Location . content t1 = Location . content t2 ) ) then errors [ name ; name ' ] ( sprintf " Type mismatch in params of overriden method , expected % s , got % s " ( type_to_string typ ) ( type_to_string typ ' ) ) in let typecheck_result ( typ : typ ) ( typ ' : typ ) : unit = if not ( compatible typ ' typ instanceof ) then errors [ name ; name ' ] ( sprintf " Type mismatch in result of overriden method , expected % s , got % s " ( type_to_string typ ) ( type_to_string typ ' ) ) in let formals , result = extract_method_type m and formals ' , result ' = extract_method_type m ' in try List . iter2 typecheck_params formals formals ' ; typecheck_result result result ' with Invalid_argument _ -> errors [ name ; name ' ] ( sprintf " A function that overrides another one must have the same number of parameters " ) in let rec complete ( parent : identifier option ) ( c : clas ) : clas = match parent with | None -> c | Some id -> let c ' = SM . find ( Location . content id ) cmap in complete c ' . extends { c with attributes = ( List . filter ( fun ( name , _ ) -> not ( List . exists ( fun ( name ' , _ ) -> Location . content name = Location . content name ' ) c . attributes ) ) c ' . attributes ) @ c . attributes ; methods = ( List . filter ( fun ( name , m ) -> try List . find ( fun ( name ' , _ ) -> Location . content name = Location . content name ' ) c . methods |> test_compatible_signature ( name , m ) ; false with Not_found -> true ) c ' . methods ) @ c . methods } in SM . map ( fun c -> complete c . extends c ) cmap
let typecheck_program ( p : program ) : unit = let cmap = class_map p . defs in let instanceof = create_instanceof cmap in let cenv = add_method cmap instanceof |> SM . map extract_class_type in List . iter ( typecheck_class cenv instanceof ) p . defs ; let venv = SM . singleton " this " ( Typ p . name ) in typecheck_instruction cenv venv S . empty instanceof p . main |> ignore
module DefaultContext = struct let qualifier = Reference . empty let constraint_solving_style = Configuration . Analysis . default_constraint_solving_style let debug = false let define = + Test . mock_define let resolution_fixpoint = None let error_map = None module Builder = Callgraph . NullBuilder end
let create_annotation_store ( ? immutables = [ ] ) annotations = let immutables = String . Map . of_alist_exn immutables in let annotify ( name , annotation ) = let annotation = let create annotation = match Map . find immutables name with | Some original -> Refinement . Unit . create ( Annotation . create_immutable ~ original ( : Some original ) annotation ) | _ -> Refinement . Unit . create ( Annotation . create_mutable annotation ) in create annotation in !& name , annotation in { Refinement . Store . annotations = List . map annotations ~ f : annotify |> Reference . Map . of_alist_exn ; temporary_annotations = Reference . Map . empty ; }
let assert_annotation_store ~ expected actual = let actual = Resolution . annotation_store actual in let compare_annotation_store { Refinement . Store . annotations = left_annotations ; temporary_annotations = left_temporary_annotations ; } { Refinement . Store . annotations = right_annotations ; temporary_annotations = right_temporary_annotations ; } = let equal_map = Reference . Map . equal [ % equal : Refinement . Unit . t ] in equal_map left_annotations right_annotations && equal_map left_temporary_annotations right_temporary_annotations in let pp_annotation_store formatter { Refinement . Store . annotations ; temporary_annotations } = let annotation_to_string ( name , refinement_unit ) = Format . asprintf " % a -> % a " Reference . pp name Refinement . Unit . pp refinement_unit in let printed_annotations = Map . to_alist annotations |> List . map ~ f : annotation_to_string |> String . concat ~ sep " :\ n " in let printed_temporary_annotations = Map . to_alist temporary_annotations |> List . map ~ f : annotation_to_string |> String . concat ~ sep " :\ n " in Format . fprintf formatter " Annotations : % s \ nTemporaryAnnotations : % s " printed_annotations printed_temporary_annotations in assert_equal ~ cmp : compare_annotation_store ~ printer ( : Format . asprintf " % a " pp_annotation_store ) ~ pp_diff ( : diff ~ print : pp_annotation_store ) expected actual
module Create ( Context : TypeCheck . Context ) = struct let create ( ? bottom = false ) ( ? immutables = [ ] ) ~ resolution annotations = let module State = State ( Context ) in if bottom then State . unreachable else let resolution = let annotation_store = create_annotation_store ~ immutables annotations in Resolution . with_annotation_store resolution ~ annotation_store in State . create ~ resolution end
let description ~ resolution error = let ast_environment = Resolution . global_resolution resolution |> GlobalResolution . ast_environment in Error . instantiate ~ show_error_traces : false ~ lookup ( : AstEnvironment . ReadOnly . get_relative ast_environment ) error |> Error . Instantiated . description
let test_initial context = let assert_initial ? parent ( ? environment = " " ) ( ? immutables = [ ] ) ~ annotations define = let define = match parse_single_statement define with | { Node . value = Define ( { signature ; _ } as define ) ; _ } -> let signature = { signature with parent = parent >>| Reference . create } in { define with signature } | _ -> failwith " Unable to parse define . " in let module Context = struct let debug = false let constraint_solving_style = Configuration . Analysis . default_constraint_solving_style let qualifier = Reference . empty let define = + define let resolution_fixpoint = Some ( LocalAnnotationMap . empty ( ) ) let error_map = Some ( LocalErrorMap . empty ( ) ) module Builder = Callgraph . NullBuilder end in let resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_resolution in let module Create = Create ( Context ) in let state = Create . create ~ immutables ~ resolution annotations in let module State = State ( Context ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let initial = let variables = let extract_variables { Node . value = { Expression . Parameter . annotation ; _ } ; _ } = match annotation with | None -> [ ] | Some annotation -> let annotation = GlobalResolution . parse_annotation ( Resolution . global_resolution resolution ) annotation in Type . Variable . all_free_variables annotation in List . concat_map define . signature . parameters ~ f : extract_variables |> List . dedup_and_sort ~ compare : Type . Variable . compare in let add_variable resolution variable = Resolution . add_type_variable resolution ~ variable in let resolution = List . fold variables ~ init : resolution ~ f : add_variable in State . initial ~ resolution in assert_state_equal state initial in assert_initial " def foo ( x : int ) -> None : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial " def foo ( x : int = 1 . 0 ) -> None : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial ~ annotations [ " : x " , Type . Any ] " def foo ( x = 1 . 0 ) -> None : . . . " ; assert_initial " def foo ( x : int ) -> int : . . . " ~ immutables [ " : x " , Type . integer ] ~ annotations [ " : x " , Type . integer ] ; assert_initial " def foo ( x : float , y : str ) -> None : . . . " ~ immutables [ " : x " , Type . float ; " y " , Type . string ] ~ annotations [ " : x " , Type . float ; " y " , Type . string ] ; assert_initial " def foo ( x ) -> None : . . . " ~ annotations [ " : x " , Type . Any ] ; assert_initial " def foo ( x : typing . Any ) -> None : . . . " ~ immutables [ " : x " , Type . Any ] ~ annotations [ " : x " , Type . Any ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " def __eq__ ( self , other : object ) -> None : . . . " ~ immutables [ " : other " , Type . object_primitive ] ~ annotations [ " : self " , Type . Primitive " Foo " ; " other " , Type . object_primitive ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " def foo ( self ) -> None : . . . " ~ annotations [ " : self " , Type . Primitive " Foo " ] ; assert_initial ~ parent " : Foo " ~ environment " : class Foo : . . . " " @ staticmethod \ ndef foo ( a ) -> None : . . . " ~ annotations [ " : a " , Type . Any ] ; assert_initial ~ environment " : T = typing . TypeVar ( ' T ' ) " " def foo ( x : test . T ) -> None : . . . " ~ immutables [ " : x " , Type . Variable . mark_all_variables_as_bound ( Type . variable " test . T " ) ] ~ annotations [ " : x " , Type . Variable . mark_all_variables_as_bound ( Type . variable " test . T " ) ]
let test_less_or_equal context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in assert_true ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . Top ] ) ~ right ( : create [ ] ) ) ; assert_true ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ; " y " , Type . integer ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ " x " , Type . integer ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ ] ) ~ right ( : create [ " x " , Type . Top ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " x " , Type . string ] ) ) ; assert_false ( State . less_or_equal ~ left ( : create [ " x " , Type . integer ] ) ~ right ( : create [ " y " , Type . integer ] ) )
let test_widen context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let widening_threshold = 3 in assert_state_equal ( State . widen ~ previous ( : create [ " x " , Type . string ] ) ~ next ( : create [ " x " , Type . integer ] ) ~ iteration : 0 ) ( create [ " x " , Type . union [ Type . integer ; Type . string ] ] ) ; assert_state_equal ( State . widen ~ previous ( : create [ " x " , Type . string ] ) ~ next ( : create [ " x " , Type . integer ] ) ~ iteration ( : widening_threshold + 1 ) ) ( create [ " x " , Type . Top ] )
let test_check_annotation context = let assert_check_annotation source variable_name descriptions = let resolution = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_resolution in let module State = State ( DefaultContext ) in let errors = let expression = let location = { Location . start = { line = 1 ; column = 1 } ; stop = { line = 1 ; column = 1 + String . length variable_name } ; } in let value = Expression . Expression . Name ( Expression . create_name ~ location variable_name ) in Node . create ~ location value in State . parse_and_check_annotation ~ resolution expression |> fst |> AnalysisError . deduplicate in let errors = List . map ~ f ( : description ~ resolution ) errors in assert_equal ~ cmp ( : List . equal String . equal ) ~ printer ( : String . concat ~ sep " :\ n " ) descriptions errors in assert_check_annotation " " " x " [ " Undefined or invalid type [ 11 ] : Annotation ` x ` is not defined as a type . " ] ; assert_check_annotation " x : int = 1 " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x : typing . Type [ int ] = int " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x = int " " test . x " [ ] ; assert_check_annotation " x : typing . Any " " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation " x = typing . Any " " test . x " [ ] ; assert_check_annotation " x : typing_extensions . TypeAlias = typing . Any " " test . x " [ ] ; assert_check_annotation { | class Foo : . . . x = Foo } | " test . x " [ ] ; assert_check_annotation { | class Foo : . . . x = Foo ( ) } | " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ] ; assert_check_annotation { | class Foo : def __getitem__ ( self , other ) -> typing . Any : . . . x = Foo [ Undefined ] } | " test . x " [ " Undefined or invalid type [ 11 ] : Annotation ` test . x ` is not defined as a type . " ]
let assert_resolved ~ context sources expression expected = let resolution = ScratchProject . setup ~ context sources |> ScratchProject . build_resolution in let resolved = Resolution . resolve_expression_to_type resolution ( parse_single_expression expression ) in assert_equal ~ printer : Type . show ~ cmp : Type . equal expected resolved
let test_module_exports context = let assert_exports_resolved expression expected = let sources = [ " implementing . py " , { | def function ( ) -> int : . . . constant : int = 1 } ; | ( " exporting . py " , { | from implementing import function , constant from implementing import function as aliased from indirect import cyclic } | ) ; " indirect . py " , { | from exporting import constant , cyclic } ; | " wildcard . py " , { | from exporting import * } ; | ( " exporting_wildcard_default . py " , { | from implementing import function , constant from implementing import function as aliased __all__ = [ " constant " ] } | ) ; " wildcard_default . py " , { | from exporting_wildcard_default import * } ; | ] in assert_resolved ~ context sources expression expected in assert_exports_resolved " implementing . constant " Type . integer ; assert_exports_resolved " implementing . function ( ) " Type . integer ; assert_exports_resolved " implementing . undefined " Type . Top ; assert_exports_resolved " exporting . constant " Type . integer ; assert_exports_resolved " exporting . function ( ) " Type . integer ; assert_exports_resolved " exporting . aliased ( ) " Type . integer ; assert_exports_resolved " exporting . undefined " Type . Top ; assert_exports_resolved " indirect . constant " Type . integer ; assert_exports_resolved " indirect . cyclic " Type . Top ; assert_exports_resolved " wildcard . constant " Type . integer ; assert_exports_resolved " wildcard . cyclic " Type . Top ; assert_exports_resolved " wildcard . aliased ( ) " Type . integer ; assert_exports_resolved " wildcard_default . constant " Type . integer ; assert_exports_resolved " wildcard_default . aliased ( ) " Type . Any ; let assert_fixpoint_stop = assert_resolved ~ context [ " loop / b . py " , { | b : int = 1 } ; | " loop / a . py " , { | from loop . b import b } ; | " loop / a . py " , { | from loop . a import b } ; | " no_loop / b . py " , { | b : int = 1 } ; | " no_loop / a . py " , { | from no_loop . b import b as c } ; | " no_loop / __init__ . py " , { | from no_loop . a import c } ; | ] in assert_fixpoint_stop " loop . b " Type . Top ; assert_fixpoint_stop " no_loop . c " Type . integer
let test_object_callables context = let assert_resolved expression annotation = assert_resolved ~ context [ ( " module . py " , { | _K = typing . TypeVar ( ' _K ' ) _V = typing . TypeVar ( ' _V ' ) _T = typing . TypeVar ( ' _T ' ) class object : def __init__ ( self ) -> None : pass class Call ( object , typing . Generic [ _K , _V ] ) : attribute : _K generic_callable : typing . Callable [ [ _K ] , _V ] def __call__ ( self ) -> _V : . . . class Submodule ( Call [ _T , _T ] , typing . Generic [ _T ] ) : pass call : Call [ int , str ] = . . . meta : typing . Type [ Call [ int , str ] ] = . . . submodule : Submodule [ int ] = . . . } | ) ; ] expression ( Type . create ~ aliases : Type . empty_aliases ( parse_single_expression annotation ) ) in assert_resolved " module . call " " module . Call [ int , str ] " ; assert_resolved " module . call . attribute " " int " ; assert_resolved " module . call . generic_callable " " typing . Callable [ [ int ] , str ] " ; assert_resolved " module . call ( ) " " str " ; assert_resolved " module . meta " " typing . Type [ module . Call [ int , str ] ] " ; assert_resolved " module . meta ( ) " " module . Call [ int , str ] " ; assert_resolved " module . submodule . generic_callable " " typing . Callable [ [ int ] , int ] "
let test_callable_selection context = let assert_resolved source expression annotation = assert_resolved ~ context [ " test . py " , source ] expression ( Type . create ~ aliases : Type . empty_aliases ( parse_single_expression annotation ) ) in assert_resolved " call : typing . Callable [ [ ] , int ] " " test . call ( ) " " int " ; assert_resolved " call : typing . Callable [ [ int ] , int ] " " test . call ( ) " " int "
type parameter_kind = | NamedParameter | VariableParameter | KeywordParameter
let test_forward_expression context = let assert_forward ( ? precondition = [ ] ) ( ? postcondition = [ ] ) ( ? environment = " " ) expression annotation = let expression = let expression = parse expression |> Preprocessing . preprocess in expression |> function | { Source . statements = [ { Node . value = Expression expression ; _ } ] ; _ } -> expression | _ -> failwith " Unable to extract expression " in let global_resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_global_resolution in let new_resolution , resolved = let resolution = let annotation_store = create_annotation_store precondition in TypeCheck . resolution ~ annotation_store global_resolution ( module TypeCheck . DummyContext ) in Resolution . resolve_expression resolution expression in assert_annotation_store ~ expected ( : create_annotation_store postcondition ) new_resolution ; assert_equal ~ cmp : Type . equal ~ printer : Type . show annotation resolved in assert_forward " await awaitable_int ( ) " Type . integer ; assert_forward " await undefined " Type . Any ; assert_forward " 1 or ' string ' " ( Type . literal_integer 1 ) ; assert_forward " 1 and ' string ' " ( Type . literal_string " string " ) ; assert_forward " undefined or 1 " Type . Top ; assert_forward " 1 or undefined " ( Type . literal_integer 1 ) ; assert_forward " undefined and undefined " Type . Top ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 0 or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " False or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " None or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " ' ' or y " Type . integer ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " b ' ' or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . NoneType ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . NoneType ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . literal_integer 0 ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . literal_integer 0 ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . Literal ( Type . Boolean false ) ; " y " , Type . integer ] ~ postcondition [ " : x " , Type . Literal ( Type . Boolean false ) ; " y " , Type . integer ] " x or y " Type . integer ; assert_forward ~ precondition [ " : x " , Type . union [ Type . NoneType ; Type . integer ; Type . string ] ] ~ postcondition [ " : x " , Type . union [ Type . NoneType ; Type . integer ; Type . string ] ] " x or 1 " ( Type . Union [ Type . integer ; Type . string ] ) ; assert_forward ~ precondition [ " : x " , Type . union [ Type . NoneType ; Type . literal_integer 0 ] ; " y " , Type . string ] ~ postcondition [ " : x " , Type . union [ Type . NoneType ; Type . literal_integer 0 ] ; " y " , Type . string ] " x or y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 1 and y " Type . string ; assert_forward ~ precondition [ " : y " , Type . string ] ~ postcondition [ " : y " , Type . string ] " 1 and y " Type . string ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " ' foo ' and y " Type . integer ; assert_forward ~ precondition [ " : y " , Type . integer ] ~ postcondition [ " : y " , Type . integer ] " b ' foo ' and y " Type . integer ; assert_forward ~ precondition : [ " x " , Type . union [ Type . literal_integer 1 ; Type . literal_integer 2 ] ; " y " , Type . string ] ~ postcondition : [ " x " , Type . union [ Type . literal_integer 1 ; Type . literal_integer 2 ] ; " y " , Type . string ] " x and y " Type . string ; let assert_optional_forward ( ? postcondition = [ " x " , Type . optional Type . integer ] ) = assert_forward ~ precondition [ " : x " , Type . optional Type . integer ] ~ postcondition in assert_optional_forward " x or 1 " Type . integer ; assert_optional_forward " x or x " ( Type . optional Type . integer ) ; assert_optional_forward " x and 1 " ( Type . optional Type . integer ) ; assert_optional_forward " 1 and x " ( Type . optional Type . integer ) ; assert_optional_forward " x and x " ( Type . optional Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . dictionary ~ key : Type . integer ~ value : Type . Bottom ] ~ postcondition [ " : x " , Type . dictionary ~ key : Type . integer ~ value : Type . Bottom ] " x . add_key ( ' string ' ) " Type . none ; assert_forward ~ precondition [ " : unknown " , Type . Top ] ~ postcondition [ " : unknown " , Type . Top ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : int ) -> typing . Optional [ Foo ] : . . . } | " test . foo ( unknown ) . attribute " Type . Top ; assert_forward ~ precondition [ " : foo_instance " , Type . Primitive " Foo " ] ~ postcondition [ " : foo_instance " , Type . Primitive " Foo " ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : typing . Any ) -> Foo : . . . } | " test . foo ( foo_instance . unknown ) . attribute " Type . integer ; assert_forward ~ precondition [ " : foo_instance " , Type . Primitive " test . Foo " ] ~ postcondition [ " : foo_instance " , Type . Primitive " test . Foo " ] ~ environment : { | class Foo : def __init__ ( self ) -> None : self . attribute : int = 1 def foo ( x : typing . Any ) -> Foo : . . . } | " test . foo ( foo_instance . unknown ) . another_unknown " Type . Top ; assert_forward " 1 < 2 " Type . bool ; assert_forward " 1 < 2 < 3 " Type . bool ; assert_forward " 1 is 2 " Type . bool ; assert_forward ~ precondition [ " : container " , Type . list Type . integer ] ~ postcondition [ " : container " , Type . list Type . integer ] " 1 in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . list Type . integer ] ~ postcondition [ " : container " , Type . list Type . integer ] " 1 not in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . iterator Type . integer ] ~ postcondition [ " : container " , Type . iterator Type . integer ] " 1 in container " Type . bool ; assert_forward ~ precondition [ " : container " , Type . iterator Type . integer ] ~ postcondition [ " : container " , Type . iterator Type . integer ] " 1 not in container " Type . bool ; assert_forward ~ environment : { | class MetaFoo ( type ) : def __contains__ ( self , x : int ) -> bool : . . . class Foo ( metaclass = MetaFoo ) : def foo ( self ) -> int : return 9 } | ~ precondition [ " : Container " , Type . meta ( Type . Primitive " test . Foo " ) ] ~ postcondition [ " : Container " , Type . meta ( Type . Primitive " test . Foo " ) ] " 1 in Container " Type . bool ; let dictionary_set_union = Type . Union [ Type . dictionary ~ key : Type . integer ~ value : Type . string ; Type . set Type . integer ] in assert_forward ~ precondition [ " : Container " , dictionary_set_union ] ~ postcondition [ " : Container " , dictionary_set_union ] " 1 in Container " Type . bool ; assert_forward " undefined < 1 " Type . bool ; assert_forward " undefined == undefined " Type . Any ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] ~ postcondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] " getattr ( x , y ) " Type . integer ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition [ " : x " , Type . Primitive " test . Foo " ; " y " , Type . string ] ~ postcondition [ " : x " , Type . Primitive " test . Foo " ; " y " , Type . string ] " getattr ( x , y ) " Type . Any ; assert_forward ~ environment { :| class Foo : field : int } | ~ precondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] ~ postcondition : [ " x " , Type . Primitive " test . Foo " ; " y " , Type . Literal ( String ( LiteralValue " field " ) ) ] " getattr ( x , y , None ) " Type . integer ; assert_forward " 1j " Type . complex ; assert_forward " 1 " ( Type . literal_integer 1 ) ; assert_forward { " " } || ( Type . literal_string " " ) ; assert_forward { | b " " } | ( Type . literal_bytes " " ) ; assert_forward " { 1 : 1 } " ( Type . dictionary ~ key : Type . integer ~ value : Type . integer ) ; assert_forward " { 1 : ' string ' } " ( Type . dictionary ~ key : Type . integer ~ value : Type . string ) ; assert_forward " { b ' ' : ' ' } " ( Type . dictionary ~ key : Type . bytes ~ value : Type . string ) ; assert_forward " { 1 : 1 , ' string ' : 1 } " ( Type . dictionary ~ key ( : Type . union [ Type . integer ; Type . string ] ) ~ value : Type . integer ) ; assert_forward " { 1 : 1 , 1 : ' string ' } " ( Type . dictionary ~ key : Type . integer ~ value ( : Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { { ** 1 : 1 } } " ( Type . dictionary ~ key : Type . integer ~ value : Type . integer ) ; assert_forward " { { ** 1 : 1 } , { ' ** a ' : ' b ' } } " ( Type . dictionary ~ key ( : Type . union [ Type . integer ; Type . string ] ) ~ value ( : Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { 1 : ' string ' , { ** undefined : 1 } } " Type . Top ; assert_forward " { undefined : 1 } " ( Type . dictionary ~ key : Type . Top ~ value : Type . integer ) ; assert_forward " { 1 : undefined } " ( Type . dictionary ~ key : Type . integer ~ value : Type . Top ) ; assert_forward " { 1 : undefined , undefined : undefined } " ( Type . dictionary ~ key : Type . Top ~ value : Type . Top ) ; assert_forward " { key : value for key in [ 1 ] for value in [ ' string ' ] } " ( Type . dictionary ~ key : Type . integer ~ value : Type . string ) ; assert_forward " . . . " Type . Any ; assert_forward " False " ( Type . Literal ( Type . Boolean false ) ) ; assert_forward " 1 . 0 " Type . float ; assert_forward " ( element for element in [ 1 ] ) " ( Type . generator_expression Type . integer ) ; assert_forward " ( element for element in [ ] ) " ( Type . generator_expression Type . Any ) ; assert_forward " ( ( element , independent ) for element in [ 1 ] for independent in [ ' string ' ] ) " ( Type . generator_expression ( Type . tuple [ Type . integer ; Type . string ] ) ) ; assert_forward " ( nested for element in [ [ 1 ] ] for nested in element ) " ( Type . generator_expression Type . integer ) ; assert_forward " ( undefined for element in [ 1 ] ) " ( Type . generator_expression Type . Top ) ; assert_forward " ( element for element in undefined ) " ( Type . generator_expression Type . Any ) ; let callable ~ parameters ~ annotation = let parameters = let open Type . Callable in let to_parameter ( name , kind , default ) = match kind with | NamedParameter -> Parameter . Named { name ; annotation = Type . Any ; default } | VariableParameter -> Parameter . Variable ( Concrete Type . Any ) | KeywordParameter -> Parameter . Keywords Type . Any in Defined ( List . map parameters ~ f : to_parameter ) in Type . Callable . create ~ parameters ~ annotation ( ) in assert_forward " lambda : 1 " ( callable ~ parameters [ ] : ~ annotation : Type . integer ) ; assert_forward " lambda parameter : parameter " ( callable ~ parameters [ " : parameter " , NamedParameter , false ] ~ annotation : Type . Any ) ; assert_forward " lambda parameter = 1 : parameter " ( callable ~ parameters [ " : parameter " , NamedParameter , true ] ~ annotation : Type . Any ) ; assert_forward " lambda * parameter : 42 " ( callable ~ parameters [ " : parameter " , VariableParameter , false ] ~ annotation : Type . integer ) ; assert_forward " lambda ** parameter : 42 " ( callable ~ parameters [ " : parameter " , KeywordParameter , false ] ~ annotation : Type . integer ) ; assert_forward " lambda : undefined " ( callable ~ parameters [ ] : ~ annotation : Type . Top ) ; Type . Variable . Namespace . reset ( ) ; let empty_list = Type . list ( Type . variable " _T " |> Type . Variable . mark_all_free_variables_as_escaped ) in Type . Variable . Namespace . reset ( ) ; assert_forward " [ ] " empty_list ; assert_forward " [ 1 ] " ( Type . list Type . integer ) ; assert_forward " [ 1 , ' string ' ] " ( Type . list ( Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " [ undefined ] " ( Type . list Type . Top ) ; assert_forward " [ undefined , undefined ] " ( Type . list Type . Top ) ; assert_forward " [ element for element in [ 1 ] ] " ( Type . list Type . integer ) ; assert_forward " [ 1 for _ in [ 1 ] ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ * x ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ 1 , * x ] " ( Type . list Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " [ ' ' , * x ] " ( Type . list ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_forward ~ precondition [ " : x " , Type . integer ] ~ postcondition [ " : x " , Type . integer ] " x " Type . integer ; assert_forward " { 1 } " ( Type . set Type . integer ) ; assert_forward " { 1 , ' string ' } " ( Type . set ( Type . union [ Type . integer ; Type . string ] ) ) ; assert_forward " { undefined } " ( Type . set Type . Top ) ; assert_forward " { undefined , undefined } " ( Type . set Type . Top ) ; assert_forward " { element for element in [ 1 ] } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " { * x } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . list Type . integer ] ~ postcondition [ " : x " , Type . list Type . integer ] " { 1 , * x } " ( Type . set Type . integer ) ; assert_forward ~ precondition [ " : x " , Type . set Type . integer ] ~ postcondition [ " : x " , Type . set Type . integer ] " { ' ' , * x } " ( Type . set ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_forward " * 1 " Type . Top ; assert_forward " * undefined " Type . Top ; assert_forward " ' string ' " ( Type . literal_string " string " ) ; assert_forward " f ' string ' " Type . string ; assert_forward " f ' string { 1 } ' " Type . string ; assert_forward " f ' string { undefined } ' " Type . string ; assert_forward " 3 if True else 1 " ( Type . union [ Type . literal_integer 3 ; Type . literal_integer 1 ] ) ; assert_forward " True if True else False " ( Type . union [ Type . Literal ( Type . Boolean true ) ; Type . Literal ( Type . Boolean false ) ] ) ; assert_forward " ' foo ' if True else ' bar ' " ( Type . union [ Type . literal_string " foo " ; Type . literal_string " bar " ] ) ; assert_forward " 1 . 0 if True else 1 " Type . float ; assert_forward " 1 if True else 1 . 0 " Type . float ; assert_forward " undefined if True else 1 " Type . Top ; assert_forward " 1 if undefined else 1 " ( Type . literal_integer 1 ) ; assert_forward " 1 if True else undefined " Type . Top ; assert_forward " undefined if undefined else undefined " Type . Top ; assert_forward ~ precondition [ " : x " , Type . integer ] ~ postcondition [ " : x " , Type . integer ] " x if x is not None else 32 " Type . integer ; assert_forward " True " ( Type . Literal ( Boolean true ) ) ; assert_forward " 1 , " ( Type . tuple [ Type . literal_integer 1 ] ) ; assert_forward " 1 , ' string ' " ( Type . tuple [ Type . literal_integer 1 ; Type . literal_string " string " ] ) ; assert_forward " undefined , " ( Type . tuple [ Type . Top ] ) ; assert_forward " undefined , undefined " ( Type . tuple [ Type . Top ; Type . Top ] ) ; assert_forward " not 1 " Type . bool ; assert_forward " not undefined " Type . bool ; assert_forward " + 1 " ( Type . literal_integer 1 ) ; assert_forward " ~ 1 " Type . integer ; assert_forward " - undefined " Type . Any ; assert_forward " ( x := True ) " ( Type . Literal ( Boolean true ) ) ~ postcondition [ " : x " , Type . Literal ( Boolean true ) ] ; assert_forward ~ environment : { | Ts = pyre_extensions . TypeVarTuple ( " Ts " ) Rs = pyre_extensions . TypeVarTuple ( " Rs " ) def foo ( x : typing . Tuple [ pyre_extensions . Unpack [ Ts ] ] , y : typing . Tuple [ pyre_extensions . Unpack [ Rs ] ] ) -> pyre_extensions . Broadcast [ typing . Tuple [ pyre_extensions . Unpack [ Ts ] ] , typing . Tuple [ pyre_extensions . Unpack [ Rs ] ] , ] : . . . } | " foo ( ( 2 , 2 ) , ( 3 , 3 ) ) " Type . Any ; assert_forward " typing . Optional [ int ] " ( Type . meta ( Type . optional Type . integer ) ) ; assert_forward " typing . Callable [ [ int , str ] , int ] " ( Type . meta ( Type . Callable . create ~ annotation : Type . integer ( ) ) ) ; assert_forward " typing_extensions . Literal [ 1 , 2 , 3 ] " ( Type . meta Type . Any ) ; assert_forward " typing . ClassVar [ int ] " ( Type . meta ( Type . parametric " typing . ClassVar " [ Single Type . integer ] ) ) ; assert_forward " typing . Union [ int , str ] " ( Type . meta Type . Any ) ; let assert_annotation ( ? precondition = [ ] ) ( ? environment = " " ) expression annotation = let expression = let expression = parse expression in expression |> function | { Source . statements = [ { Node . value = Expression expression ; _ } ] ; _ } -> expression | _ -> failwith " Unable to extract expression " in let resolution = let global_resolution = ScratchProject . setup ~ context [ " test . py " , environment ] |> ScratchProject . build_global_resolution in let annotation_store = create_annotation_store precondition in TypeCheck . resolution ~ annotation_store global_resolution ( module TypeCheck . DummyContext ) in let resolved_annotation = Resolution . resolve_expression_to_annotation resolution expression in assert_equal ~ cmp : Annotation . equal ~ printer : Annotation . show annotation resolved_annotation in assert_annotation ~ environment " : x = 1 " " test . x " ( Annotation . create_immutable Type . integer ) ; assert_annotation ~ environment " : x : typing . Union [ int , str ] = 1 " " test . x " ( Annotation . create_immutable ~ original ( : Some ( Type . union [ Type . string ; Type . integer ] ) ) ( Type . union [ Type . string ; Type . integer ] ) ) ; assert_annotation ~ environment : { | class Foo : def __init__ ( self ) : self . attribute : int = 1 } | " test . Foo ( ) . attribute " ( Annotation . create_immutable Type . integer )
let test_forward_statement context = let global_resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_global_resolution in let assert_forward ( ? precondition_immutables = [ ] ) ( ? postcondition_immutables = [ ] ) ( ? bottom = false ) precondition statement postcondition = let forwarded = let parsed = parse statement |> function | { Source . statements = statement :: rest ; _ } -> statement :: rest | _ -> failwith " unable to parse test " in let resolution = let annotation_store = create_annotation_store ~ immutables : precondition_immutables precondition in TypeCheck . resolution global_resolution ~ annotation_store ( module TypeCheck . DummyContext ) in let rec process_statement resolution = function | [ ] -> Some resolution | statement :: rest -> ( match Resolution . resolve_statement resolution statement with | Resolution . Unreachable -> None | Resolution . Reachable { resolution ; _ } -> process_statement resolution rest ) in process_statement resolution parsed in match forwarded with | None -> assert_true bottom | Some actual_resolution -> assert_false bottom ; assert_annotation_store ~ expected ( : create_annotation_store ~ immutables : postcondition_immutables postcondition ) actual_resolution in assert_forward [ " y " , Type . integer ] " x = y " [ " x " , Type . integer ; " y " , Type . integer ] ; assert_forward [ " y " , Type . integer ; " z " , Type . Top ] " x = z " [ " x " , Type . Top ; " y " , Type . integer ; " z " , Type . Top ] ; assert_forward [ " x " , Type . integer ] " x += 1 " [ " x " , Type . integer ] ; assert_forward [ " z " , Type . integer ] " x = y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . integer ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . Any ] [ ] " x : Derp " [ " x " , Type . Any ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . string ] [ ] " x : str = 1 " [ " x " , Type . string ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . union [ Type . string ; Type . integer ] ] [ ] " x : typing . Union [ int , str ] = 1 " [ " x " , Type . literal_integer 1 ] ; assert_forward [ " c " , Type . integer ; " d " , Type . Top ] " a , b = c , d " [ " a " , Type . integer ; " b " , Type . Top ; " c " , Type . integer ; " d " , Type . Top ] ; assert_forward [ " z " , Type . integer ] " x , y = z " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . integer ] ; assert_forward [ " z " , Type . tuple [ Type . integer ; Type . string ; Type . string ] ] " x , y = z " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . tuple [ Type . integer ; Type . string ; Type . string ] ] ; assert_forward [ " y " , Type . integer ; " z " , Type . Top ] " x = y , z " [ " x " , Type . tuple [ Type . integer ; Type . Top ] ; " y " , Type . integer ; " z " , Type . Top ] ; assert_forward ~ postcondition_immutables [ " : x " , Type . tuple [ Type . Any ; Type . Any ] ] [ ] " x : typing . Tuple [ typing . Any , typing . Any ] = 1 , 2 " [ " x " , Type . tuple [ Type . literal_integer 1 ; Type . literal_integer 2 ] ] ; assert_forward [ " z " , Type . tuple [ Type . integer ; Type . string ] ] " x , y = z " [ " x " , Type . integer ; " y " , Type . string ; " z " , Type . tuple [ Type . integer ; Type . string ] ] ; assert_forward [ " z " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " x , y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ ] " ( x , y ) , z = 1 " [ " x " , Type . Any ; " y " , Type . Any ; " z " , Type . Any ] ; assert_forward [ " z " , Type . list Type . integer ] " x , y = z " [ " x " , Type . integer ; " y " , Type . integer ; " z " , Type . list Type . integer ] ; assert_forward [ ] " x , y = return_tuple ( ) " [ " x " , Type . integer ; " y " , Type . integer ] ; assert_forward [ ] " x = ( ) " [ " x " , Type . Tuple ( Concrete [ ] ) ] ; assert_forward [ " x " , Type . list Type . integer ] " [ a , b ] = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . integer ] ; assert_forward [ " x " , Type . list Type . integer ] " [ a , * b ] = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . list Type . integer ] ; assert_forward [ " x " , Type . list Type . integer ] " a , * b = x " [ " x " , Type . list Type . integer ; " a " , Type . integer ; " b " , Type . list Type . integer ] ; assert_forward [ " x " , Type . iterable Type . integer ] " [ a , b ] = x " [ " x " , Type . iterable Type . integer ; " a " , Type . integer ; " b " , Type . integer ] ; assert_forward [ " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " a , b = c " [ " a " , Type . integer ; " b " , Type . integer ; " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ] " * a , b = c " [ " a " , Type . list Type . integer ; " b " , Type . integer ; " c " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation Type . integer ) ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ] " * a , b = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ; " a " , Type . list ( Type . union [ Type . integer ; Type . string ] ) ; " b " , Type . float ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ] " a , * b = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . float ] ; " a " , Type . integer ; " b " , Type . list ( Type . union [ Type . string ; Type . float ] ) ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . integer ; Type . float ] ] " a , * b , c = x " [ " x " , Type . tuple [ Type . integer ; Type . string ; Type . integer ; Type . float ] ; " a " , Type . integer ; " b " , Type . list ( Type . union [ Type . string ; Type . integer ] ) ; " c " , Type . float ; ] ; assert_forward [ " x " , Type . tuple [ Type . integer ] ] " a , * b = x " [ " x " , Type . tuple [ Type . integer ] ; " a " , Type . integer ; " b " , Type . tuple [ ] ] ; assert_forward [ " x " , Type . tuple [ Type . integer ] ] " * b , c = x " [ " x " , Type . tuple [ Type . integer ] ; " b " , Type . tuple [ ] ; " c " , Type . integer ] ; assert_forward [ " x " , Type . tuple [ Type . integer ; Type . float ] ] " a , * b , c = x " [ " x " , Type . tuple [ Type . integer ; Type . float ] ; " a " , Type . integer ; " b " , Type . tuple [ ] ; " c " , Type . float ; ] ; assert_forward ~ postcondition_immutables [ " : y " , Type . integer ] [ ] " y : int " [ " y " , Type . integer ] ; assert_forward ~ postcondition_immutables [ " : y " , Type . integer ] [ ] " y : int = x " [ " y " , Type . integer ] ; assert_forward ~ precondition_immutables [ " : y " , Type . Top ] ~ postcondition_immutables [ " : y " , Type . Top ] [ " x " , Type . Top ; " y " , Type . Top ] " y = x " [ " x " , Type . Top ; " y " , Type . Top ] ; assert_forward ~ precondition_immutables [ " : y " , Type . string ] ~ postcondition_immutables [ " : y " , Type . integer ] [ " y " , Type . string ] " y : int " [ " y " , Type . integer ] ; assert_forward [ " d " , Type . dictionary ~ key : Type . string ~ value : Type . integer ] " del d [ 0 ] " [ " d " , Type . dictionary ~ key : Type . string ~ value : Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x " [ " x " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . integer ] " assert y " [ " x " , Type . optional Type . integer ; " y " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x is not None " [ " x " , Type . integer ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] " assert x and y " [ " x " , Type . integer ; " y " , Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ; " z " , Type . optional Type . float ] " assert x and ( y and z ) " [ " x " , Type . integer ; " y " , Type . float ; " z " , Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] " assert x or y " [ " x " , Type . optional Type . integer ; " y " , Type . optional Type . float ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert x is None " [ " x " , Type . none ] ; assert_forward [ " x " , Type . optional Type . integer ] " assert ( not x ) or 1 " [ " x " , Type . optional Type . integer ] ; assert_forward [ " x " , Type . list ( Type . optional Type . integer ) ] " assert all ( x ) " [ " x " , Type . list Type . integer ] ; assert_forward [ " x " , Type . iterable ( Type . optional Type . integer ) ] " assert all ( x ) " [ " x " , Type . iterable Type . integer ] ; assert_forward [ " x " , Type . list ( Type . union [ Type . none ; Type . integer ; Type . string ] ) ] " assert all ( x ) " [ " x " , Type . list ( Type . union [ Type . integer ; Type . string ] ) ] ; assert_forward [ " x " , Type . awaitable ( Type . union [ Type . none ; Type . integer ] ) ] " assert all ( x ) " [ " x " , Type . awaitable ( Type . union [ Type . none ; Type . integer ] ) ] ; assert_forward [ " x " , Type . dictionary ~ key ( : Type . optional Type . integer ) ~ value : Type . integer ] " assert all ( x ) " [ " x " , Type . dictionary ~ key ( : Type . optional Type . integer ) ~ value : Type . integer ] ; assert_forward [ " x " , Type . dictionary ~ key : Type . integer ~ value : Type . string ; " y " , Type . float ] " assert y in x " [ " x " , Type . dictionary ~ key : Type . integer ~ value : Type . string ; " y " , Type . integer ] ; assert_forward [ " x " , Type . list Type . string ; " y " , Type . union [ Type . integer ; Type . string ] ] " assert y in x " [ " x " , Type . list Type . string ; " y " , Type . string ] ; assert_forward [ " x " , Type . list Type . Top ; " y " , Type . integer ] " assert y in x " [ " x " , Type . list Type . Top ; " y " , Type . integer ] ; assert_forward [ ] " assert None in [ 1 ] " [ ] ; assert_forward [ " x " , Type . list Type . Top ] " assert None in x " [ " x " , Type . list Type . Top ] ; assert_forward ~ precondition_immutables [ " : x " , Type . float ] ~ postcondition_immutables [ " : x " , Type . float ] [ " x " , Type . float ] " assert x in [ 1 ] " [ " x " , Type . integer ] ; assert_forward ~ bottom : true [ " x " , Type . none ] " assert x " [ " x " , Type . none ] ; assert_forward ~ bottom : true [ " x " , Type . none ] " assert x is not None " [ " x " , Type . none ] ; let assert_refinement_by_type_comparison ( ? bottom = false ) ~ precondition ( ? negated = false ) ~ variable ~ type_expression ~ postcondition ( ) = let assert_forward_expression assertion_expression = assert_forward ~ bottom precondition ( Format . asprintf " assert % s " assertion_expression ) postcondition in Format . asprintf " % s isinstance ( % s , % s ) " ( if negated then " not " else " " ) variable type_expression |> assert_forward_expression ; Format . asprintf " type ( % s ) % s % s " variable ( if negated then " is not " else " is " ) type_expression |> assert_forward_expression ; Format . asprintf " type ( % s ) % s % s " variable ( if negated then " " != else " " ) == type_expression |> assert_forward_expression in assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ] ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ; " y " , Type . Top ] ~ variable " : y " ~ type_expression " : str " ~ postcondition [ " : x " , Type . Any ; " y " , Type . string ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . Any ] ~ variable " : x " ~ type_expression " ( : int , str ) " ~ postcondition [ " : x " , Type . union [ Type . integer ; Type . string ] ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " ( : int , str ) " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " : str " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . Bottom ] ~ variable " : x " ~ type_expression " : str " ~ postcondition [ " : x " , Type . string ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . float ] ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . integer ] ~ variable " : x " ~ type_expression " : 1 " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : true ~ precondition [ " : x " , Type . integer ] ~ negated : true ~ variable " : x " ~ type_expression " : float " ~ postcondition [ " : x " , Type . integer ] ( ) ; assert_refinement_by_type_comparison ~ bottom : false ~ precondition [ " : x " , Type . float ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . float ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . optional ( Type . union [ Type . integer ; Type . string ] ) ] ~ negated : true ~ variable " : x " ~ type_expression " : int " ~ postcondition [ " : x " , Type . optional Type . string ] ( ) ; assert_refinement_by_type_comparison ~ precondition [ " : x " , Type . optional ( Type . union [ Type . integer ; Type . string ] ) ] ~ negated : true ~ variable " : x " ~ type_expression " : type ( None ) " ~ postcondition [ " : x " , Type . union [ Type . integer ; Type . string ] ] ( ) ; assert_refinement_by_type_comparison ~ precondition : [ " my_type " , Type . tuple [ Type . meta Type . integer ; Type . meta Type . string ] ; " x " , Type . Top ] ~ variable " : x " ~ type_expression " : my_type " ~ postcondition : [ " my_type " , Type . tuple [ Type . meta Type . integer ; Type . meta Type . string ] ; " x " , Type . union [ Type . integer ; Type . string ] ; ] ( ) ; assert_refinement_by_type_comparison ~ precondition : [ ( " my_type " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation ( Type . meta Type . integer ) ) ) ; " x " , Type . Top ; ] ~ variable " : x " ~ type_expression " : my_type " ~ postcondition : [ ( " my_type " , Type . Tuple ( Type . OrderedTypes . create_unbounded_concatenation ( Type . meta Type . integer ) ) ) ; " x " , Type . integer ; ] ( ) ; assert_forward ~ bottom : true [ " x " , Type . integer ] " assert not isinstance ( x + 1 , int ) " [ " x " , Type . integer ] ; assert_forward ~ bottom : false [ " x " , Type . Bottom ] " assert not isinstance ( x , int ) " [ " x " , Type . Bottom ] ; assert_forward ~ bottom : true [ ] " assert False " [ ] ; assert_forward ~ bottom : true [ ] " assert None " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 . 0 " [ ] ; assert_forward ~ bottom : true [ ] " assert 0 . 0j " [ ] ; assert_forward ~ bottom : true [ ] " assert ' ' " [ ] ; assert_forward ~ bottom : true [ ] " assert b ' ' " [ ] ; assert_forward ~ bottom : true [ ] " assert [ ] " [ ] ; assert_forward ~ bottom : true [ ] " assert ( ) " [ ] ; assert_forward ~ bottom : true [ ] " assert { } " [ ] ; assert_forward ~ bottom : false [ ] " assert ( not True ) " [ ] ; assert_forward [ ] " raise 1 " [ ] ; assert_forward [ ] " raise Exception " [ ] ; assert_forward [ ] " raise Exception ( ) " [ ] ; assert_forward [ ] " raise undefined " [ ] ; assert_forward [ ] " raise " [ ] ; assert_forward [ ] " return 1 " [ ] ; assert_forward [ " y " , Type . integer ] " pass " [ " y " , Type . integer ]
let test_forward context = let resolution = ScratchProject . setup ~ context [ ] |> ScratchProject . build_resolution in let create = let module Create = Create ( DefaultContext ) in Create . create ~ resolution in let module State = State ( DefaultContext ) in let assert_state_equal = assert_equal ~ cmp : State . equal ~ printer ( : Format . asprintf " % a " State . pp ) ~ pp_diff ( : diff ~ print : State . pp ) in let assert_forward ( ? precondition_bottom = false ) ( ? postcondition_bottom = false ) precondition statement postcondition = let forwarded = let parsed = parse statement |> function | { Source . statements = statement :: rest ; _ } -> statement :: rest | _ -> failwith " unable to parse test " in List . fold ~ f ( : fun state statement -> State . forward ~ statement_key : Cfg . entry_index ~ statement state ) ~ init ( : create ~ bottom : precondition_bottom precondition ) parsed in assert_state_equal ( create ~ bottom : postcondition_bottom postcondition ) forwarded in assert_forward [ ] " x = 1 " [ " x " , Type . literal_integer 1 ] ; assert_forward ~ precondition_bottom : true ~ postcondition_bottom : true [ ] " x = 1 " [ ] ; assert_forward ~ postcondition_bottom : true [ ] " sys . exit ( 1 ) " [ ]
type method_call = { direct_target : string ; class_name : string ; dispatch : Callgraph . dispatch ; is_optional_class_attribute : bool ; }
type property_setter_call = { direct_target : string ; class_name : string ; }
let function_caller name = Callgraph . FunctionCaller !& name
let property_setter_caller name = Callgraph . PropertySetterCaller !& name
let test_calls context = let assert_calls source calls = let project = ScratchProject . setup ~ context [ " qualifier . py " , source ] in let _ = ScratchProject . build_type_environment project in let assert_calls ( caller , callees ) = let expected_callees = let callee = function | ` Method { direct_target ; class_name ; dispatch ; is_optional_class_attribute } -> Callgraph . Method { direct_target = Reference . create direct_target ; class_name = Type . Primitive class_name ; dispatch ; is_optional_class_attribute ; } | ` Function name -> Callgraph . Function ( Reference . create name ) | ` PropertySetter { direct_target ; class_name } -> Callgraph . PropertySetter { direct_target = Reference . create direct_target ; class_name = Type . Primitive class_name ; } in List . map callees ~ f : callee |> List . map ~ f : Callgraph . show_callee |> String . Set . of_list in let actual_callees = let show { Callgraph . callee ; _ } = Callgraph . show_callee callee in Callgraph . get ~ caller |> List . map ~ f : show |> String . Set . of_list in assert_equal ~ printer ( : fun set -> Set . to_list set |> String . concat ~ sep " , " ) : ~ cmp : String . Set . equal expected_callees actual_callees in List . iter calls ~ f : assert_calls ; Memory . reset_shared_memory ( ) in assert_calls { | def foo ( ) : . . . def calls_foo ( ) : foo ( ) } | [ function_caller " qualifier . foo " , [ ] ; function_caller " qualifier . calls_foo " , [ ` Function " qualifier . foo " ] ; ] ; assert_calls { | def foo ( ) : . . . def bar ( ) : . . . def calls_on_same_line ( ) : foo ( ) ; bar ( ) } | [ ( function_caller " qualifier . calls_on_same_line " , [ ` Function " qualifier . foo " ; ` Function " qualifier . bar " ] ) ; ] ; assert_calls { | class Class : def method ( ) : . . . def calls_method ( c : Class ) : c . method ( ) } | [ ( function_caller " qualifier . calls_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; dispatch = Dynamic ; is_optional_class_attribute = false ; } ; ] ) ; ] ; assert_calls { | class Class : . . . class ClassWithInit : def __init__ ( self ) : super ( ) . __init__ ( ) def calls_Class ( ) : Class ( ) def calls_ClassWithInit ( ) : ClassWithInit ( ) def calls_ClassWithInit__init__ ( object : object ) : ClassWithInit . __init__ ( object ) } | [ ( function_caller " qualifier . ClassWithInit . __init__ " , [ ` Method { direct_target = " object . __init__ " ; class_name = " object " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Class " , [ ` Method { direct_target = " object . __init__ " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_ClassWithInit " , [ ` Method { direct_target = " qualifier . ClassWithInit . __init__ " ; class_name = " qualifier . ClassWithInit " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_ClassWithInit__init__ " , [ ` Method { direct_target = " qualifier . ClassWithInit . __init__ " ; class_name = " qualifier . ClassWithInit " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ] ; assert_calls { | class Class : @ classmethod def classmethod ( cls ) : . . . def calls_class_method ( ) : Class . classmethod ( ) } | [ ( function_caller " qualifier . calls_class_method " , [ ` Method { direct_target = " qualifier . Class . classmethod " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ] ; assert_calls { | class Class : def method ( self ) : . . . class Indirect ( Class ) : . . . class Subclass ( Indirect ) : . . . class OverridingSubclass ( Subclass ) : def method ( self ) : . . . def calls_Class_method ( c : Class ) : c . method ( ) def calls_Indirect_method ( i : Indirect ) : i . method ( ) def calls_Subclass_method ( s : Subclass ) : s . method ( ) def calls_OverridingSubclass_method ( o : OverridingSubclass ) : o . method ( ) } | [ ( function_caller " qualifier . calls_Class_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Indirect_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Subclass_method " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_OverridingSubclass_method " , [ ` Method { direct_target = " qualifier . OverridingSubclass . method " ; class_name = " qualifier . OverridingSubclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Class : @ classmethod def class_method ( cls ) : . . . class Indirect ( Class ) : . . . class Subclass ( Indirect ) : @ classmethod def class_method ( cls ) : . . . def calls_Class_class_method ( ) : Class . class_method ( ) def calls_Indirect_class_method ( ) : Indirect . class_method ( ) def calls_Subclass_class_method ( ) : Subclass . class_method ( ) def calls_Type_Class_class_method ( c : typing . Type [ Class ] ) : c . class_method ( ) def calls_Type_Indirect_class_method ( c : typing . Type [ Indirect ] ) : c . class_method ( ) def calls_Type_Subclass_class_method ( c : typing . Type [ Subclass ] ) : c . class_method ( ) } | [ ( function_caller " qualifier . calls_Class_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Indirect_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Subclass_class_method " , [ ` Method { direct_target = " qualifier . Subclass . class_method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Static ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Class_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Indirect_class_method " , [ ` Method { direct_target = " qualifier . Class . class_method " ; class_name = " qualifier . Indirect " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ( function_caller " qualifier . calls_Type_Subclass_class_method " , [ ` Method { direct_target = " qualifier . Subclass . class_method " ; class_name = " qualifier . Subclass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Class : def method ( ) : . . . class OtherClass : def method ( ) : . . . def calls_method_on_union ( union : typing . Union [ Class , OtherClass ] ) : union . method ( ) } | [ ( function_caller " qualifier . calls_method_on_union " , [ ` Method { direct_target = " qualifier . Class . method " ; class_name = " qualifier . Class " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ` Method { direct_target = " qualifier . OtherClass . method " ; class_name = " qualifier . OtherClass " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : def method ( ) : . . . def call_twice ( foo : Foo ) : foo . method ( ) bar = foo bar . method ( ) } | [ ( function_caller " qualifier . call_twice " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . def call_property ( foo : Foo ) : x = foo . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . class Bar ( Foo ) : pass def call_property ( bar : Bar ) : x = bar . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def x ( self ) -> int : . . . @ x . setter def x ( self , item : int ) -> None : . . . def call_property_setter ( foo : Foo ) -> None : foo . x = 1 } | [ ( function_caller " qualifier . call_property_setter " , [ ` PropertySetter { direct_target = " qualifier . Foo . x " ; class_name = " qualifier . Foo " } ] ) ; ] ; assert_calls { | class Foo : def method ( self ) -> int : . . . class Bar : pass def call_property ( bar : Bar ) : x = bar . method } | [ function_caller " qualifier . call_property " , [ ] ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . class Bar : @ property def method ( self ) -> int : . . . def call_property ( parameter : typing . Union [ Foo , Bar ] ) : x = parameter . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ` Method { direct_target = " qualifier . Bar . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | class Foo : @ property def method ( self ) -> int : . . . def call_property ( ) : x = Foo . method } | [ ( function_caller " qualifier . call_property " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | import typing class Foo : def method ( self ) -> int : . . . def calls_optional ( foo : typing . Optional [ Foo ] ) -> None : foo . method ( ) } | [ ( function_caller " qualifier . calls_optional " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | import typing class Foo : def method ( self ) -> int : . . . class Bar ( Foo ) : pass def calls_optional ( bar : typing . Optional [ Bar ] ) -> None : bar . method ( ) } | [ ( function_caller " qualifier . calls_optional " , [ ` Method { direct_target = " qualifier . Foo . method " ; class_name = " qualifier . Bar " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | from typing import Optional class Foo : @ property def x ( self ) -> int : . . . def optional_property ( foo : typing . Optional [ Foo ] ) -> None : y = foo . x } | [ ( function_caller " qualifier . optional_property " , [ ` Method { direct_target = " qualifier . Foo . x " ; class_name = " qualifier . Foo " ; is_optional_class_attribute = true ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | def calls_isinstance ( ) : x = 1 if isinstance ( x , int ) : return 0 return 1 } | [ function_caller " qualifier . calls_isinstance " , [ ` Function " isinstance " ] ] ; assert_calls { | from typing import Generic , TypeVar T = TypeVar ( " T " ) class C ( Generic [ T ] ) : def method ( self ) -> int : . . . class D ( C [ int ] ) : def method ( self ) -> int : . . . def calls_C_str ( c : C [ str ] ) -> None : c . method ( ) } | [ ( function_caller " qualifier . calls_C_str " , [ ` Method { direct_target = " qualifier . C . method " ; class_name = " qualifier . C [ str ] " ; is_optional_class_attribute = false ; dispatch = Dynamic ; } ; ] ) ; ] ; assert_calls { | def foo ( ) : . . . def bar ( ) : . . . class C : @ property def p ( self ) -> int : foo ( ) return 0 @ p . setter def p ( self , value : int ) -> None : bar ( ) } | [ function_caller " qualifier . C . p " , [ ` Function " qualifier . foo " ] ; property_setter_caller " qualifier . C . p " , [ ` Function " qualifier . bar " ] ; ]
let test_unpack_callable_and_self_argument context = let parse ~ global_resolution annotation = parse_single_expression ~ preprocess : true annotation |> GlobalResolution . parse_annotation global_resolution in let assert_unpack_type ( ? source = " " ) ~ signature_select given expected = let global_resolution = let { ScratchProject . BuiltGlobalEnvironment . global_environment ; _ } = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_global_environment in AnnotatedGlobalEnvironment . read_only global_environment |> GlobalResolution . create in let actual = TypeCheck . unpack_callable_and_self_argument ~ signature_select ~ global_resolution ( parse ~ global_resolution given ) in let expected = expected >>| fun ( callable , self_argument ) -> { TypeOperation . callable ; self_argument } in assert_equal ~ printer [ :% show : TypeOperation . callable_and_self_argument option ] ~ cmp [ :% eq : TypeOperation . callable_and_self_argument option ] actual expected in let assert_unpack ( ? source = " " ) given expected = let global_resolution = let { ScratchProject . BuiltGlobalEnvironment . global_environment ; _ } = ScratchProject . setup ~ context [ " test . py " , source ] |> ScratchProject . build_global_environment in AnnotatedGlobalEnvironment . read_only global_environment |> GlobalResolution . create in let expected = expected >>= fun ( expected_string , self_argument ) -> match parse ~ global_resolution expected_string with | Callable callable -> Some ( callable , self_argument ) | _ -> assert false in assert_unpack_type ~ source given expected in let signature_select ( ? pairs = [ ] ) ~ arguments : _ ~ callable ~ self_argument : _ = match pairs with | [ ( Type . Any , right ) ] -> SignatureSelectionTypes . Found { selected_return_annotation = right } | _ -> List . find ~ f ( : fun ( left , _ ) -> [ % eq : Type . t ] left ( Type . Callable callable ) ) pairs >>| ( fun ( _ , right ) -> SignatureSelectionTypes . Found { selected_return_annotation = right } ) |> Option . value ~ default : ( SignatureSelectionTypes . NotFound { closest_return_annotation = Type . Bottom ; reason = None } ) in let default_select ~ arguments : _ ~ callable : _ ~ self_argument : _ = SignatureSelectionTypes . Found { selected_return_annotation = Type . integer } in assert_unpack ~ signature_select : default_select " typing . Callable [ [ int ] , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack_type ~ signature_select : default_select " typing . Any " ( Some ( { kind = Anonymous ; implementation = { annotation = Type . Any ; parameters = Undefined } ; overloads = [ ] ; } , None ) ) ; assert_unpack_type ~ signature_select : default_select " typing . Any " ( Some ( { kind = Anonymous ; implementation = { annotation = Type . Any ; parameters = Undefined } ; overloads = [ ] ; } , None ) ) ; assert_unpack ~ signature_select : default_select " typing . Callable [ [ int ] , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack ~ signature_select : default_select " BoundMethod [ typing . Callable [ [ int ] , bool ] , str ] " ( Some ( " typing . Callable [ [ int ] , bool ] " , Some Type . string ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Generic , TypeVar T = TypeVar ( " T " ) class Foo ( Generic [ T ] ) : def __call__ ( self , x : int ) -> T : . . . } | " BoundMethod [ test . Foo [ str ] , int ] " ( Some ( " typing . Callable [ [ Named ( x , int ) ] , str ] " , Some Type . integer ) ) ; assert_unpack_type ~ signature_select : default_select ~ source : { | class Foo : def __call__ ( self , x : bool ) -> str : . . . class Bar : def __call__ ( self , x : str ) -> int : . . . } | " pyre_extensions . Compose [ test . Foo , test . Bar ] " ( Some ( { Type . Callable . kind = Type . Callable . Named ( Reference . create " test . Foo . __call__ " ) ; implementation = { parameters = Type . Callable . Defined [ Type . Callable . Parameter . Named { name = " $ parameter $ self " ; annotation = Type . Primitive " test . Foo " ; default = false ; } ; Type . Callable . Parameter . Named { name = " $ parameter $ x " ; annotation = Type . bool ; default = false } ; ] ; annotation = Type . integer ; } ; overloads = [ ] ; } , Some ( Type . Primitive " test . Foo " ) ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable class Bar : __call__ : Callable [ [ int ] , int ] = . . . class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " ( Some ( " typing . Callable [ [ int ] , int ] " , Some Type . integer ) ) ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable class Baz : __call__ : Callable [ [ int ] , int ] = . . . class Bar : __call__ : Baz = . . . class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " None ; assert_unpack ~ signature_select : default_select ~ source : { | class Bar : __call__ : int class Foo ( ) : __call__ : Bar = . . . } | " BoundMethod [ test . Foo , int ] " None ; assert_unpack ~ signature_select : default_select ~ source : { | from typing import Callable from pyre_extensions import Compose class Bar2 : __call__ : Compose [ Callable [ [ int ] , int ] , Callable [ [ int ] , int ] ] = . . . class Baz2 : __call__ : Compose [ Callable [ [ int ] , int ] , Callable [ [ int ] , int ] ] = . . . } | " pyre_extensions . Compose [ test . Bar2 , test . Baz2 ] " ( Some ( " typing . Callable [ [ int ] , int ] " , None ) ) ; assert_unpack ~ signature_select : default_select " typing . Tuple [ int , str ] " None ; assert_unpack ~ signature_select : ( signature_select ~ pairs : [ ( Type . Callable . create ~ parameters : ( Type . Callable . Defined [ PositionalOnly { index = 0 ; annotation = Type . integer ; default = false } ] ) ~ annotation : Type . float ( ) , Type . float ) ; ( Type . Callable . create ~ parameters : ( Type . Callable . Defined [ PositionalOnly { index = 0 ; annotation = Type . float ; default = false } ] ) ~ annotation : Type . string ( ) , Type . string ) ; ] ) { | pyre_extensions . Compose [ pyre_extensions . Compose [ typing . Callable [ [ bool ] , int ] , typing . Callable [ [ int ] , float ] ] , typing . Callable [ [ float ] , str ] ] } | ( Some ( " typing . Callable [ [ bool ] , str ] " , None ) ) ; ( )
let ( ) = " type " >::: [ " initial " >:: test_initial ; " less_or_equal " >:: test_less_or_equal ; " widen " >:: test_widen ; " check_annotation " >:: test_check_annotation ; " forward_expression " >:: test_forward_expression ; " forward_statement " >:: test_forward_statement ; " forward " >:: test_forward ; " module_exports " >:: test_module_exports ; " object_callables " >:: test_object_callables ; " callable_selection " >:: test_callable_selection ; " calls " >:: test_calls ; " unpack_callable_and_self_argument " >:: test_unpack_callable_and_self_argument ; ] |> Test . run
type ' a class_info = { cls_id : Ident . t ; cls_id_loc : string loc ; cls_decl : class_declaration ; cls_ty_id : Ident . t ; cls_ty_decl : class_type_declaration ; cls_obj_id : Ident . t ; cls_obj_abbr : type_declaration ; cls_typesharp_id : Ident . t ; cls_abbr : type_declaration ; cls_arity : int ; cls_pub_methods : string list ; cls_info : ' a ; }
type class_type_info = { clsty_ty_id : Ident . t ; clsty_id_loc : string loc ; clsty_ty_decl : class_type_declaration ; clsty_obj_id : Ident . t ; clsty_obj_abbr : type_declaration ; clsty_typesharp_id : Ident . t ; clsty_abbr : type_declaration ; clsty_info : Typedtree . class_type_declaration ; }
type ' a full_class = { id : Ident . t ; id_loc : tag loc ; clty : class_declaration ; ty_id : Ident . t ; cltydef : class_type_declaration ; obj_id : Ident . t ; obj_abbr : type_declaration ; cl_id : Ident . t ; cl_abbr : type_declaration ; arity : int ; pub_meths : string list ; coe : Warnings . loc list ; expr : ' a ; req : ' a Typedtree . class_infos ; }
type error = Unconsistent_constraint of Ctype . Unification_trace . t | Field_type_mismatch of string * string * Ctype . Unification_trace . t | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident . t | Unbound_class_type_2 of Longident . t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Ctype . Unification_trace . t | Virtual_class of bool * bool * string list * string list | Parameter_arity_mismatch of Longident . t * int * int | Parameter_mismatch of Ctype . Unification_trace . t | Bad_parameters of Ident . t * type_expr * type_expr | Class_match_failure of Ctype . class_match_failure list | Unbound_val of string | Unbound_type_var of ( formatter -> unit ) * Ctype . closed_class_failure | Non_generalizable_class of Ident . t * Types . class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident . t * Types . class_declaration * Ctype . Unification_trace . t | Final_self_clash of Ctype . Unification_trace . t | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of type_expr
let type_open_descr : ( ? used_slot : bool ref -> Env . t -> Parsetree . open_description -> open_description * Env . t ) ref = ref ( fun ? used_slot : _ _ -> assert false )
let ctyp desc typ env loc = { ctyp_desc = desc ; ctyp_type = typ ; ctyp_loc = loc ; ctyp_env = env ; ctyp_attributes = [ ] }
let unbound_class = Path . Pident ( Ident . create_local " * undef " ) *
let rec scrape_class_type = function Cty_constr ( _ , _ , cty ) -> scrape_class_type cty | cty -> cty
let rec generalize_class_type gen = function Cty_constr ( _ , params , cty ) -> List . iter gen params ; generalize_class_type gen cty | Cty_signature { csig_self = sty ; csig_vars = vars ; csig_inher = inher } -> gen sty ; Vars . iter ( fun _ ( _ , _ , ty ) -> gen ty ) vars ; List . iter ( fun ( _ , tl ) -> List . iter gen tl ) inher | Cty_arrow ( _ , ty , cty ) -> gen ty ; generalize_class_type gen cty
let generalize_class_type vars = let gen = if vars then Ctype . generalize else Ctype . generalize_structure in generalize_class_type gen
let virtual_methods sign = let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . Types . csig_self ) in List . fold_left ( fun virt ( lab , _ , _ ) -> if lab = dummy_method then virt else if Concr . mem lab sign . csig_concr then virt else lab :: virt ) [ ] fields
let rec constructor_type constr cty = match cty with Cty_constr ( _ , _ , cty ) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow ( l , ty , cty ) -> Ctype . newty ( Tarrow ( l , ty , constructor_type constr cty , Cok ) )
let rec class_body cty = match cty with Cty_constr _ -> cty | Cty_signature _ -> cty | Cty_arrow ( _ , _ , cty ) -> class_body cty