text
stringlengths 12
786k
|
---|
module UnannotatedGlobals = struct include DependencyTrackedMemory . DependencyTrackedTableNoCache ( SharedMemoryKeys . ReferenceKey ) ( DependencyKey ) ( UnannotatedGlobalValue ) let is_qualifier = false let key_to_reference = Fn . id end |
module ReadWrite = struct type t = { key_tracker : KeyTracker . t ; modules : Modules . t ; class_summaries : ClassSummaries . t ; function_definitions : FunctionDefinitions . t ; unannotated_globals : UnannotatedGlobals . t ; ast_environment : AstEnvironment . t ; } let create ast_environment = { key_tracker = KeyTracker . create ( ) ; modules = Modules . create ( ) ; class_summaries = ClassSummaries . create ( ) ; function_definitions = FunctionDefinitions . create ( ) ; unannotated_globals = UnannotatedGlobals . create ( ) ; ast_environment ; } let ast_environment { ast_environment ; _ } = ast_environment let configuration { ast_environment ; _ } = AstEnvironment . configuration ast_environment end |
let set_module { modules ; _ } ~ qualifier module_ = Modules . add modules qualifier module_ |
let set_class_summary { class_summaries ; _ } ~ name class_summary = ClassSummaries . write_around class_summaries name class_summary |
let set_function_definition { function_definitions ; _ } ~ name function_definition = FunctionDefinitions . write_around function_definitions name function_definition |
let set_unannotated_global { unannotated_globals ; _ } ~ name unannotated_global = UnannotatedGlobals . add unannotated_globals name unannotated_global |
let set_class_summaries ( { key_tracker ; _ } as environment ) ( { Source . source_path = { ModulePath . qualifier ; _ } ; _ } as source ) = let module ClassCollector = Visit . MakeStatementVisitor ( struct type t = Class . t Node . t list let visit_children _ = true let statement _ sofar = function | { Node . location ; value = Statement . Class definition } -> { Node . location ; value = definition } :: sofar | _ -> sofar end ) in let classes = ClassCollector . visit [ ] source in let classes = match Reference . as_list qualifier with | [ ] -> classes @ missing_builtin_classes | [ " typing " ] -> classes @ missing_typing_classes | [ " typing_extensions " ] -> classes @ missing_typing_extensions_classes | _ -> classes in let register new_annotations { Node . location ; value = { Class . name ; _ } as definition } = let primitive = Reference . show name in let definition = match primitive with | " type " -> let value = Type . expression ( Type . parametric " typing . Generic " [ Single ( Type . variable " typing . _T " ) ] ) in { definition with Class . base_arguments = [ { name = None ; value } ] } | _ -> definition in set_class_summary environment ~ name : primitive { Node . location ; value = ClassSummary . create ~ qualifier definition } ; Set . add new_annotations primitive in List . fold classes ~ init : Type . Primitive . Set . empty ~ f : register |> Set . to_list |> KeyTracker . add_class_keys key_tracker qualifier |
let set_function_definitions ( { key_tracker ; _ } as environment ) ( { Source . source_path = { ModulePath . qualifier ; is_external ; _ } ; _ } as source ) = match is_external with | true -> ( ) | false -> let function_definitions = FunctionDefinition . collect_defines source in let register ( name , function_definition ) = set_function_definition environment ~ name function_definition ; name in List . map function_definitions ~ f : register |> List . sort ~ compare : Reference . compare |> KeyTracker . add_define_keys key_tracker qualifier |
let set_unannotated_globals ( { key_tracker ; _ } as environment ) ( { Source . source_path = { ModulePath . qualifier ; _ } ; _ } as source ) = let write { UnannotatedGlobal . Collector . Result . name ; unannotated_global } = let name = Reference . create name |> Reference . combine qualifier in set_unannotated_global environment ~ name unannotated_global ; name in let merge_defines unannotated_globals_alist = let not_defines , defines = List . partition_map unannotated_globals_alist ~ f ( : function | { UnannotatedGlobal . Collector . Result . name ; unannotated_global = Define defines } -> Either . Second ( name , defines ) | x -> Either . First x ) in let add_to_map sofar ( name , defines ) = let merge_with_existing to_merge = function | None -> Some to_merge | Some existing -> Some ( to_merge @ existing ) in Map . change sofar name ~ f ( : merge_with_existing defines ) in List . fold defines ~ f : add_to_map ~ init : Identifier . Map . empty |> Identifier . Map . to_alist |> List . map ~ f ( : fun ( name , defines ) -> { UnannotatedGlobal . Collector . Result . name ; unannotated_global = Define ( List . rev defines ) ; } ) |> fun defines -> List . append defines not_defines in let drop_classes unannotated_globals = let is_not_class = function | { UnannotatedGlobal . Collector . Result . unannotated_global = Class ; _ } -> false | _ -> true in List . filter unannotated_globals ~ f : is_not_class in let globals = UnannotatedGlobal . Collector . from_source source |> merge_defines |> drop_classes in let globals = match Reference . as_list qualifier with | [ ] -> globals @ missing_builtin_globals | _ -> globals in globals |> List . map ~ f : write |> KeyTracker . add_unannotated_global_keys key_tracker qualifier |
let set_module_data environment ( { Source . source_path = { ModulePath . qualifier ; _ } ; _ } as source ) = set_class_summaries environment source ; set_function_definitions environment source ; set_unannotated_globals environment source ; set_module environment ~ qualifier ( Module . create source ) |
let add_to_transaction { modules ; class_summaries ; function_definitions ; unannotated_globals ; _ } transaction ~ previous_classes_list ~ previous_unannotated_globals_list ~ previous_defines_list ~ previous_modules_list = let module_keys = Modules . KeySet . of_list previous_modules_list in let class_keys = ClassSummaries . KeySet . of_list previous_classes_list in let defines_keys = FunctionDefinitions . KeySet . of_list previous_defines_list in let unannotated_globals_keys = UnannotatedGlobals . KeySet . of_list previous_unannotated_globals_list in transaction |> Modules . add_to_transaction modules ~ keys : module_keys |> ClassSummaries . add_to_transaction class_summaries ~ keys : class_keys |> FunctionDefinitions . add_to_transaction function_definitions ~ keys : defines_keys |> UnannotatedGlobals . add_to_transaction unannotated_globals ~ keys : unannotated_globals_keys |
let get_all_dependents ~ class_additions ~ unannotated_global_additions ~ define_additions = let function_and_class_dependents = DependencyKey . RegisteredSet . union ( ClassSummaries . KeySet . of_list class_additions |> ClassSummaries . get_all_dependents ) ( FunctionDefinitions . KeySet . of_list define_additions |> FunctionDefinitions . get_all_dependents ) in DependencyKey . RegisteredSet . union function_and_class_dependents ( UnannotatedGlobals . KeySet . of_list unannotated_global_additions |> UnannotatedGlobals . get_all_dependents ) |
module ReadOnly = struct type t = { ast_environment : AstEnvironment . ReadOnly . t ; class_exists : ? dependency : DependencyKey . registered -> string -> bool ; all_classes : unit -> Type . Primitive . t list ; all_indices : unit -> IndexTracker . t list ; all_unannotated_globals : unit -> Reference . t list ; all_defines : unit -> Reference . t list ; all_defines_in_module : Reference . t -> Reference . t list ; get_class_summary : ? dependency : DependencyKey . registered -> string -> ClassSummary . t Node . t option ; get_unannotated_global : ? dependency : DependencyKey . registered -> Reference . t -> UnannotatedGlobal . t option ; get_function_definition : ? dependency : DependencyKey . registered -> Reference . t -> FunctionDefinition . t option ; get_define_body : ? dependency : DependencyKey . registered -> Reference . t -> Define . t Node . t option ; get_module_metadata : ? dependency : DependencyKey . registered -> Reference . t -> Module . t option ; module_exists : ? dependency : SharedMemoryKeys . DependencyKey . registered -> Reference . t -> bool ; } let ast_environment { ast_environment ; _ } = ast_environment let unannotated_global_environment = Fn . id let all_classes { all_classes ; _ } = all_classes ( ) let all_indices { all_indices ; _ } = all_indices ( ) let all_defines { all_defines ; _ } = all_defines ( ) let all_unannotated_globals { all_unannotated_globals ; _ } = all_unannotated_globals ( ) let all_defines_in_module { all_defines_in_module ; _ } = all_defines_in_module let get_module_metadata { get_module_metadata ; _ } = get_module_metadata let module_exists { module_exists ; _ } = module_exists let get_class_summary { get_class_summary ; _ } = get_class_summary let class_exists { class_exists ; _ } = class_exists let get_function_definition { get_function_definition ; _ } = get_function_definition let get_define_body { get_define_body ; _ } = get_define_body let get_unannotated_global { get_unannotated_global ; _ } = get_unannotated_global let primitive_name annotation = let primitive , _ = Type . split annotation in Type . primitive_name primitive let is_protocol { get_class_summary ; _ } ? dependency annotation = primitive_name annotation >>= get_class_summary ? dependency >>| Node . value >>| ClassSummary . is_protocol |> Option . value ~ default : false let contains_untracked read_only ? dependency annotation = let is_tracked = class_exists read_only ? dependency in List . exists ~ f ( : fun annotation -> not ( is_tracked annotation ) ) ( Type . elements annotation ) let legacy_resolve_exports read_only ? dependency reference = let widening_threshold = 25 in let rec resolve_exports_fixpoint ~ reference ~ visited ~ count = if Set . mem visited reference || count > widening_threshold then reference else let rec resolve_exports ~ lead ~ tail = match tail with | head :: tail -> let incremented_lead = lead @ [ head ] in if Option . is_some ( get_module_metadata ? dependency read_only ( Reference . create_from_list incremented_lead ) ) then resolve_exports ~ lead : incremented_lead ~ tail else get_module_metadata ? dependency read_only ( Reference . create_from_list lead ) >>| ( fun definition -> match Module . legacy_aliased_export definition ( Reference . create head ) with | Some export -> Reference . combine export ( Reference . create_from_list tail ) | _ -> resolve_exports ~ lead ( : lead @ [ head ] ) ~ tail ) |> Option . value ~ default : reference | _ -> reference in match Reference . as_list reference with | head :: tail -> let exported_reference = resolve_exports ~ lead [ : head ] ~ tail in if Reference . is_strict_prefix ~ prefix : reference exported_reference then reference else resolve_exports_fixpoint ~ reference : exported_reference ~ visited ( : Set . add visited reference ) ~ count ( : count + 1 ) | _ -> reference in resolve_exports_fixpoint ~ reference ~ visited : Reference . Set . empty ~ count : 0 module ResolveExportItem = struct module T = struct type t = { current_module : Reference . t ; name : Identifier . t ; } [ @@ deriving sexp , compare , hash ] end include T include Hashable . Make ( T ) end let resolve_exports read_only ? dependency ( ? from = Reference . empty ) reference = let visited_set = ResolveExportItem . Hash_set . create ( ) in let rec resolve_module_alias ~ current_module ~ names_to_resolve ( ) = match get_module_metadata ? dependency read_only current_module with | None -> let rec resolve_placeholder_stub sofar = function | [ ] -> None | name :: prefixes -> ( let checked_module = List . rev prefixes |> Reference . create_from_list in let sofar = name :: sofar in match get_module_metadata ? dependency read_only checked_module with | Some module_metadata when Module . empty_stub module_metadata -> Some ( ResolvedReference . PlaceholderStub { stub_module = checked_module ; remaining = sofar } ) | _ -> resolve_placeholder_stub sofar prefixes ) in resolve_placeholder_stub names_to_resolve ( Reference . as_list current_module |> List . rev ) | Some module_metadata -> ( match Module . empty_stub module_metadata with | true -> Some ( ResolvedReference . PlaceholderStub { stub_module = current_module ; remaining = names_to_resolve } ) | false -> ( match names_to_resolve with | [ ] -> Some ( ResolvedReference . Module current_module ) | next_name :: rest_names -> ( let item = { ResolveExportItem . current_module ; name = next_name } in match Hash_set . strict_add visited_set item with | Result . Error _ -> None | Result . Ok _ -> ( match Module . get_export module_metadata next_name with | None -> ( match Module . get_export module_metadata " __getattr__ " with | Some Module . Export . ( Name ( Define { is_getattr_any = true } ) ) -> Some ( ResolvedReference . ModuleAttribute { from = current_module ; name = next_name ; export = ResolvedReference . FromModuleGetattr ; remaining = rest_names ; } ) | _ -> resolve_module_alias ~ current_module : ( Reference . create next_name |> Reference . combine current_module ) ~ names_to_resolve : rest_names ( ) ) | Some ( Module . Export . NameAlias { from ; name } ) -> if Reference . equal current_module from then resolve_module_alias ~ current_module ( : Reference . create name |> Reference . combine from ) ~ names_to_resolve : rest_names ( ) else resolve_module_alias ~ current_module : from ~ names_to_resolve ( : name :: rest_names ) ( ) | Some ( Module . Export . Module name ) -> resolve_module_alias ~ current_module : name ~ names_to_resolve : rest_names ( ) | Some ( Module . Export . Name export ) -> Some ( ResolvedReference . ModuleAttribute { from = current_module ; name = next_name ; export = ResolvedReference . Exported export ; remaining = rest_names ; } ) ) ) ) ) in resolve_module_alias ~ current_module : from ~ names_to_resolve ( : Reference . as_list reference ) ( ) let first_matching_class_decorator read_only ? dependency ~ names { Node . value = { ClassSummary . decorators ; _ } ; _ } = let resolve_and_check_for_match decorator = match Decorator . from_expression decorator with | None -> None | Some ( { Ast . Statement . Decorator . name = { Node . value = name ; location } ; _ } as decorator ) -> let resolved_name = match resolve_exports read_only ? dependency name with | Some ( ResolvedReference . ModuleAttribute { from ; name ; remaining ; _ } ) -> Reference . create_from_list ( name :: remaining ) |> Reference . combine from | _ -> name in let with_matched_name_if_matches name_to_match = if String . equal ( Reference . show resolved_name ) name_to_match then Some { decorator with name = { Node . value = resolved_name ; location } } else None in List . find_map names ~ f : with_matched_name_if_matches in List . find_map decorators ~ f : resolve_and_check_for_match let exists_matching_class_decorator read_only ? dependency ~ names class_summary = first_matching_class_decorator read_only ? dependency ~ names class_summary |> Option . is_some end |
module LazyLoader = struct type t = { environment : ReadWrite . t ; ast_environment : AstEnvironment . ReadOnly . t ; } let load_module_if_tracked { environment ; ast_environment } qualifier = if not ( Modules . mem environment . modules qualifier ) then if AstEnvironment . ReadOnly . is_module_tracked ast_environment qualifier then match AstEnvironment . ReadOnly . get_processed_source ~ track_dependency : true ast_environment qualifier with | Some source -> set_module_data environment source | None -> ( ) let load_all_possible_modules loader ~ is_qualifier reference = let load_module_if_tracked = load_module_if_tracked loader in let ancestors_descending = Reference . possible_qualifiers reference in List . iter ancestors_descending ~ f : load_module_if_tracked ; if is_qualifier then load_module_if_tracked reference ; ( ) end |
module ReadOnlyTable = struct module type S = sig type key type value type table type t val create : loader : LazyLoader . t -> table -> t val mem : t -> ? dependency : DependencyKey . registered -> key -> bool val get : t -> ? dependency : DependencyKey . registered -> key -> value option end module type In = sig type key type value type t val is_qualifier : bool val key_to_reference : key -> Reference . t val mem : t -> ? dependency : DependencyKey . registered -> key -> bool val get : t -> ? dependency : DependencyKey . registered -> key -> value option end module Make ( In : In ) : S with type key := In . key and type value := In . value and type table := In . t = struct type t = { loader : LazyLoader . t ; table : In . t ; } let create ~ loader table = { loader ; table } let is_qualifier = In . is_qualifier let mem { loader ; table } ? dependency key = match In . mem table ? dependency key with | true -> true | false -> LazyLoader . load_all_possible_modules loader ~ is_qualifier ( In . key_to_reference key ) ; In . mem table ? dependency key let get { loader ; table } ? dependency key = match In . get table ? dependency key with | Some _ as hit -> hit | None -> LazyLoader . load_all_possible_modules loader ~ is_qualifier ( In . key_to_reference key ) ; In . get table ? dependency key end end |
let read_only ( { ast_environment ; key_tracker ; modules ; class_summaries ; function_definitions ; unannotated_globals ; } as environment ) = let ast_environment = AstEnvironment . read_only ast_environment in let loader = LazyLoader . { environment ; ast_environment } in let module Modules = ReadOnlyTable . Make ( Modules ) in let module ClassSummaries = ReadOnlyTable . Make ( ClassSummaries ) in let module FunctionDefinitions = ReadOnlyTable . Make ( FunctionDefinitions ) in let module UnannotatedGlobals = ReadOnlyTable . Make ( UnannotatedGlobals ) in let modules = Modules . create ~ loader modules in let class_summaries = ClassSummaries . create ~ loader class_summaries in let function_definitions = FunctionDefinitions . create ~ loader function_definitions in let unannotated_globals = UnannotatedGlobals . create ~ loader unannotated_globals in let get_module = Modules . get modules in let get_module_metadata ? dependency qualifier = let qualifier = match Reference . as_list qualifier with | [ " future " ; " builtins " ] | [ " builtins " ] -> Reference . empty | _ -> qualifier in match get_module ? dependency qualifier with | Some _ as result -> result | None -> ( match AstEnvironment . ReadOnly . is_module_tracked ast_environment qualifier with | true -> Some ( Module . create_implicit ( ) ) | false -> None ) in let module_exists ? dependency qualifier = let qualifier = match Reference . as_list qualifier with | [ " future " ; " builtins " ] | [ " builtins " ] -> Reference . empty | _ -> qualifier in match Modules . mem modules ? dependency qualifier with | true -> true | false -> AstEnvironment . ReadOnly . is_module_tracked ast_environment qualifier in let get_class_summary = ClassSummaries . get class_summaries in let class_exists = ClassSummaries . mem class_summaries in let get_function_definition = FunctionDefinitions . get function_definitions in let get_define_body ? dependency key = get_function_definition ? dependency key >>= fun { FunctionDefinition . body ; _ } -> body in let get_unannotated_global = UnannotatedGlobals . get unannotated_globals in let all_defines_in_module qualifier = LazyLoader . load_module_if_tracked loader qualifier ; KeyTracker . get_define_keys key_tracker [ qualifier ] in let all_classes ( ) = AstEnvironment . ReadOnly . all_explicit_modules ast_environment |> KeyTracker . get_class_keys key_tracker in let all_indices ( ) = all_classes ( ) |> Type . Primitive . Set . of_list |> IndexTracker . indices |> IndexTracker . Set . to_list in let all_unannotated_globals ( ) = AstEnvironment . ReadOnly . all_explicit_modules ast_environment |> KeyTracker . get_unannotated_global_keys key_tracker in let all_defines ( ) = AstEnvironment . ReadOnly . all_explicit_modules ast_environment |> KeyTracker . get_define_keys key_tracker in { ReadOnly . ast_environment ; get_module_metadata ; module_exists ; get_class_summary ; class_exists ; get_function_definition ; get_define_body ; get_unannotated_global ; all_defines_in_module ; all_classes ; all_indices ; all_defines ; all_unannotated_globals ; } |
module UpdateResult = struct type t = { previous_classes : Type . Primitive . Set . t ; previous_defines : Reference . Set . t ; define_additions : Reference . Set . t ; previous_unannotated_globals : Reference . Set . t ; triggered_dependencies : DependencyKey . RegisteredSet . t ; invalidated_modules : AstEnvironment . InvalidatedModules . t ; read_only : ReadOnly . t ; } type read_only = ReadOnly . t let previous_classes { previous_classes ; _ } = previous_classes let previous_defines { previous_defines ; _ } = previous_defines let define_additions { define_additions ; _ } = define_additions let previous_unannotated_globals { previous_unannotated_globals ; _ } = previous_unannotated_globals let locally_triggered_dependencies { triggered_dependencies ; _ } = triggered_dependencies let all_triggered_dependencies environment = [ locally_triggered_dependencies environment ] let invalidated_modules { invalidated_modules ; _ } = invalidated_modules let unannotated_global_environment_update_result = Fn . id let read_only { read_only ; _ } = read_only end |
let cold_start ( { ast_environment ; _ } as environment ) = let ast_read_only = AstEnvironment . read_only ast_environment in AstEnvironment . ReadOnly . get_processed_source ast_read_only ~ track_dependency : true Reference . empty >>| set_module_data environment |> Option . value ~ default ( ) ; : read_only environment |
let update_this_and_all_preceding_environments ( { ast_environment ; key_tracker ; _ } as environment ) ~ scheduler trigger = let invalidated_modules = AstEnvironment . update ~ scheduler ast_environment trigger in let ast_environment = AstEnvironment . read_only ast_environment in let map sources = let register qualifier = AstEnvironment . ReadOnly . get_processed_source ~ track_dependency : true ast_environment qualifier >>| set_module_data environment |> Option . value ~ default ( ) : in List . iter sources ~ f : register in let update ( ) = SharedMemoryKeys . DependencyKey . Registry . collected_iter scheduler ~ policy : ( Scheduler . Policy . fixed_chunk_count ~ minimum_chunks_per_worker : 1 ~ minimum_chunk_size : 100 ~ preferred_chunks_per_worker : 5 ( ) ) ~ f : map ~ inputs : invalidated_modules in let KeyTracker . PreviousKeys . { previous_classes_list ; previous_classes ; previous_defines_list ; previous_defines ; previous_unannotated_globals_list ; previous_unannotated_globals ; } = KeyTracker . get_previous_keys_and_clear key_tracker invalidated_modules in let define_additions , triggered_dependencies = Profiling . track_duration_and_shared_memory_with_dynamic_tags " TableUpdate ( Unannotated globals ) " ~ f ( : fun _ -> let ( ) , mutation_triggers = DependencyKey . Transaction . empty ~ scheduler |> add_to_transaction environment ~ previous_classes_list ~ previous_unannotated_globals_list ~ previous_defines_list ~ previous_modules_list : invalidated_modules |> DependencyKey . Transaction . execute ~ update in let current_classes = KeyTracker . get_class_keys key_tracker invalidated_modules |> Type . Primitive . Set . of_list in let current_defines = KeyTracker . get_define_keys key_tracker invalidated_modules |> Reference . Set . of_list in let current_unannotated_globals = KeyTracker . get_unannotated_global_keys key_tracker invalidated_modules |> Reference . Set . of_list in let class_additions = Type . Primitive . Set . diff current_classes previous_classes in let define_additions = Reference . Set . diff current_defines previous_defines in let unannotated_global_additions = Reference . Set . diff current_unannotated_globals previous_unannotated_globals in let addition_triggers = get_all_dependents ~ class_additions ( : Set . to_list class_additions ) ~ unannotated_global_additions ( : Set . to_list unannotated_global_additions ) ~ define_additions ( : Set . to_list define_additions ) in let triggered_dependencies = DependencyKey . RegisteredSet . union addition_triggers mutation_triggers in let tags ( ) = let triggered_dependencies_size = SharedMemoryKeys . DependencyKey . RegisteredSet . cardinal triggered_dependencies |> Format . sprintf " % d " in [ " phase_name " , " Global discovery " ; " number_of_triggered_dependencies " , triggered_dependencies_size ; ] in { Profiling . result = define_additions , triggered_dependencies ; tags } ) in { UpdateResult . previous_classes ; previous_defines ; define_additions ; previous_unannotated_globals ; triggered_dependencies ; invalidated_modules ; read_only = read_only environment ; } |
let location ( start_line , start_column ) ( stop_line , stop_column ) = { Location . start = { Location . line = start_line ; column = start_column } ; stop = { Location . line = stop_line ; column = stop_column } ; } |
let create_with_location value start end_ = Node . create value ~ location ( : location start end_ ) |
let create_and_cold_start project = let ast_environment = ScratchProject . build_ast_environment project in let unannotated_global_environment = UnannotatedGlobalEnvironment . create ast_environment in let _ = UnannotatedGlobalEnvironment . cold_start unannotated_global_environment in unannotated_global_environment |
let test_global_registration context = let assert_registers ( ? expected = true ) source name = let project = ScratchProject . setup [ " test . py " , source ] ~ context in let read_only = create_and_cold_start project |> UnannotatedGlobalEnvironment . read_only in assert_equal ( UnannotatedGlobalEnvironment . ReadOnly . class_exists read_only name ) expected in assert_registers { | class Bar : pass } | " test . Bar " ; assert_registers ~ expected : false { | class Foo : pass } | " test . Bar " ; ( ) |
let test_define_registration context = let assert_registers ~ expected source = let project = ScratchProject . setup [ " test . py " , source ] ~ context in let read_only = create_and_cold_start project |> UnannotatedGlobalEnvironment . read_only in let actual = UnannotatedGlobalEnvironment . ReadOnly . all_defines_in_module read_only " !& test " in let expected = List . sort expected ~ compare : Reference . compare in assert_equal ~ cmp ( : List . equal Reference . equal ) ~ printer ( : List . to_string ~ f : Reference . show ) expected actual in assert_registers { | def foo ( ) : pass } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ] ; assert_registers { | def bar ( ) : . . . def foo ( ) : return bar ( ) } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ; " !& test . bar " ] ; assert_registers { | from typing import overload @ overload def foo ( x : int ) -> int : . . . @ overload def foo ( x : str ) -> str : . . . def foo ( x ) : return x } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ] ; assert_registers { | class Foo : pass } | ~ expected [ " :!& test . $ toplevel " ; " !& test . Foo . $ class_toplevel " ] ; assert_registers { | class Foo : x : int class Foo : y : str } | ~ expected [ " :!& test . $ toplevel " ; " !& test . Foo . $ class_toplevel " ] ; assert_registers { | class Foo : def foo ( self ) : . . . } | ~ expected [ " :!& test . $ toplevel " ; " !& test . Foo . $ class_toplevel " ; " !& test . Foo . foo " ] ; assert_registers { | class Foo : @ property def foo ( self ) : . . . @ foo . setter def foo ( self , value ) : . . . } | ~ expected [ " :!& test . $ toplevel " ; " !& test . Foo . $ class_toplevel " ; " !& test . Foo . foo " ] ; assert_registers { | def foo ( ) : def bar ( ) : . . . return bar ( ) } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ] ; assert_registers { | def foo ( ) : def bar ( ) : pass bar ( ) def baz ( ) : pass baz ( ) } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo $ baz " ] ; assert_registers { | def foo ( ) : def bar ( ) : def baz ( ) : pass bar ( x ) } | ~ expected : [ " !& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo ? bar $ baz " ] ; assert_registers { | def foo ( flag ) : if flag : def bar ( ) : pass return bar ( ) else : def baz ( ) : pass return baz ( ) } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo $ baz " ] ; assert_registers { | def foo ( ) : for x in range ( 3 ) : def bar ( ) : def baz ( ) : pass return bar ( x ) } | ~ expected : [ " !& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo ? bar $ baz " ] ; assert_registers { | def foo ( ) : with open ( " something " ) as f : def bar ( ) : def baz ( ) : pass bar ( ) } | ~ expected : [ " !& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo ? bar $ baz " ] ; assert_registers { | def foo ( ) : try : def bar ( ) : pass bar ( ) except : def baz ( ) : pass baz ( ) finally : def quix ( ) : pass return quix ( ) } | ~ expected : [ " !& test . $ toplevel " ; " !& test . foo " ; " !&$ local_test ? foo $ bar " ; " !&$ local_test ? foo $ baz " ; " !&$ local_test ? foo $ quix " ; ] ; assert_registers { | def foo ( ) : class C : x : int def bar ( self ) : . . . } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ] ; assert_registers { | def foo ( ) : class C : x : int def bar ( self ) : class D : def baz ( self ) : . . . } | ~ expected [ " :!& test . $ toplevel " ; " !& test . foo " ] ; assert_registers { | class C : def foo ( self ) : . . . class D : def bar ( self ) : . . . } | ~ expected : [ " !& test . $ toplevel " ; " !& test . C . $ class_toplevel " ; " !& test . C . foo " ; " !& test . C . D . $ class_toplevel " ; " !& test . C . D . bar " ; ] ; ( ) |
let test_simple_global_registration context = let assert_registers source name expected = let project = ScratchProject . setup [ " test . py " , source ] ~ context in let read_only = create_and_cold_start project |> UnannotatedGlobalEnvironment . read_only in let printer global = global >>| UnannotatedGlobal . sexp_of_t >>| Sexp . to_string_hum |> Option . value ~ default " : None " in let location_insensitive_compare left right = Option . compare UnannotatedGlobal . compare left right = 0 in assert_equal ~ cmp : location_insensitive_compare ~ printer expected ( UnannotatedGlobalEnvironment . ReadOnly . get_unannotated_global read_only ( Reference . create name ) ) in let target_location = { Location . start = { line = 2 ; column = 0 } ; stop = { line = 2 ; column = 3 } } |> Location . with_module ~ module_reference ( : Reference . create " test " ) in let value_location = { Location . start = { line = 2 ; column = 6 } ; stop = { line = 2 ; column = 7 } } in let value = let value = parse_single_expression " 8 " in { value with location = value_location } in assert_registers { | bar = 8 } | " test . bar " ( Some ( SimpleAssign { explicit_annotation = None ; value ; target_location } ) ) ; assert_registers { | other . bar = 8 } | " test . other . bar " None ; assert_registers { | other . bar = 8 } | " other . bar " None ; assert_registers { | try : baz = 8 except : pass } | " test . baz " ( Some ( SimpleAssign { explicit_annotation = None ; value = create_with_location ( Expression . Expression . Constant ( Expression . Constant . Integer 8 ) ) ( 3 , 8 ) ( 3 , 9 ) ; target_location = { Location . start = { line = 3 ; column = 2 } ; stop = { line = 3 ; column = 5 } } |> Location . with_module ~ module_reference ( : Reference . create " test " ) ; } ) ) ; let parse_define define = match parse_single_statement define ~ preprocess : true ~ handle " : test . py " with | { Node . value = Statement . Statement . Define { signature ; _ } ; location } -> { UnannotatedGlobal . UnannotatedDefine . define = signature ; location = Location . with_module ~ module_reference ( : Reference . create " test " ) location ; } | _ -> failwith " not define " in assert_registers { | def foo ( x : int ) -> str : pass def foo ( x : float ) -> bool : pass } | " test . foo " ( Some ( Define [ parse_define { | def foo ( x : int ) -> str : pass } ; | parse_define { | # spacer # spacer def foo ( x : float ) -> bool : pass } ; | ] ) ) ; ( ) |
let test_builtin_modules context = let read_only = let sources = [ " builtins . py " , " foo : int = 42 " ] in let project = ScratchProject . setup ~ context ~ include_typeshed_stubs : false ~ include_helper_builtins : false sources in create_and_cold_start project |> UnannotatedGlobalEnvironment . read_only in assert_bool " empty qualifier module exists " ( UnannotatedGlobalEnvironment . ReadOnly . module_exists read_only Reference . empty ) ; assert_bool " random qualifier doesn ' t exist " ( not ( UnannotatedGlobalEnvironment . ReadOnly . module_exists read_only " !& derp " ) ) ; assert_bool " ` builtins ` exists " ( UnannotatedGlobalEnvironment . ReadOnly . module_exists read_only " !& builtins " ) ; assert_bool " ` future . builtins ` exists " ( UnannotatedGlobalEnvironment . ReadOnly . module_exists read_only " !& future . builtins " ) ; let assert_nonempty qualifier = match UnannotatedGlobalEnvironment . ReadOnly . get_module_metadata read_only qualifier with | None -> assert_failure " Module does not exist " | Some metadata -> assert_bool " empty stub not expected " ( not ( Module . empty_stub metadata ) ) ; assert_bool " implicit module not expected " ( not ( Module . is_implicit metadata ) ) ; assert_equal ~ ctxt : context ~ cmp [ :% compare . equal : Module . Export . t option ] ~ printer ( : fun export -> Sexp . to_string_hum [ % message ( export : Module . Export . t option ) ] ) ( Some Module . Export . ( Name GlobalVariable ) ) ( Module . get_export metadata " foo " ) in assert_nonempty Reference . empty ; assert_nonempty " !& builtins " ; assert_nonempty " !& future . builtins " ; ( ) |
let test_resolve_exports context = let open UnannotatedGlobalEnvironment in let assert_resolved ( ? include_typeshed = false ) ~ expected ? from ~ reference sources = Memory . reset_shared_memory ( ) ; let project = if include_typeshed then ScratchProject . setup ~ context sources else ScratchProject . setup ~ context ~ include_typeshed_stubs : false ~ include_helper_builtins : false ~ external_sources [ " : builtins . py " , " " ] sources in let read_only = create_and_cold_start project |> UnannotatedGlobalEnvironment . read_only in let actual = ReadOnly . resolve_exports read_only ? from reference in assert_equal ~ ctxt : context ~ cmp [ :% compare . equal : ResolvedReference . t option ] ~ printer ( : fun result -> Sexp . to_string_hum [ % message ( result : ResolvedReference . t option ) ] ) expected actual in let resolved_module name = ResolvedReference . Module name in let resolved_attribute ( ? remaining = [ ] ) ? export from name = let export = match export with | None -> ResolvedReference . FromModuleGetattr | Some export -> ResolvedReference . Exported export in ResolvedReference . ModuleAttribute { from ; name ; export ; remaining } in let resolved_placeholder_stub ( ? remaining = [ ] ) stub_module = ResolvedReference . PlaceholderStub { stub_module ; remaining } in let open Module in assert_resolved [ ] ~ reference " :!& derp " ~ expected : None ; assert_resolved [ " derp . py " , " " ] ~ reference " :!& derp " ~ expected ( : Some ( resolved_module " !& derp " ) ) ; assert_resolved [ " derp . py " , " " ] ~ reference " :!& derp . foo " ~ expected : None ; assert_resolved [ " derp . pyi " , " # pyre - placeholder - stub " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_placeholder_stub " !& derp " ~ remaining [ " : foo " ] ) ) ; assert_resolved [ " derp / foo . pyi " , " # pyre - placeholder - stub " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_placeholder_stub " !& derp . foo " ) ) ; assert_resolved [ " derp / foo . py " , " " ] ~ reference " :!& derp " ~ expected ( : Some ( resolved_module " !& derp " ) ) ; assert_resolved [ " derp / foo . py " , " " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_module " !& derp . foo " ) ) ; assert_resolved [ " derp / foo . py " , " " ] ~ reference " :!& derp . foo . bar " ~ expected : None ; assert_resolved [ " derp / __init__ . py " , " " ; " derp / foo . py " , " " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_module " !& derp . foo " ) ) ; assert_resolved [ " derp / __init__ . py " , " foo = 1 " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_attribute " !& derp " " foo " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " derp . py " , " foo = 1 " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_attribute " !& derp " " foo " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " derp . py " , " def foo ( ) : pass " ] ~ reference " :!& derp . foo " ~ expected : ( Some ( resolved_attribute " !& derp " " foo " ~ export ( : Export . Name . Define { is_getattr_any = false } ) ) ) ; assert_resolved [ " derp . py " , " class foo : pass " ] ~ reference " :!& derp . foo " ~ expected ( : Some ( resolved_attribute " !& derp " " foo " ~ export : Export . Name . Class ) ) ; assert_resolved [ " derp . py " , " class foo : pass " ] ~ reference " :!& derp . foo . bar . baz " ~ expected : ( Some ( resolved_attribute " !& derp " " foo " ~ export : Export . Name . Class ~ remaining [ " : bar " ; " baz " ] ) ) ; assert_resolved [ " a . py " , " import b " ] ~ reference " :!& a . b " ~ expected : None ; assert_resolved [ " a . py " , " import b " ; " b . py " , " " ] ~ reference " :!& a . b " ~ expected ( : Some ( resolved_module " !& b " ) ) ; assert_resolved [ " a . py " , " import b " ; " b / c . py " , " " ] ~ reference " :!& a . b " ~ expected ( : Some ( resolved_module " !& b " ) ) ; assert_resolved [ " a . py " , " import b " ; " b / c . py " , " " ] ~ reference " :!& a . b . c " ~ expected ( : Some ( resolved_module " !& b . c " ) ) ; assert_resolved [ " a . py " , " import b as c " ; " b . py " , " " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_module " !& b " ) ) ; assert_resolved [ " a . py " , " from b import c " ] ~ reference " :!& a . c " ~ expected : None ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " " ] ~ reference " :!& a . c " ~ expected : None ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " import c " ; " c . py " , " " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_module " !& c " ) ) ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " import c " ; " c . py " , " " ] ~ reference " :!& a . c . d " ~ expected : None ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " c = 42 " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_attribute " !& b " " c " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from b import c as d " ; " b . py " , " c = 42 " ] ~ reference " :!& a . d " ~ expected ( : Some ( resolved_attribute " !& b " " c " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from b import c as d " ; " b . py " , " c = 42 " ] ~ reference " :!& a . d . e " ~ expected : ( Some ( resolved_attribute " !& b " " c " ~ export : Export . Name . GlobalVariable ~ remaining [ " : e " ] ) ) ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " from d import c " ; " d . py " , " c = 42 " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_attribute " !& d " " c " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " from d import c " ; " d . py " , " from e import f as c " ; " e . py " , " f = 42 " ; ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_attribute " !& e " " f " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from b import foo " ; " b . py " , " from c import bar as foo " ; " c . py " , " from d import cow as bar " ; " d . py " , " cow = 1 " ; ] ~ reference " :!& a . foo " ~ expected ( : Some ( resolved_attribute " !& d " " cow " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from typing import Any \ nb = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ] ~ reference " :!& a . b " ~ expected ( : Some ( resolved_attribute " !& a " " b " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from typing import Any \ nb = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_attribute " !& a " " c " ) ) ; assert_resolved [ " a . py " , " from typing import Any \ nb = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ] ~ reference " :!& a . c . d " ~ expected ( : Some ( resolved_attribute " !& a " " c " ~ remaining [ " : d " ] ) ) ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " from typing import Any \ nc = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ; ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_attribute " !& b " " c " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " a . py " , " from b import d " ; " b . py " , " from typing import Any \ nc = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ; ] ~ reference " :!& a . d " ~ expected ( : Some ( resolved_attribute " !& b " " d " ) ) ; assert_resolved [ " a . py " , " from b import d " ; " b . py " , " from typing import Any \ nc = 42 \ ndef __getattr__ ( name ) -> Any : . . . " ; ] ~ reference " :!& a . d . e " ~ expected ( : Some ( resolved_attribute " !& b " " d " ~ remaining [ " : e " ] ) ) ; assert_resolved [ " a . py " , " from b import c " ; " b . pyi " , " # pyre - placeholder - stub " ] ~ reference " :!& a . c . d " ~ expected ( : Some ( resolved_placeholder_stub " !& b " ~ remaining [ " : c " ; " d " ] ) ) ; assert_resolved [ " a . py " , " from a import b " ] ~ reference " :!& a . b " ~ expected : None ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " from a import c " ] ~ reference " :!& a . c " ~ expected : None ; assert_resolved [ " a . py " , " from b import c " ; " b . py " , " from d import c " ; " d . py " , " from b import c " ] ~ reference " :!& a . c " ~ expected : None ; assert_resolved [ " a / __init__ . py " , " from a import b " ] ~ reference " :!& a . b " ~ expected : None ; assert_resolved [ " a / __init__ . py " , " from a import b " ; " a / b . py " , " " ] ~ reference " :!& a . b " ~ expected ( : Some ( resolved_module " !& a . b " ) ) ; assert_resolved [ " a / __init__ . py " , " from a import b as c " ; " a / b . py " , " " ] ~ reference " :!& a . c " ~ expected ( : Some ( resolved_module " !& a . b " ) ) ; assert_resolved [ " a . py " , " from a import b " ; " a / b . py " , " " ] ~ reference " :!& a . b " ~ expected ( : Some ( resolved_module " !& a . b " ) ) ; assert_resolved [ " a . py " , " b = 1 \ nfrom a import b " ] ~ reference " :!& a . b " ~ expected : None ; assert_resolved [ " a . py " , " from b . c import d " ; " b . py " , " import c " ; " c . py " , " d = 42 " ] ~ reference " :!& a . d " ~ expected : None ; assert_resolved [ " a . py " , " from b . nonexistent import foo " ; " b . pyi " , " # pyre - placeholder - stub " ] ~ reference " :!& a . foo " ~ expected ( : Some ( resolved_placeholder_stub " !& b " ~ remaining [ " : nonexistent " ; " foo " ] ) ) ; assert_resolved [ " qualifier . py " , " from qualifier . foo import foo " ; " qualifier / __init__ . py " , " " ; " qualifier / foo / __init__ . py " , " foo = 1 " ; ] ~ reference " :!& qualifier . foo . foo " ~ expected ( : Some ( resolved_attribute " !& qualifier . foo " " foo " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " qualifier / __init__ . py " , " from qualifier . a import bar as a " ; " qualifier / a . py " , " foo = 1 \ nbar = 1 " ; ] ~ reference " :!& qualifier . a " ~ expected ( : Some ( resolved_attribute " !& qualifier . a " " bar " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " qualifier / __init__ . py " , " from qualifier . a import bar as a " ; " qualifier / a . py " , " foo = 1 \ nbar = 1 " ; ] ~ reference " :!& qualifier . a . foo " ~ expected : ( Some ( resolved_attribute " !& qualifier . a " " bar " ~ export : Export . Name . GlobalVariable ~ remaining [ " : foo " ] ) ) ; assert_resolved [ " qualifier / __init__ . py " , " from qualifier . a import bar as a " ; " qualifier / a . py " , " foo = 1 \ nbar = 1 " ; ] ~ from " :!& qualifier . a " ~ reference " :!& foo " ~ expected ( : Some ( resolved_attribute " !& qualifier . a " " foo " ~ export : Export . Name . GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __doc__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __doc__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __file__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __file__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __name__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __name__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __package__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __package__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __path__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __path__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " " ] ~ reference " :!& foo . __dict__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __dict__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo / bar . py " , " " ] ~ reference " :!& foo . __name__ " ~ expected ( : Some ( resolved_attribute " !& foo " " __name__ " ~ export : GlobalVariable ) ) ; assert_resolved [ " foo . py " , " from bar import __name__ " ; " bar . py " , " " ] ~ reference " :!& foo . __name__ " ~ expected ( : Some ( resolved_attribute " !& bar " " __name__ " ~ export : GlobalVariable ) ) ; ( ) |
let assert_updates ~ context ? original_source ? new_source ~ middle_actions ~ expected_triggers ? post_actions ( ) = Memory . reset_shared_memory ( ) ; let sources = original_source >>| ( fun source -> " test . py " , source ) |> Option . to_list in let project = ScratchProject . setup ~ include_typeshed_stubs : false ~ incremental_style : FineGrained ~ in_memory : false sources ~ context in let configuration = ScratchProject . configuration_of project in let unannotated_global_environment = create_and_cold_start project in let read_only = UnannotatedGlobalEnvironment . read_only unannotated_global_environment in let execute_action = function | ` Get ( class_name , dependency , expected_number_of_statements ) -> let printer number = number >>| Format . sprintf " number of attributes : % d " |> Option . value ~ default " : No class " in UnannotatedGlobalEnvironment . ReadOnly . get_class_summary read_only ~ dependency class_name >>| Node . value >>| ClassSummary . attributes >>| Identifier . SerializableMap . bindings >>| List . length |> assert_equal ~ printer expected_number_of_statements | ` Mem ( class_name , dependency , expectation ) -> UnannotatedGlobalEnvironment . ReadOnly . class_exists read_only ~ dependency class_name |> assert_equal expectation | ` AllClasses expectation -> let _force_lazy_loading_of_module_ = UnannotatedGlobalEnvironment . ReadOnly . get_module_metadata read_only ( Reference . create " test " ) in UnannotatedGlobalEnvironment . ReadOnly . all_classes read_only |> assert_equal ~ printer ( : List . to_string ~ f : Fn . id ) expectation | ` Global ( global_name , dependency , expectation ) -> let printer optional = optional >>| UnannotatedGlobal . sexp_of_t >>| Sexp . to_string_hum |> Option . value ~ default " : none " in let cmp left right = Option . compare UnannotatedGlobal . compare left right = 0 in let remove_target_location = function | UnannotatedGlobal . SimpleAssign assign -> UnannotatedGlobal . SimpleAssign { assign with target_location = Location . WithModule . any } | UnannotatedGlobal . TupleAssign assign -> UnannotatedGlobal . TupleAssign { assign with target_location = Location . WithModule . any } | global -> global in UnannotatedGlobalEnvironment . ReadOnly . get_unannotated_global read_only global_name ~ dependency >>| remove_target_location |> assert_equal ~ cmp ~ printer expectation | ` Define ( define_name , dependency , expectation ) -> let actual = UnannotatedGlobalEnvironment . ReadOnly . get_function_definition read_only define_name ~ dependency in let cmp left right = Int . equal 0 ( Option . compare FunctionDefinition . compare left right ) in let print format definition = Format . fprintf format " % s " ( Sexp . to_string_hum [ % message ( definition : FunctionDefinition . t option ) ] ) in assert_equal ~ cmp ~ printer ( : fun definition -> Sexp . to_string_hum [ % message ( definition : FunctionDefinition . t option ) ] ) ~ pp_diff ( : diff ~ print ) expectation actual | ` DefineBody ( define_name , dependency , expectation ) -> let actual = UnannotatedGlobalEnvironment . ReadOnly . get_define_body read_only define_name ~ dependency in let cmp = [ % compare . equal : Statement . Define . t Node . t option ] in assert_equal ~ cmp ~ printer ( : fun bodies -> Sexp . to_string_hum [ % message ( bodies : Statement . Define . t Node . t option ) ] ) expectation actual in List . iter middle_actions ~ f : execute_action ; let add_file { ScratchProject . configuration = { Configuration . Analysis . local_root ; _ } ; _ } content ~ relative = let content = trim_extra_indentation content in let file = File . create ~ content ( PyrePath . create_relative ~ root : local_root ~ relative ) in File . write file in let delete_file { ScratchProject . configuration = { Configuration . Analysis . local_root ; _ } ; _ } relative = PyrePath . create_relative ~ root : local_root ~ relative |> PyrePath . absolute |> Core . Unix . remove in if Option . is_some original_source then delete_file project " test . py " ; new_source >>| add_file project ~ relative " : test . py " |> Option . value ~ default ( ) ; : let { ScratchProject . module_tracker ; _ } = project in let { Configuration . Analysis . local_root ; _ } = configuration in let path = Test . relative_artifact_path ~ root : local_root ~ relative " : test . py " in let update_result = ModuleTracker . update ~ paths [ : path ] module_tracker |> ( fun updates -> AstEnvironment . Update updates ) |> UnannotatedGlobalEnvironment . update_this_and_all_preceding_environments unannotated_global_environment ~ scheduler ( : mock_scheduler ( ) ) in let printer set = SharedMemoryKeys . DependencyKey . RegisteredSet . elements set |> List . map ~ f : SharedMemoryKeys . DependencyKey . get_key |> List . to_string ~ f : SharedMemoryKeys . show_dependency in let expected_triggers = SharedMemoryKeys . DependencyKey . RegisteredSet . of_list expected_triggers in post_actions >>| List . iter ~ f : execute_action |> Option . value ~ default ( ) ; : assert_equal ~ cmp : SharedMemoryKeys . DependencyKey . RegisteredSet . equal ~ printer expected_triggers ( UnannotatedGlobalEnvironment . UpdateResult . locally_triggered_dependencies update_result ) |
let type_check_dependency = SharedMemoryKeys . DependencyKey . Registry . register ( TypeCheckDefine ( Reference . create " test " ) ) |
let alias_dependency = SharedMemoryKeys . DependencyKey . Registry . register ( TypeCheckDefine ( Reference . create " dep " ) ) |
let test_get_class_summary context = let assert_updates = assert_updates ~ context in let dependency = type_check_dependency in assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Foo : x : str } | ~ middle_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ~ expected_triggers [ : dependency ] ( ) ; assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Foo : x : str } | ~ middle_actions [ ` : Get ( " test . Missing " , dependency , None ) ] ~ expected_triggers [ ] : ( ) ; assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Unrelated : x : int class Foo : x : int } | ~ middle_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ~ expected_triggers [ : dependency ] ( ) ; assert_updates ~ original_source : { | class Foo : x : int class Foo : x : int y : int } | ~ new_source { :| class Unrelated : x : int class Foo : x : int } | ~ middle_actions [ ` : Get ( " test . Foo " , dependency , Some 2 ) ] ~ expected_triggers [ : dependency ] ~ post_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ( ) ; assert_updates ~ original_source : { | class Foo : def method ( self ) -> None : print ( " hello " ) } | ~ new_source { :| class Foo : def method ( self ) -> int : return 1 } | ~ middle_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ~ expected_triggers [ : dependency ] ~ post_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ( ) ; assert_updates ~ original_source : { | class Foo : def method ( self ) -> None : print ( " hellobo " ) } | ~ new_source : { | class Foo : def method ( self ) -> None : print ( " goodbye " ) } | ~ middle_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ~ expected_triggers [ ] : ~ post_actions [ ` : Get ( " test . Foo " , dependency , Some 1 ) ] ( ) ; ( ) |
let test_class_exists_and_all_classes context = let assert_updates = assert_updates ~ context in let dependency = type_check_dependency in assert_updates ~ new_source { :| class Foo : x : int } | ~ middle_actions [ ` : Mem ( " test . Foo " , dependency , false ) ] ~ expected_triggers [ : dependency ] ( ) ; assert_updates ~ original_source { :| class Foo : x : int } | ~ middle_actions [ ` : Mem ( " test . Foo " , dependency , true ) ] ~ expected_triggers [ : dependency ] ( ) ; assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Foo : x : int } | ~ middle_actions [ ` : Mem ( " test . Foo " , dependency , true ) ] ~ expected_triggers [ ] : ( ) ; assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Foo : x : str } | ~ middle_actions [ ` : Mem ( " test . Foo " , dependency , true ) ] ~ expected_triggers [ ] : ( ) ; assert_updates ~ original_source { :| class Foo : x : int class Bar : y : str } | ~ new_source { :| class Foo : x : str } | ~ middle_actions [ ` : AllClasses [ " test . Bar " ; " test . Foo " ] ] ~ expected_triggers [ ] : ~ post_actions [ ` : AllClasses [ " test . Foo " ] ] ( ) ; ( ) |
let test_get_unannotated_global context = let assert_updates = assert_updates ~ context in let dependency = alias_dependency in assert_updates ~ original_source { :| x : int = 7 } | ~ new_source { :| x : int = 9 } | ~ middle_actions : [ ` Global ( Reference . create " test . x " , dependency , Some ( UnannotatedGlobal . SimpleAssign { explicit_annotation = Some { ( parse_single_expression " int " ) with location = location ( 2 , 3 ) ( 2 , 6 ) } ; value = { ( parse_single_expression " 7 " ) with location = location ( 2 , 9 ) ( 2 , 10 ) } ; target_location = Location . WithModule . any ; } ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` Global ( Reference . create " test . x " , dependency , Some ( UnannotatedGlobal . SimpleAssign { explicit_annotation = Some { ( parse_single_expression " int " ) with location = location ( 2 , 3 ) ( 2 , 6 ) } ; value = { ( parse_single_expression " 9 " ) with location = location ( 2 , 9 ) ( 2 , 10 ) } ; target_location = Location . WithModule . any ; } ) ) ; ] ( ) ; assert_updates ~ original_source { :| import target . member as alias } | ~ new_source { :| import target . member as new_alias } | ~ middle_actions : [ ` Global ( Reference . create " test . alias " , dependency , Some ( UnannotatedGlobal . Imported ( UnannotatedGlobal . ImportEntry . Module { target = " !& target . member " ; implicit_alias = false } ) ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions [ ` : Global ( Reference . create " test . alias " , dependency , None ) ] ( ) ; assert_updates ~ original_source { :| from target import member , other_member } | ~ new_source { :| from target import other_member , member } | ~ middle_actions : [ ` Global ( Reference . create " test . member " , dependency , Some ( UnannotatedGlobal . Imported ( UnannotatedGlobal . ImportEntry . Name { from = " !& target " ; target = " member " ; implicit_alias = true } ) ) ) ; ` Global ( Reference . create " test . other_member " , dependency , Some ( UnannotatedGlobal . Imported ( UnannotatedGlobal . ImportEntry . Name { from = " !& target " ; target = " other_member " ; implicit_alias = true } ) ) ) ; ] ~ expected_triggers [ ] : ~ post_actions : [ ` Global ( Reference . create " test . member " , dependency , Some ( UnannotatedGlobal . Imported ( UnannotatedGlobal . ImportEntry . Name { from = " !& target " ; target = " member " ; implicit_alias = true } ) ) ) ; ` Global ( Reference . create " test . other_member " , dependency , Some ( UnannotatedGlobal . Imported ( UnannotatedGlobal . ImportEntry . Name { from = " !& target " ; target = " other_member " ; implicit_alias = true } ) ) ) ; ] ( ) ; assert_updates ~ original_source { :| from target import * } | ~ middle_actions [ ` : Global ( Reference . create " test . " , * dependency , None ) ] ~ expected_triggers [ ] : ( ) ; let open Statement in let open Expression in let tuple_expression = node ~ start ( : 2 , 10 ) ~ stop ( : 2 , 24 ) ( Expression . Tuple [ node ~ start ( : 2 , 10 ) ~ stop ( : 2 , 13 ) ( Expression . Name ( Name . Identifier " int " ) ) ; node ~ start ( : 2 , 15 ) ~ stop ( : 2 , 18 ) ( Expression . Name ( Name . Identifier " str " ) ) ; node ~ start ( : 2 , 20 ) ~ stop ( : 2 , 24 ) ( Expression . Name ( Name . Identifier " bool " ) ) ; ] ) in assert_updates ~ original_source { :| X , Y , Z = int , str , bool } | ~ middle_actions : [ ` Global ( Reference . create " test . X " , dependency , Some ( UnannotatedGlobal . TupleAssign { value = tuple_expression ; index = 0 ; target_location = Location . WithModule . any ; total_length = 3 ; } ) ) ; ` Global ( Reference . create " test . Y " , dependency , Some ( UnannotatedGlobal . TupleAssign { value = tuple_expression ; index = 1 ; target_location = Location . WithModule . any ; total_length = 3 ; } ) ) ; ` Global ( Reference . create " test . Z " , dependency , Some ( UnannotatedGlobal . TupleAssign { value = tuple_expression ; index = 2 ; target_location = Location . WithModule . any ; total_length = 3 ; } ) ) ; ] ~ expected_triggers [ : dependency ] ( ) ; assert_updates ~ original_source { :| X = int X = str } | ~ new_source { :| X = int X = str } | ~ middle_actions : [ ` Global ( Reference . create " test . X " , dependency , Some ( UnannotatedGlobal . SimpleAssign { explicit_annotation = None ; value = { ( parse_single_expression " int " ) with location = location ( 2 , 4 ) ( 2 , 7 ) } ; target_location = Location . WithModule . any ; } ) ) ; ] ~ expected_triggers [ ] : ( ) ; assert_updates ~ original_source { :| if condition : X = int else : X = str } | ~ new_source { :| if condition : X = int else : X = str } | ~ middle_actions : [ ` Global ( Reference . create " test . X " , dependency , Some ( UnannotatedGlobal . SimpleAssign { explicit_annotation = None ; value = { ( parse_single_expression " int " ) with location = location ( 3 , 6 ) ( 3 , 9 ) } ; target_location = Location . WithModule . any ; } ) ) ; ] ~ expected_triggers [ ] : ( ) ; let create_simple_signature ~ start ( : start_line , start_column ) ~ stop ( : stop_line , stop_column ) name return_annotation = { UnannotatedGlobal . UnannotatedDefine . define = { Define . Signature . name ; parameters = [ ] ; decorators = [ ] ; return_annotation ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; location = { Location . WithModule . start = { Location . line = start_line ; column = start_column } ; stop = { Location . line = stop_line ; column = stop_column } ; module_reference = Reference . create " test " ; } ; } in assert_updates ~ original_source { :| def foo ( ) -> None : print ( " hellobo " ) } | ~ new_source { :| def foo ( ) -> None : print ( " goodbye " ) } | ~ middle_actions : [ ` Global ( Reference . create " test . foo " , dependency , Some ( UnannotatedGlobal . Define [ create_simple_signature ~ start ( : 2 , 0 ) ~ stop ( : 3 , 17 ) " !& test . foo " ( Some ( node ~ start ( : 2 , 13 ) ~ stop ( : 2 , 17 ) ( Expression . Constant Constant . NoneLiteral ) ) ) ; ] ) ) ; ] ~ expected_triggers [ ] : ~ post_actions : [ ` Global ( Reference . create " test . foo " , dependency , Some ( UnannotatedGlobal . Define [ create_simple_signature ~ start ( : 2 , 0 ) ~ stop ( : 3 , 17 ) " !& test . foo " ( Some ( node ~ start ( : 2 , 13 ) ~ stop ( : 2 , 17 ) ( Expression . Constant Constant . NoneLiteral ) ) ) ; ] ) ) ; ] ( ) ; ( ) |
let test_dependencies_and_new_values context = let assert_updates = assert_updates ~ context in assert_updates ~ original_source { :| class Foo : x : int } | ~ new_source { :| class Foo : 2376 x : str } | ~ middle_actions : [ ` Get ( " test . Foo " , alias_dependency , Some 1 ) ; ` Get ( " test . Foo " , type_check_dependency , Some 1 ) ; ] ~ expected_triggers [ : alias_dependency ; type_check_dependency ] ( ) ; assert_updates ~ original_source { :| } | ~ new_source { :| x : int = 9 } | ~ middle_actions [ ` : Global ( Reference . create " test . x " , alias_dependency , None ) ] ~ expected_triggers [ : alias_dependency ] ~ post_actions : [ ` Global ( Reference . create " test . x " , alias_dependency , Some ( UnannotatedGlobal . SimpleAssign { explicit_annotation = Some { ( parse_single_expression " int " ) with location = location ( 2 , 3 ) ( 2 , 6 ) } ; value = { ( parse_single_expression " 9 " ) with location = location ( 2 , 9 ) ( 2 , 10 ) } ; target_location = Location . WithModule . any ; } ) ) ; ] ( ) ; ( ) |
let test_get_define_body context = let assert_updates = assert_updates ~ context in let dependency = type_check_dependency in let open Statement in let open Expression in let create_simple_return ~ start ~ stop expression = node ~ start ~ stop ( Statement . Return { Return . is_implicit = false ; expression = Some expression } ) in let create_simple_define ~ start ~ stop name body = node ~ start ~ stop { Define . signature = { Define . Signature . name ; parameters = [ ] ; decorators = [ ] ; return_annotation = None ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body ; } in assert_updates ~ original_source { :| def foo ( ) : return 1 } | ~ new_source { :| def foo ( ) : return 1 } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ ] : ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source { :| def foo ( ) : return 1 } | ~ new_source { :| def foo ( ) : return 2 } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 2 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source { :| def foo ( ) : return 1 } | ~ new_source { :| def foo ( ) : return 2 def foo ( ) : return 3 } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 4 , 0 ) ~ stop ( : 5 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 5 , 2 ) ~ stop ( : 5 , 10 ) ( node ~ start ( : 5 , 9 ) ~ stop ( : 5 , 10 ) ( Expression . Constant ( Constant . Integer 3 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source { :| def foo ( ) : return 1 def foo ( ) : return 2 } | ~ new_source { :| def foo ( ) : return 3 } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 4 , 0 ) ~ stop ( : 5 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 5 , 2 ) ~ stop ( : 5 , 10 ) ( node ~ start ( : 5 , 9 ) ~ stop ( : 5 , 10 ) ( Expression . Constant ( Constant . Integer 2 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 3 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source : { | from typing import overload @ overload def foo ( x : int ) -> int : . . . @ overload def foo ( x : str ) -> str : . . . def foo ( x ) : return x } | ~ new_source : { | from typing import overload @ overload def foo ( x : str ) -> str : . . . def foo ( x ) : return x @ overload def foo ( x : int ) -> int : . . . } | ~ middle_actions : [ ( let body = node ~ start ( : 7 , 0 ) ~ stop ( : 8 , 10 ) { Define . signature = { Define . Signature . name = " !& test . foo " ; parameters = [ node ~ start ( : 7 , 8 ) ~ stop ( : 7 , 9 ) { Parameter . name = " $ parameter $ x " ; value = None ; annotation = None } ; ] ; decorators = [ ] ; return_annotation = None ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ create_simple_return ~ start ( : 8 , 2 ) ~ stop ( : 8 , 10 ) ( node ~ start ( : 8 , 9 ) ~ stop ( : 8 , 10 ) ( Expression . Name ( Name . Identifier " $ parameter $ x " ) ) ) ; ] ; } in ` DefineBody ( " !& test . foo " , dependency , Some body ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ( let body = node ~ start ( : 5 , 0 ) ~ stop ( : 6 , 10 ) { Define . signature = { Define . Signature . name = " !& test . foo " ; parameters = [ node ~ start ( : 5 , 8 ) ~ stop ( : 5 , 9 ) { Parameter . name = " $ parameter $ x " ; value = None ; annotation = None } ; ] ; decorators = [ ] ; return_annotation = None ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ create_simple_return ~ start ( : 6 , 2 ) ~ stop ( : 6 , 10 ) ( node ~ start ( : 6 , 9 ) ~ stop ( : 6 , 10 ) ( Expression . Name ( Name . Identifier " $ parameter $ x " ) ) ) ; ] ; } in ` DefineBody ( " !& test . foo " , dependency , Some body ) ) ; ] ( ) ; let ( ) = let body = node ~ start ( : 5 , 0 ) ~ stop ( : 6 , 10 ) { Define . signature = { Define . Signature . name = " !& test . foo " ; parameters = [ node ~ start ( : 5 , 8 ) ~ stop ( : 5 , 9 ) { Parameter . name = " $ parameter $ x " ; value = None ; annotation = None } ; ] ; decorators = [ ] ; return_annotation = None ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ create_simple_return ~ start ( : 6 , 2 ) ~ stop ( : 6 , 10 ) ( node ~ start ( : 6 , 9 ) ~ stop ( : 6 , 10 ) ( Expression . Name ( Name . Identifier " $ parameter $ x " ) ) ) ; ] ; } in let first_overload = node ~ start ( : 4 , 0 ) ~ stop ( : 4 , 27 ) { Define . signature = { Define . Signature . name = " !& test . foo " ; parameters = [ node ~ start ( : 4 , 8 ) ~ stop ( : 4 , 14 ) { Parameter . name = " $ parameter $ x " ; value = None ; annotation = Some ( node ~ start ( : 4 , 11 ) ~ stop ( : 4 , 14 ) ( Expression . Name ( Name . Identifier " int " ) ) ) ; } ; ] ; decorators = [ node ~ start ( : 3 , 1 ) ~ stop ( : 3 , 9 ) ( Expression . Name ( Name . Attribute { Name . Attribute . base = node ~ start ( : 3 , 1 ) ~ stop ( : 3 , 9 ) ( Expression . Name ( Name . Identifier " typing " ) ) ; attribute = " overload " ; special = false ; } ) ) ; ] ; return_annotation = Some ( node ~ start ( : 4 , 19 ) ~ stop ( : 4 , 22 ) ( Expression . Name ( Name . Identifier " int " ) ) ) ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ node ~ start ( : 4 , 24 ) ~ stop ( : 4 , 27 ) ( Statement . Expression ( node ~ start ( : 4 , 24 ) ~ stop ( : 4 , 27 ) ( Expression . Constant Constant . Ellipsis ) ) ) ; ] ; } in let second_overload = node ~ start ( : 8 , 0 ) ~ stop ( : 8 , 27 ) { Define . signature = { Define . Signature . name = " !& test . foo " ; parameters = [ node ~ start ( : 8 , 8 ) ~ stop ( : 8 , 14 ) { Parameter . name = " $ parameter $ x " ; value = None ; annotation = Some ( node ~ start ( : 8 , 11 ) ~ stop ( : 8 , 14 ) ( Expression . Name ( Name . Identifier " str " ) ) ) ; } ; ] ; decorators = [ node ~ start ( : 7 , 1 ) ~ stop ( : 7 , 9 ) ( Expression . Name ( Name . Attribute { Name . Attribute . base = node ~ start ( : 7 , 1 ) ~ stop ( : 7 , 9 ) ( Expression . Name ( Name . Identifier " typing " ) ) ; attribute = " overload " ; special = false ; } ) ) ; ] ; return_annotation = Some ( node ~ start ( : 8 , 19 ) ~ stop ( : 8 , 22 ) ( Expression . Name ( Name . Identifier " str " ) ) ) ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ node ~ start ( : 8 , 24 ) ~ stop ( : 8 , 27 ) ( Statement . Expression ( node ~ start ( : 8 , 24 ) ~ stop ( : 8 , 27 ) ( Expression . Constant Constant . Ellipsis ) ) ) ; ] ; } in assert_updates ~ original_source : { | from typing import overload @ overload def foo ( x : int ) -> int : . . . def foo ( x ) : return x } | ~ new_source : { | from typing import overload @ overload def foo ( x : int ) -> int : . . . def foo ( x ) : return x @ overload def foo ( x : str ) -> str : . . . } | ~ middle_actions : [ ( let definition = let open FunctionDefinition in let siblings = [ { Sibling . kind = Sibling . Kind . Overload ; body = first_overload } ] in { body = Some body ; siblings ; qualifier = " !& test " } in ` Define ( " !& test . foo " , dependency , Some definition ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ( let definition = let open FunctionDefinition in let siblings = [ { Sibling . kind = Sibling . Kind . Overload ; body = first_overload } ; { Sibling . kind = Sibling . Kind . Overload ; body = second_overload } ; ] in { body = Some body ; siblings ; qualifier = " !& test " } in ` Define ( " !& test . foo " , dependency , Some definition ) ) ; ] ( ) in assert_updates ~ original_source { :| class A : foo : int } | ~ new_source : { | class A : @ property def foo ( self ) -> int : . . . @ foo . setter def foo ( self , value : int ) -> None : . . . } | ~ middle_actions [ ` : Define ( " !& test . A . foo " , dependency , None ) ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ( let definition = let open FunctionDefinition in let create_elipsis ~ start ~ stop ( ) = node ~ start ~ stop ( Statement . Expression ( node ~ start ~ stop ( Expression . Constant Constant . Ellipsis ) ) ) in let body = node ~ start ( : 4 , 2 ) ~ stop ( : 4 , 27 ) { Define . signature = { Define . Signature . name = " !& test . A . foo " ; parameters = [ node ~ start ( : 4 , 10 ) ~ stop ( : 4 , 14 ) { Parameter . name = " $ parameter $ self " ; value = None ; annotation = None } ; ] ; decorators = [ node ~ start ( : 3 , 3 ) ~ stop ( : 3 , 11 ) ( Expression . Name ( Name . Identifier " property " ) ) ; ] ; return_annotation = Some ( node ~ start ( : 4 , 19 ) ~ stop ( : 4 , 22 ) ( Expression . Name ( Name . Identifier " int " ) ) ) ; async = false ; generator = false ; parent = Some " !& test . A " ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ create_elipsis ~ start ( : 4 , 24 ) ~ stop ( : 4 , 27 ) ( ) ] ; } in let siblings = [ ( let body = node ~ start ( : 6 , 2 ) ~ stop ( : 6 , 40 ) { Define . signature = { Define . Signature . name = " !& test . A . foo " ; parameters = [ node ~ start ( : 6 , 10 ) ~ stop ( : 6 , 14 ) { Parameter . name = " $ parameter $ self " ; value = None ; annotation = None ; } ; node ~ start ( : 6 , 16 ) ~ stop ( : 6 , 26 ) { Parameter . name = " $ parameter $ value " ; value = None ; annotation = Some ( node ~ start ( : 6 , 23 ) ~ stop ( : 6 , 26 ) ( Expression . Name ( Name . Identifier " int " ) ) ) ; } ; ] ; decorators = [ node ~ start ( : 5 , 3 ) ~ stop ( : 5 , 13 ) ( Expression . Name ( Name . Attribute { Name . Attribute . base = node ~ start ( : 5 , 3 ) ~ stop ( : 5 , 6 ) ( Expression . Name ( Name . Identifier " foo " ) ) ; attribute = " setter " ; special = false ; } ) ) ; ] ; return_annotation = Some ( node ~ start ( : 6 , 31 ) ~ stop ( : 6 , 35 ) ( Expression . Constant Constant . NoneLiteral ) ) ; async = false ; generator = false ; parent = Some " !& test . A " ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ create_elipsis ~ start ( : 6 , 37 ) ~ stop ( : 6 , 40 ) ( ) ] ; } in { Sibling . kind = Sibling . Kind . PropertySetter ; body } ) ; ] in { body = Some body ; siblings ; qualifier = " !& test " } in ` Define ( " !& test . A . foo " , dependency , Some definition ) ) ; ] ( ) ; assert_updates ~ original_source { :| def foo ( ) : return 1 } | ~ new_source : { | # The truth is , the game was rigged from the start . def foo ( ) : return 1 } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 3 , 0 ) ~ stop ( : 4 , 12 ) " !& test . foo " [ create_simple_return ~ start ( : 4 , 4 ) ~ stop ( : 4 , 12 ) ( node ~ start ( : 4 , 11 ) ~ stop ( : 4 , 12 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source { :| } | ~ new_source { :| def foo ( ) : return 2 } | ~ middle_actions [ ` : DefineBody ( " !& test . foo " , dependency , None ) ] ~ expected_triggers [ : dependency ] ~ post_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 2 ) ) ) ; ] ) ) ; ] ( ) ; assert_updates ~ original_source { :| def foo ( ) : return 1 } | ~ new_source { :| } | ~ middle_actions : [ ` DefineBody ( " !& test . foo " , dependency , Some ( create_simple_define ~ start ( : 2 , 0 ) ~ stop ( : 3 , 10 ) " !& test . foo " [ create_simple_return ~ start ( : 3 , 2 ) ~ stop ( : 3 , 10 ) ( node ~ start ( : 3 , 9 ) ~ stop ( : 3 , 10 ) ( Expression . Constant ( Constant . Integer 1 ) ) ) ; ] ) ) ; ] ~ expected_triggers [ : dependency ] ~ post_actions [ ` : DefineBody ( " !& test . foo " , dependency , None ) ] ( ) ; ( ) |
let ( ) = " environment " >::: [ " global_registration " >:: test_global_registration ; " define_registration " >:: test_define_registration ; " simple_globals " >:: test_simple_global_registration ; " builtins " >:: test_builtin_modules ; " resolve_exports " >:: test_resolve_exports ; " get_class_summary " >:: test_get_class_summary ; " class_exists_and_all_classes " >:: test_class_exists_and_all_classes ; " get_unannotated_global " >:: test_get_unannotated_global ; " dependencies_and_new_values " >:: test_dependencies_and_new_values ; " get_define_body " >:: test_get_define_body ; ] |> Test . run |
let test_collection context = let assert_collected_names ~ expected source_text = let source = parse ~ handle " : test . py " source_text in let actual = Collector . from_source source |> List . map ~ f ( : fun { Collector . Result . name ; _ } -> name ) in assert_equal ~ ctxt : context ~ cmp [ :% compare . equal : string list ] ~ printer ( : String . concat ~ sep " , : " ) expected actual in assert_collected_names { | x = 1 y = 2 z = 3 } | ~ expected [ " : x " ; " y " ; " z " ] ; assert_collected_names { | x , y = 1 , 2 z [ 3 ] = 4 u , ( v , w ) = derp } | ~ expected [ " : x " ; " y " ] ; assert_collected_names { | def foo ( ) : pass def bar ( ) : pass def foo ( ) : pass } | ~ expected [ " : foo " ; " bar " ; " foo " ] ; assert_collected_names { | class Foo : pass class Bar : class Nested : pass class Baz : def foo ( self ) : . . . } | ~ expected [ " : Foo " ; " Bar " ; " Baz " ] ; assert_collected_names { | import x import y as z from u . v import w from a . b import c as d } | ~ expected [ " : x " ; " z " ; " w " ; " d " ] ; assert_collected_names { | if derp ( ) : x = 1 z = 2 else : x = 3 y = 4 } | ~ expected [ " : x " ; " z " ; " x " ; " y " ] ; assert_collected_names { | try : x = 1 z = 2 except : y = 3 } | ~ expected [ " : x " ; " z " ; " y " ] ; assert_collected_names { | with derp ( ) : x = 1 import y } | ~ expected [ " : x " ; " y " ] ; ( ) |
let test_import context = let assert_imports ~ expected source_text = let source = parse ~ handle " : test . py " source_text in let actual = Collector . from_source source |> List . filter_map ~ f ( : function | { Collector . Result . name ; unannotated_global = Imported import } -> Some ( name , import ) | _ -> None ) in assert_equal ~ ctxt : context ~ cmp [ :% compare . equal : ( Identifier . t * ImportEntry . t ) list ] ~ printer ( : fun result -> Sexp . to_string_hum [ % message ( result : ( Identifier . t * ImportEntry . t ) list ) ] ) expected actual in assert_imports " import foo " ~ expected [ " : foo " , ImportEntry . Module { target = " !& foo " ; implicit_alias = true } ] ; assert_imports " import foo as bar " ~ expected [ " : bar " , ImportEntry . Module { target = " !& foo " ; implicit_alias = false } ] ; assert_imports " import foo . bar " ~ expected [ " : foo " , ImportEntry . Module { target = " !& foo . bar " ; implicit_alias = true } ] ; assert_imports " import foo . bar as baz " ~ expected [ " : baz " , ImportEntry . Module { target = " !& foo . bar " ; implicit_alias = false } ] ; assert_imports " from foo import bar " ~ expected [ " : bar " , ImportEntry . Name { from = " !& foo " ; target = " bar " ; implicit_alias = true } ] ; assert_imports " from foo import bar as baz " ~ expected [ " : baz " , ImportEntry . Name { from = " !& foo " ; target = " bar " ; implicit_alias = false } ] ; assert_imports " from foo . bar import baz as qux " ~ expected : [ " qux " , ImportEntry . Name { from = " !& foo . bar " ; target = " baz " ; implicit_alias = false } ] ; assert_imports " import a as b , c . d " ~ expected : [ " b " , ImportEntry . Module { target = " !& a " ; implicit_alias = false } ; " c " , ImportEntry . Module { target = " !& c . d " ; implicit_alias = true } ; ] ; assert_imports " from a . b import c as d , e " ~ expected : [ " d " , ImportEntry . Name { from = " !& a . b " ; target = " c " ; implicit_alias = false } ; " e " , ImportEntry . Name { from = " !& a . b " ; target = " e " ; implicit_alias = true } ; ] ; assert_imports " from foo import " * ~ expected [ ] ; : ( ) |
let ( ) = " node " >::: [ " collection " >:: test_collection ; " import " >:: test_import ] |> Test . run |
type loc = FanLoc . t ; type ant = [ ` Ant of ( loc * FanUtil . anti_cxt ) ] ; type nil = [ ` Nil of loc ] ; type ant_nil = [ ant | nil ] ; type literal = [ ` Chr of ( loc * string ) | ` Int of ( loc * string ) | ` Int32 of ( loc * string ) | ` Int64 of ( loc * string ) | ` Flo of ( loc * string ) | ` Nativeint of ( loc * string ) | ` Str of ( loc * string ) ] ; type rec_flag = [ ` Recursive of loc | ` ReNil of loc | ant ] ; type direction_flag = [ ` To of loc | ` Downto of loc | ant ] ; type mutable_flag = [ ` Mutable of loc | ` MuNil of loc | ant ] ; type private_flag = [ ` Private of loc | ` PrNil of loc | ant ] ; type virtual_flag = [ ` Virtual of loc | ` ViNil of loc | ant ] ; type override_flag = [ ` Override of loc | ` OvNil of loc | ant ] ; type row_var_flag = [ ` RowVar of loc | ` RvNil of loc | ant ] ; type position_flag = [ ` Positive of loc | ` Negative of loc | ` Normal of loc | ant ] ; type meta_bool = [ ` True of loc ` | False of loc | ant ] ; type ' a meta_option = [ ` None | ` Some of ' a | ant ] ; type ' a meta_list = [ ` LNil | ` LCons of ( ' a * ' a meta_list ) | ant ] ; type alident = [ ` Lid of ( loc * string ) | ant ] ; type auident = [ ` Uid of ( loc * string ) | ant ] ; type aident = [ alident | auident ] ; type astring = [ ` C of ( loc * string ) | ant ] ; type uident = [ ` Dot of ( loc * uident * uident ) | ` App of ( loc * uident * uident ) | auident ] ; type ident = [ ` Dot of ( loc * ident * ident ) | ` App of ( loc * ident * ident ) | alident | auident ] ; type dupath = [ ` Dot of ( loc * dupath * dupath ) | auident ] ; type dlpath = [ ` Dot of ( loc * dupath * alident ) | alident ] ; type sid = [ ` Id of ( loc * ident ) ] ; type any = [ ` Any of loc ] ; |
type pat = [ nil | sid | ` App of ( loc * pat * pat ) | ` Vrn of ( loc * string ) | ` Com of ( loc * pat * pat ) | ` Sem of ( loc * pat * pat ) | ` Par of ( loc * pat ) | any | ` Record of ( loc * rec_pat ) | ant | literal | ` Alias of ( loc * pat * alident ) | ` Array of ( loc * pat ) | ` Label of ( loc * alident * pat ) | ` PaOlbi of ( loc * alident * pat * meta_option exp ) | ` Bar of ( loc * pat * pat ) | ` PaRng of ( loc * pat * pat ) | ` Constraint of ( loc * pat * ctyp ) | ` ClassPath of ( loc * ident ) | ` Lazy of ( loc * pat ) | ` ModuleUnpack of ( loc * auident * meta_option ctyp ) ] [ nil | ` RecBind of ( loc * ident * pat ) | ` Sem of ( loc * rec_pat * rec_pat ) | any | ant ] ; |
let to_http service region req = let uri = Uri . add_query_params ( Uri . of_string ( Aws . Util . of_option_exn ( Endpoints . url_of service region ) ) ) ( List . append [ ( " Version " , [ " 2016 - 11 - 15 " ] ) ; ( " Action " , [ " UnassignIpv6Addresses " ] ) ] ( Util . drop_empty ( Uri . query_of_encoded ( Query . render ( UnassignIpv6AddressesRequest . to_query req ) ) ) ) ) in ( ` POST , uri , [ ] ) |
let of_http body = try let xml = Ezxmlm . from_string body in let resp = Xml . member " UnassignIpv6AddressesResponse " ( snd xml ) in try Util . or_error ( Util . option_bind resp UnassignIpv6AddressesResult . parse ) ( let open Error in BadResponse { body ; message = " Could not find well formed UnassignIpv6AddressesResult . " } ) with | Xml . RequiredFieldMissing msg -> let open Error in ` Error ( BadResponse { body ; message = ( " Error parsing UnassignIpv6AddressesResult - missing field in body or children : " ^ msg ) } ) with | Failure msg -> ` Error ( let open Error in BadResponse { body ; message = ( " Error parsing xml : " ^ msg ) } ) |
let parse_error code err = let errors = [ ] @ Errors_internal . common in match Errors_internal . of_string err with | Some var -> if ( List . mem var errors ) && ( ( match Errors_internal . to_http_code var with | Some var -> var = code | None -> true ) ) then Some var else None | None -> None |
type synonym = ' a -> ' a [ %% expect { | ^^ } ] | |
type record = { contents : ' a } [ %% expect { | ^^ } ] | |
type wrapper = Wrapper of ' a [ %% expect { | ^^ } ] | |
type polyvariant = [ > ` C ] [ %% expect { | ^^^^^^^^^^^^^^^^^^^^^^^^^ In type [ > ` C ] as ' a the variable ' a is unbound } ] | |
type ' a only_one = ' a * ' b [ %% expect { | ^^ } ] | |
type extensible += Extension of ' a [ %% expect { | |
type extensible = . . ^^ } ] | |
type r = R of r list [ @@ unboxed ] |
let rec a = R [ a ] ; ; [ %% expect { | |
type r = R of r list [ @@ unboxed ] } ] ; ; | |
type t = { x : int64 } [ @@ unboxed ] |
let rec x = { x = y } and y = 3L ; ; [ %% expect { | |
type t = { x : int64 ; } [ @@ unboxed ] ^^^^^^^ } ] ; ; | |
type r = A of r [ @@ unboxed ] |
let rec y = A y ; ; [ %% expect { | |
type r = A of r [ @@ unboxed ] ^^^ } ] ; ; | |
type a = { a : b } |
let rec a = { a = ( if Sys . opaque_identity true then X a else Y ) } ; ; [ %% expect { | |
type a = { a : b ; } } ] ; ; | |
type a = { a : b } [ @@ unboxed ] |
let rec a = { a = ( if Sys . opaque_identity true then X a else Y ) } ; ; [ %% expect { | |
type a = { a : b ; } [ @@ unboxed ] } ] ; ; | |
type d = D of e [ %% expect { | |
type d = D of e } ] ; ; | |
let rec d = D ( if Sys . opaque_identity true then V d else W ) ; ; [ %% expect { | } ] ; ; | |
type d = D of e [ @@ unboxed ] |
let rec d = D ( if Sys . opaque_identity true then V d else W ) ; ; [ %% expect { | |
type d = D of e [ @@ unboxed ] } ] ; ; | |
module Transform = struct let pass_name = " unbox - closures " let precondition ~ env ( ~ set_of_closures : Flambda . set_of_closures ) = ! Clflags . unbox_closures && not ( E . at_toplevel env ) && not ( Variable . Map . is_empty set_of_closures . free_vars ) let what_to_specialise ~ env ( ~ set_of_closures : Flambda . set_of_closures ) = let what_to_specialise = W . create ~ set_of_closures in if not ( precondition ~ env ~ set_of_closures ) then what_to_specialise else begin let round = E . round env in let num_closure_vars = Variable . Map . cardinal set_of_closures . free_vars in let module B = Inlining_cost . Benefit in let saved_by_not_building_closure = B . remove_prims ( B . remove_call B . zero ) num_closure_vars in Flambda_iterators . fold_function_decls_ignoring_stubs set_of_closures ~ init : what_to_specialise ~ f ( : fun ~ fun_var ( ~ function_decl : Flambda . function_declaration ) what_to_specialise -> let body_size = Inlining_cost . lambda_size function_decl . body in let small_enough_to_duplicate = let module W = Inlining_cost . Whether_sufficient_benefit in let wsb = W . create_estimate ~ original_size : 0 ~ toplevel : false ~ branch_depth : 0 ~ new_size ( ( : body_size / ! Clflags . unbox_closures_factor ) + 1 ) ~ benefit : saved_by_not_building_closure ~ lifting : false ~ round in W . evaluate wsb in let what_to_specialise = if small_enough_to_duplicate then W . make_direct_call_surrogate_for what_to_specialise ~ fun_var else what_to_specialise in let bound_by_the_closure = Flambda_utils . variables_bound_by_the_closure ( Closure_id . wrap fun_var ) set_of_closures . function_decls in Variable . Set . fold ( fun inner_free_var what_to_specialise -> W . new_specialised_arg what_to_specialise ~ fun_var ~ group : inner_free_var ~ definition ( : Existing_inner_free_var inner_free_var ) ) bound_by_the_closure what_to_specialise ) end end |
let ( ) = Pass_wrapper . register ~ pass_name |
let add_lifted_projections_around_set_of_closures ~ set_of_closures ~ existing_inner_to_outer_vars ~ benefit ~ definitions_indexed_by_new_inner_vars = let body = Flambda_utils . name_expr ( Set_of_closures set_of_closures ) ~ name : Internal_variable_names . unbox_free_vars_of_closures in Variable . Map . fold ( fun new_inner_var ( projection : Projection . t ) ( expr , benefit ) -> let find_outer_var inner_var = match Variable . Map . find inner_var existing_inner_to_outer_vars with | ( outer_var : Flambda . specialised_to ) -> outer_var . var | exception Not_found -> Misc . fatal_errorf " ( UFV ) find_outer_var : expected % a \ to be in [ existing_inner_to_outer_vars ] , but it is \ not . ( The projection was : % a ) " Variable . print inner_var Projection . print projection in let benefit = B . add_projection projection benefit in let named : Flambda . named = let projection = Projection . map_projecting_from projection ~ f : find_outer_var in Flambda_utils . projection_to_named projection in let expr = Flambda . create_let ( find_outer_var new_inner_var ) named expr in ( expr , benefit ) ) definitions_indexed_by_new_inner_vars ( body , benefit ) |
let run ~ env ( ~ set_of_closures : Flambda . set_of_closures ) = if not ! Clflags . unbox_free_vars_of_closures then None else let definitions_indexed_by_new_inner_vars , _ , free_vars , done_something = let all_existing_definitions = Variable . Map . fold ( fun _inner_var ( outer_var : Flambda . specialised_to ) all_existing_definitions -> match outer_var . projection with | None -> all_existing_definitions | Some projection -> Projection . Set . add projection all_existing_definitions ) set_of_closures . free_vars Projection . Set . empty in Flambda_iterators . fold_function_decls_ignoring_stubs set_of_closures ~ init ( : Variable . Map . empty , all_existing_definitions , set_of_closures . free_vars , false ) ~ f ( : fun ~ fun_var : _ ~ function_decl result -> let extracted = Extract_projections . from_function_decl ~ env ~ function_decl ~ which_variables : set_of_closures . free_vars in Projection . Set . fold ( fun projection ( ( definitions_indexed_by_new_inner_vars , all_existing_definitions_including_added_ones , additional_free_vars , _done_something ) as result ) -> if Projection . Set . mem projection all_existing_definitions_including_added_ones then begin result end else begin let projecting_from = Projection . projecting_from projection in let new_inner_var = Variable . rename projecting_from in let new_outer_var = Variable . rename projecting_from in let definitions_indexed_by_new_inner_vars = Variable . Map . add new_inner_var projection definitions_indexed_by_new_inner_vars in let all_existing_definitions_including_added_ones = Projection . Set . add projection all_existing_definitions_including_added_ones in let new_outer_var : Flambda . specialised_to = { var = new_outer_var ; projection = Some projection ; } in let additional_free_vars = Variable . Map . add new_inner_var new_outer_var additional_free_vars in definitions_indexed_by_new_inner_vars , all_existing_definitions_including_added_ones , additional_free_vars , true end ) extracted result ) in if not done_something then None else let num_free_vars_before = Variable . Map . cardinal set_of_closures . free_vars in let num_free_vars_after = Variable . Map . cardinal free_vars in assert ( num_free_vars_after > num_free_vars_before ) ; if num_free_vars_after > 2 * num_free_vars_before then None else let set_of_closures = Flambda . create_set_of_closures ~ function_decls : set_of_closures . function_decls ~ free_vars ~ specialised_args : set_of_closures . specialised_args ~ direct_call_surrogates : set_of_closures . direct_call_surrogates in let expr , benefit = add_lifted_projections_around_set_of_closures ~ set_of_closures ~ benefit : B . zero ~ existing_inner_to_outer_vars : set_of_closures . free_vars ~ definitions_indexed_by_new_inner_vars in Some ( expr , benefit ) |
let run ~ env ~ set_of_closures = Pass_wrapper . with_dump ~ ppf_dump ( : Inline_and_simplify_aux . Env . ppf_dump env ) ~ pass_name ~ input : set_of_closures ~ print_input : Flambda . print_set_of_closures ~ print_output ( : fun ppf ( expr , _ ) -> Flambda . print ppf expr ) ~ f ( : fun ( ) -> run ~ env ~ set_of_closures ) |
module Transform = struct let pass_name = " unbox - specialised - args " let precondition ~ env : _ ( ~ set_of_closures : Flambda . set_of_closures ) = ! Clflags . unbox_specialised_args && not ( Variable . Map . is_empty set_of_closures . specialised_args ) let what_to_specialise ~ env ( ~ set_of_closures : Flambda . set_of_closures ) = let what_to_specialise = W . create ~ set_of_closures in if not ( precondition ~ env ~ set_of_closures ) then what_to_specialise else let projections_by_function = Variable . Map . filter_map set_of_closures . function_decls . funs ~ f ( : fun _fun_var ( function_decl : Flambda . function_declaration ) -> if function_decl . stub then None else Some ( Extract_projections . from_function_decl ~ env ~ function_decl ~ which_variables : set_of_closures . specialised_args ) ) in let invariant_params_flow = Invariant_params . invariant_param_sources set_of_closures . function_decls ~ backend ( : Inline_and_simplify_aux . Env . backend env ) in Variable . Map . fold ( fun fun_var extractions what_to_specialise -> Projection . Set . fold ( fun ( projection : Projection . t ) what_to_specialise -> let group = Projection . projecting_from projection in assert ( Variable . Map . mem group set_of_closures . specialised_args ) ; let what_to_specialise = W . new_specialised_arg what_to_specialise ~ fun_var ~ group ~ definition ( : Projection_from_existing_specialised_arg projection ) in match Variable . Map . find group invariant_params_flow with | exception Not_found -> what_to_specialise | flow -> Variable . Pair . Set . fold ( fun ( target_fun_var , target_spec_arg ) what_to_specialise -> if Variable . equal fun_var target_fun_var || not ( Variable . Map . mem target_spec_arg set_of_closures . specialised_args ) then begin what_to_specialise end else begin let projection = Projection . map_projecting_from projection ~ f ( : fun var -> assert ( Variable . equal var group ) ; target_spec_arg ) in W . new_specialised_arg what_to_specialise ~ fun_var : target_fun_var ~ group ~ definition : ( Projection_from_existing_specialised_arg projection ) end ) flow what_to_specialise ) extractions what_to_specialise ) projections_by_function what_to_specialise end |
module Float = struct type _ t = | IO : int option t | F : float t let bar : type a . a t -> float -> int -> a = fun t f i -> match t with | IO -> Some i | F -> f [ @@ inline always ] let foo ( t : float t ) f i = let r = ref 0 . in r := bar t f i end |
module Int32 = struct type _ t = | IO : int option t | F : int32 t let bar : type a . a t -> int32 -> int -> a = fun t f i -> match t with | IO -> Some i | F -> f [ @@ inline always ] let foo ( t : int32 t ) f i = let r = ref 0l in r := bar t f i end |
module Int64 = struct type _ t = | IO : int option t | F : int64 t let bar : type a . a t -> int64 -> int -> a = fun t f i -> match t with | IO -> Some i | F -> f [ @@ inline always ] let foo ( t : int64 t ) f i = let r = ref 0L in r := bar t f i end |
module Nativeint = struct type _ t = | IO : int option t | F : nativeint t let bar : type a . a t -> nativeint -> int -> a = fun t f i -> match t with | IO -> Some i | F -> f [ @@ inline always ] let foo ( t : nativeint t ) f i = let r = ref 0n in r := bar t f i end |
let kasprintf k fmt = Format . ( kfprintf ( fun _ -> k ( flush_str_formatter ( ) ) ) str_formatter fmt ) |
let invalid_arg fmt = kasprintf invalid_arg ( " Nocrypto : " ^^ fmt ) |
let failwith fmt = kasprintf failwith ( " Nocrypto : " ^^ fmt ) |
let ( ) // x y = if y < 1 then raise Division_by_zero else if x > 0 then 1 + ( ( x - 1 ) / y ) else 0 [ @@ inline ] |
let imin ( a : int ) b = if a < b then a else b |
let imax ( a : int ) b = if a < b then b else a |
let ( . ) & f g = fun h -> f ( g h ) |
let id x = x |
let rec until p f = let r = f ( ) in if p r then r else until p f |
module Option = struct let get_or f x = function None -> f x | Some y -> y let ( ) >>= a fb = match a with Some x -> fb x | _ -> None let ( ) >>| a f = match a with Some x -> Some ( f x ) | _ -> None let v_map ~ def ~ f = function | Some x -> f x | None -> def let get ~ def = function | Some x -> x | None -> def let map ~ f = function | Some x -> Some ( f x ) | None -> None let cond ~ f = function | Some x -> ignore ( f x ) | None -> ( ) end |
type ' a iter = ( ' a -> unit ) -> unit |
let iter1 a f = f a |
let iter2 a b f = f a ; f b |
let iter3 a b c f = f a ; f b ; f c |
let string_fold ~ f ~ z str = let st = ref z in ( String . iter ( fun c -> st := f ! st c ) str ; ! st ) |
module Z = struct include Z let two = ~$ 2 let three = ~$ 3 let pp = pp_print open Sexplib . Conv let sexp_of_t z = sexp_of_string ( Z . to_string z ) let t_of_sexp s = Z . of_string ( string_of_sexp s ) end |
module Cs = struct open Cstruct let empty = create 0 let null cs = len cs = 0 let ( ) <+> = append let ct_eq cs1 cs2 = let rec go ok i = function | n when n >= 8 -> go ( LE . ( get_uint64 cs1 i = get_uint64 cs2 i ) && ok ) ( i + 8 ) ( n - 8 ) | n when n >= 4 -> go ( LE . ( get_uint32 cs1 i = get_uint32 cs2 i ) && ok ) ( i + 4 ) ( n - 4 ) | n when n >= 2 -> go ( LE . ( get_uint16 cs1 i = get_uint16 cs2 i ) && ok ) ( i + 2 ) ( n - 2 ) | 1 -> ( get_uint8 cs1 i = get_uint8 cs2 i ) && ok | _ -> ok in let n1 = len cs1 and n2 = len cs2 in go true 0 ( imin n1 n2 ) && n1 = n2 let ct_find_uint8 ( ? off = 0 ) ~ f cs = let rec go acc i = function | 0 -> acc | n -> let acc = match ( acc , f ( get_uint8 cs i ) ) with | ( None , true ) -> Some i | _ -> acc in go acc ( succ i ) ( pred n ) in go None off ( len cs - off ) let clone ( ? off = 0 ) ? len cs = let len = match len with None -> cs . len - off | Some x -> x in let cs ' = create_unsafe len in ( blit cs off cs ' 0 len ; cs ' ) let xor_into src dst n = if n > imin ( len src ) ( len dst ) then invalid_arg " Uncommon . Cs . xor_into : buffers to small ( need % d ) " n else Native . xor_into src . buffer src . off dst . buffer dst . off n let xor cs1 cs2 = let len = imin ( len cs1 ) ( len cs2 ) in let cs = clone ~ len cs2 in ( xor_into cs1 cs len ; cs ) let create ( ? init = 0x00 ) n = let cs = create_unsafe n in ( memset cs init ; cs ) let is_prefix cs0 cs = cs0 . len <= cs . len && equal cs0 ( sub cs 0 cs0 . len ) let set_msb bits cs = if bits > 0 then let n = len cs in let rec go width = function | i when i = n -> ( ) | i when width < 8 -> set_uint8 cs i ( get_uint8 cs i lor ( 0xff lsl ( 8 - width ) ) ) | i -> set_uint8 cs i 0xff ; go ( width - 8 ) ( succ i ) in go bits 0 let split2 cs l = ( sub cs 0 l , sub cs l ( len cs - l ) ) let split3 cs l1 l2 = let l12 = l1 + l2 in ( sub cs 0 l1 , sub cs l1 l2 , sub cs l12 ( len cs - l12 ) ) let rpad cs size x = let l = len cs and cs ' = Cstruct . create_unsafe size in if size < l then invalid_arg " Uncommon . Cs . rpad : size < len " ; blit cs 0 cs ' 0 l ; memset ( sub cs ' l ( size - l ) ) x ; cs ' let lpad cs size x = let l = len cs and cs ' = Cstruct . create_unsafe size in if size < l then invalid_arg " Uncommon . Cs . lpad : size < len " ; blit cs 0 cs ' ( size - l ) l ; memset ( sub cs ' 0 ( size - l ) ) x ; cs ' let of_bytes , of_int32s , of_int64s = let aux k set xs = let cs = Cstruct . create_unsafe @@ List . length xs * k in List . iteri ( fun i x -> set cs ( i * k ) x ) xs ; cs in ( aux 1 set_uint8 , aux 4 BE . set_uint32 , aux 8 BE . set_uint64 ) let b x = let cs = Cstruct . create_unsafe 1 in ( set_uint8 cs 0 x ; cs ) let rec shift_left_inplace cs = function | 0 -> ( ) | bits when bits mod 8 = 0 -> let off = bits / 8 in blit cs off cs 0 ( cs . len - off ) ; memset ( shift cs ( cs . len - off ) ) 0x00 | bits when bits < 8 -> let foo = 8 - bits in for i = 0 to cs . len - 2 do let b1 = get_uint8 cs i and b2 = get_uint8 cs ( i + 1 ) in set_uint8 cs i ( ( b1 lsl bits ) lor ( b2 lsr foo ) ) done ; set_uint8 cs ( cs . len - 1 ) @@ get_uint8 cs ( cs . len - 1 ) lsl bits | bits -> shift_left_inplace cs ( 8 * ( bits / 8 ) ) ; shift_left_inplace cs ( bits mod 8 ) let rec shift_right_inplace cs = function | 0 -> ( ) | bits when bits mod 8 = 0 -> let off = bits / 8 in blit cs 0 cs off ( cs . len - off ) ; memset ( sub cs 0 off ) 0x00 | bits when bits < 8 -> let foo = 8 - bits in for i = cs . len - 1 downto 1 do let b1 = get_uint8 cs i and b2 = get_uint8 cs ( i - 1 ) in set_uint8 cs i ( ( b2 lsl foo ) lor ( b1 lsr bits ) ) done ; set_uint8 cs 0 @@ get_uint8 cs 0 lsr bits | bits -> shift_right_inplace cs ( 8 * ( bits / 8 ) ) ; shift_right_inplace cs ( bits mod 8 ) let of_hex str = let hexdigit = function | ' a ' . . ' f ' as x -> int_of_char x - 87 | ' A ' . . ' F ' as x -> int_of_char x - 55 | ' 0 ' . . ' 9 ' as x -> int_of_char x - 48 | x -> invalid_arg " of_hex : ` % c ' " x in let whitespace = function ' ' | ' \ t ' | ' \ r ' | ' \ n ' -> true | _ -> false in match string_fold ~ f ( : fun ( cs , i , acc ) -> function | char when whitespace char -> ( cs , i , acc ) | char -> match ( acc , hexdigit char ) with | ( None , x ) -> ( cs , i , Some ( x lsl 4 ) ) | ( Some y , x ) -> set_uint8 cs i ( x lor y ) ; ( cs , succ i , None ) ) ~ z ( : create_unsafe ( String . length str ) , 0 , None ) str with | ( _ , _ , Some _ ) -> invalid_arg " of_hex : dangling nibble " | ( cs , i , _ ) -> sub cs 0 i let ( lsl ) cs bits = let cs ' = clone cs in shift_left_inplace cs ' bits ; cs ' and ( lsr ) cs bits = let cs ' = clone cs in shift_right_inplace cs ' bits ; cs ' and ( lxor ) cs1 cs2 = xor cs1 cs2 end |
module Array = struct include Array let mem x arr = let rec scan = function | - 1 -> false | n -> arr . ( n ) = x || scan ( pred n ) in scan ( Array . length arr - 1 ) end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.