text
stringlengths 0
601k
|
---|
let grandparent = Type . Primitive " Grandparent " |
module DiamondOrder = struct type t = unit let rec always_less_or_equal _ ~ left ~ right = match left , right with | _ , _ when Type . equal left right -> true | _ , Type . Top -> true | Type . Bottom , _ -> true | Type . Primitive " Child " , Type . Primitive " left_parent " -> true | Type . Primitive " Child " , Type . Primitive " right_parent " -> true | Type . Primitive " Child " , Type . Primitive " Grandparent " -> true | Type . Primitive " left_parent " , Type . Primitive " Grandparent " -> true | Type . Primitive " right_parent " , Type . Primitive " Grandparent " -> true | left , Union rights -> List . exists rights ~ f ( : fun right -> always_less_or_equal ( ) ~ left ~ right ) | Tuple ( Concrete left ) , Tuple ( Concrete right ) -> ( match List . for_all2 left right ~ f ( : fun left right -> always_less_or_equal ( ) ~ left ~ right ) with | Ok result -> result | _ -> false ) | _ -> false let meet _ left right = match left , right with | left , right when always_less_or_equal ( ) ~ left ~ right -> left | right , left when always_less_or_equal ( ) ~ left ~ right -> left | Type . Primitive " left_parent " , Type . Primitive " right_parent " -> Type . Primitive " Child " | _ -> Type . Bottom let join _ left right = match left , right with | left , right when always_less_or_equal ( ) ~ left ~ right -> right | right , left when always_less_or_equal ( ) ~ left ~ right -> right | Type . Primitive " left_parent " , Type . Primitive " right_parent " -> Type . Primitive " Grandparent " | _ -> Type . Top end |
module DiamondOrderedConstraints = OrderedConstraints ( DiamondOrder ) |
let variable ( ? name = " _V " ) constraints = Type . Variable . Unary . create name ~ constraints |
let add_bound constraints bound = let order = ( ) in constraints >>= fun constraints -> match bound with | ` Lower pair -> DiamondOrderedConstraints . add_lower_bound constraints ~ order ~ pair | ` Upper pair -> DiamondOrderedConstraints . add_upper_bound constraints ~ order ~ pair | ` Fallback variable -> DiamondOrderedConstraints . add_fallback_to_any constraints variable |> Option . some |
let test_add_bound _ = let assert_add_bound_has_result ( ? preconstraints = Some empty ) bound ~ expected_is_some = let result = add_bound preconstraints bound |> Option . is_some in assert_equal ~ printer ( : Printf . sprintf " % B " ) expected_is_some result in let assert_add_bound_succeeds = assert_add_bound_has_result ~ expected_is_some : true in let assert_add_bound_fails = assert_add_bound_has_result ~ expected_is_some : false in let unconstrained = variable Type . Variable . Unconstrained in assert_add_bound_succeeds ( ` Lower ( UnaryPair ( unconstrained , child ) ) ) ; assert_add_bound_fails ~ preconstraints ( : add_bound ( Some empty ) ( ` Lower ( UnaryPair ( unconstrained , left_parent ) ) ) ) ( ` Upper ( UnaryPair ( unconstrained , right_parent ) ) ) ; assert_add_bound_fails ( ` Lower ( UnaryPair ( variable ( Type . Variable . Bound child ) , left_parent ) ) ) ; assert_add_bound_succeeds ( ` Lower ( UnaryPair ( variable ( Type . Variable . Bound child ) , child ) ) ) ; assert_add_bound_succeeds ( ` Upper ( UnaryPair ( variable ( Type . Variable . Bound child ) , left_parent ) ) ) ; let explicit_parent_a_parent_b = variable ( Type . Variable . Explicit [ left_parent ; right_parent ] ) in assert_add_bound_succeeds ( ` Lower ( UnaryPair ( explicit_parent_a_parent_b , left_parent ) ) ) ; assert_add_bound_succeeds ( ` Lower ( UnaryPair ( explicit_parent_a_parent_b , right_parent ) ) ) ; assert_add_bound_succeeds ( ` Lower ( UnaryPair ( explicit_parent_a_parent_b , Variable ( Type . Variable . Unary . mark_as_bound explicit_parent_a_parent_b ) ) ) ) ; assert_add_bound_succeeds ( ` Upper ( UnaryPair ( explicit_parent_a_parent_b , Variable ( Type . Variable . Unary . mark_as_bound explicit_parent_a_parent_b ) ) ) ) ; assert_add_bound_fails ~ preconstraints : ( add_bound ( Some empty ) ( ` Lower ( UnaryPair ( explicit_parent_a_parent_b , left_parent ) ) ) ) ( ` Lower ( UnaryPair ( explicit_parent_a_parent_b , right_parent ) ) ) ; let parameter_variadic = Type . Variable . Variadic . Parameters . create " T " in assert_add_bound_succeeds ( ` Lower ( ParameterVariadicPair ( parameter_variadic , Type . Callable . Defined [ ] ) ) ) ; let preconstraints = add_bound ( Some empty ) ( ` Lower ( ParameterVariadicPair ( parameter_variadic , Type . Callable . Defined [ ] ) ) ) in assert_add_bound_succeeds ~ preconstraints ( ` Lower ( ParameterVariadicPair ( parameter_variadic , Type . Callable . Defined [ ] ) ) ) ; assert_add_bound_fails ~ preconstraints ( ` Lower ( ParameterVariadicPair ( parameter_variadic , Type . Callable . Defined [ Named { name = " x " ; annotation = Type . integer ; default = false } ] ) ) ) ; let variadic = Type . Variable . Variadic . Tuple . create " Ts " in let bound = TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) in assert_add_bound_succeeds ( ` Lower bound ) ; let preconstraints = add_bound ( Some empty ) ( ` Lower bound ) in assert_add_bound_succeeds ~ preconstraints ( ` Lower bound ) ; assert_add_bound_fails ~ preconstraints ( ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . bool ; Type . bool ] ) ) ) ; ( ) |
let optional_map_compare left right = match left , right with | Some left , Some right -> TypeConstraints . Solution . equal left right | None , None -> true | _ , _ -> false |
let optional_map_print map = map >>| TypeConstraints . Solution . show |> Option . value ~ default " : None " |
let assert_solution ~ sequentially_applied_bounds expected = let result = List . fold sequentially_applied_bounds ~ init ( : Some empty ) ~ f : add_bound >>= DiamondOrderedConstraints . solve ~ order ( ) : in let expected = expected >>| TypeConstraints . Solution . create in assert_equal ~ cmp : optional_map_compare ~ printer : optional_map_print expected result |
let test_single_variable_solution _ = assert_solution ~ sequentially_applied_bounds [ ] : ( Some [ ] ) ; let unconstrained = variable Type . Variable . Unconstrained in assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( unconstrained , child ) ) ] ( Some [ UnaryPair ( unconstrained , child ) ] ) ; assert_solution ~ sequentially_applied_bounds [ ` : Upper ( UnaryPair ( unconstrained , child ) ) ] ( Some [ UnaryPair ( unconstrained , child ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained , child ) ) ; ` Lower ( UnaryPair ( unconstrained , left_parent ) ) ] ( Some [ UnaryPair ( unconstrained , left_parent ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained , left_parent ) ) ; ` Lower ( UnaryPair ( unconstrained , right_parent ) ) ; ] ( Some [ UnaryPair ( unconstrained , grandparent ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Upper ( UnaryPair ( unconstrained , left_parent ) ) ; ` Lower ( UnaryPair ( unconstrained , grandparent ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds [ ` : Upper ( UnaryPair ( unconstrained , Type . Variable unconstrained ) ) ] ( Some [ ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Upper ( UnaryPair ( unconstrained , Type . list ( Type . Variable unconstrained ) ) ) ] None ; let bounded_by_parent_A = variable ( Type . Variable . Bound left_parent ) in assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( bounded_by_parent_A , child ) ) ] ( Some [ UnaryPair ( bounded_by_parent_A , child ) ] ) ; assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( bounded_by_parent_A , right_parent ) ) ] None ; let explicit_int_string_parent_A = variable ( Type . Variable . Explicit [ Type . integer ; Type . string ; left_parent ] ) in assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( explicit_int_string_parent_A , child ) ) ] ( Some [ UnaryPair ( explicit_int_string_parent_A , left_parent ) ] ) ; assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( explicit_int_string_parent_A , grandparent ) ) ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( explicit_int_string_parent_A , Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ) ; ] ( Some [ UnaryPair ( explicit_int_string_parent_A , Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Upper ( UnaryPair ( explicit_int_string_parent_A , Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ) ; ] ( Some [ UnaryPair ( explicit_int_string_parent_A , Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( explicit_int_string_parent_A , Type . optional ( Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Upper ( UnaryPair ( explicit_int_string_parent_A , Type . optional ( Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ) ) ; ] ( Some [ UnaryPair ( explicit_int_string_parent_A , Variable ( Type . Variable . Unary . mark_as_bound explicit_int_string_parent_A ) ) ; ] ) ; let parameter_variadic = Type . Variable . Variadic . Parameters . create " T " in let empty_parameters = Type . Callable . Defined [ ] in let one_named_parameter = Type . Callable . Defined [ Named { name = " x " ; annotation = Type . integer ; default = false } ] in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameter_variadic , empty_parameters ) ) ] ( Some [ ParameterVariadicPair ( parameter_variadic , empty_parameters ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameter_variadic , empty_parameters ) ) ; ` Lower ( ParameterVariadicPair ( parameter_variadic , one_named_parameter ) ) ; ] None ; let variadic = Type . Variable . Variadic . Tuple . create " Ts " in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ) ; ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . string ] ) ) ; ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . bool ] ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Child " ; Type . Primitive " Child " ] ) ) ; ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Grandparent " ; Type . Primitive " Grandparent " ] ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Grandparent " ; Type . Primitive " Grandparent " ] ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Child " ; Type . Primitive " Grandparent " ] ) ) ; ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Grandparent " ; Type . Primitive " Child " ] ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . Primitive " Child " ] ) ) ; ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . string ] ) ) ; ] None ; ( ) |
let test_multiple_variable_solution _ = let unconstrained_a = variable ~ name " : A " Type . Variable . Unconstrained in let unconstrained_b = variable ~ name " : B " Type . Variable . Unconstrained in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , child ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , child ) ; UnaryPair ( unconstrained_b , child ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_a ) ) ; ] None ; let unconstrained_c = variable ~ name " : C " Type . Variable . Unconstrained in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_c ) ) ; ` Lower ( UnaryPair ( unconstrained_c , child ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , child ) ; UnaryPair ( unconstrained_b , child ) ; UnaryPair ( unconstrained_c , child ) ; ] ) ; let unrelated = variable ~ name " : unrelated " Type . Variable . Unconstrained in assert_solution ~ sequentially_applied_bounds [ ` : Lower ( UnaryPair ( unconstrained_a , Type . Variable unrelated ) ) ] ( Some [ UnaryPair ( unconstrained_a , Type . Variable unrelated ) ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_a ) ) ; ` Lower ( UnaryPair ( unconstrained_c , child ) ) ; ] None ; let parameters_a = Type . Variable . Variadic . Parameters . create " Ta " in let parameters_b = Type . Variable . Variadic . Parameters . create " Tb " in let empty_parameters = Type . Callable . Defined [ ] in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameters_a , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_b ) ) ) ; ` Lower ( ParameterVariadicPair ( parameters_b , empty_parameters ) ) ; ] ( Some [ ParameterVariadicPair ( parameters_a , empty_parameters ) ; ParameterVariadicPair ( parameters_b , empty_parameters ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameters_a , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_b ) ) ) ; ` Lower ( ParameterVariadicPair ( parameters_b , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_a ) ) ) ; ] None ; let parameters_with_unconstrained_a = Type . Callable . Defined [ Named { name = " x " ; annotation = Type . Variable unconstrained_a ; default = false } ] in let parameters_with_integer = Type . Callable . Defined [ Named { name = " x " ; annotation = Type . integer ; default = false } ] in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameters_a , parameters_with_unconstrained_a ) ) ; ` Lower ( UnaryPair ( unconstrained_a , Type . integer ) ) ; ] ( Some [ ParameterVariadicPair ( parameters_a , parameters_with_integer ) ; UnaryPair ( unconstrained_a , Type . integer ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( ParameterVariadicPair ( parameters_a , parameters_with_unconstrained_a ) ) ; ` Lower ( UnaryPair ( unconstrained_a , Type . Callable . create ~ parameters ( : Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_a ) ) ~ annotation : Type . integer ( ) ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Fallback ( Unary unconstrained_b ) ; ] ( Some [ UnaryPair ( unconstrained_a , Type . Any ) ; UnaryPair ( unconstrained_b , Type . Any ) ] ) ; let variadic = Type . Variable . Variadic . Tuple . create " Ts " in let variadic2 = Type . Variable . Variadic . Tuple . create " Ts2 " in assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ : Type . integer ] ~ suffix [ : Type . string ] variadic2 ) ) ) ; ` Lower ( TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concrete [ Type . bool ] ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . bool ; Type . string ] ) ; TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concrete [ Type . bool ] ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic2 ) ) ) ; ` Lower ( TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic ) ) ) ; ] None ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ : Type . Variable unconstrained_a ] ~ suffix [ : Type . string ] variadic2 ) ) ) ; ` Lower ( TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concrete [ Type . bool ] ) ) ; ` Lower ( UnaryPair ( unconstrained_a , Type . integer ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , Type . integer ) ; TupleVariadicPair ( variadic , Type . OrderedTypes . Concrete [ Type . integer ; Type . bool ; Type . string ] ) ; TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concrete [ Type . bool ] ) ; ] ) ; assert_solution ~ sequentially_applied_bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ : Type . integer ] ~ suffix [ : Type . string ] variadic2 ) ) ) ; ` Fallback ( TupleVariadic variadic2 ) ; ] ( Some [ TupleVariadicPair ( variadic , Concatenation ( Type . OrderedTypes . Concatenation . create_from_unbounded_element ~ prefix [ : Type . integer ] ~ suffix [ : Type . string ] Type . Any ) ) ; TupleVariadicPair ( variadic2 , Concatenation ( Type . OrderedTypes . Concatenation . create_from_unbounded_element Type . Any ) ) ; ] ) ; ( ) |
let test_partial_solution _ = let expect_split_solution ~ bounds ~ variables expected_partial_solution expected_remainder_solution = let partial_result , remainder_solution = List . fold bounds ~ init ( : Some empty ) ~ f : add_bound >>= DiamondOrderedConstraints . extract_partial_solution ~ order ( ) : ~ variables >>| ( fun ( remainder , partial_solution ) -> Some partial_solution , DiamondOrderedConstraints . solve ~ order ( ) : remainder ) |> Option . value ~ default ( : None , None ) in let parse expected = expected >>| TypeConstraints . Solution . create in let double_compare ( left_first , left_second ) ( right_first , right_second ) = optional_map_compare left_first right_first && optional_map_compare left_second right_second in let double_print ( first , second ) = Printf . sprintf " % s ; % s " ( optional_map_print first ) ( optional_map_print second ) in assert_equal ~ cmp : double_compare ~ printer : double_print ( parse expected_partial_solution , parse expected_remainder_solution ) ( partial_result , remainder_solution ) in let unconstrained_a = variable ~ name " : A " Type . Variable . Unconstrained in let unconstrained_b = variable ~ name " : B " Type . Variable . Unconstrained in let unconstrained_c = variable ~ name " : C " Type . Variable . Unconstrained in expect_split_solution ~ variables [ : Type . Variable . Unary unconstrained_a ] ~ bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_a ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ] ) ( Some [ ] ) ; expect_split_solution ~ variables [ : Type . Variable . Unary unconstrained_a ] ~ bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . list ( Type . Variable unconstrained_b ) ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_a ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , Type . list ( Type . Variable unconstrained_b ) ) ] ) None ; expect_split_solution ~ variables [ : Type . Variable . Unary unconstrained_a ] ~ bounds : [ ` Lower ( UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ) ; ` Lower ( UnaryPair ( unconstrained_b , Type . Variable unconstrained_c ) ) ; ` Lower ( UnaryPair ( unconstrained_c , Type . Variable unconstrained_b ) ) ; ] ( Some [ UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) ] ) None ; let parameters_a = Type . Variable . Variadic . Parameters . create " Ta " in let parameters_b = Type . Variable . Variadic . Parameters . create " Tb " in expect_split_solution ~ variables [ : Type . Variable . ParameterVariadic parameters_a ] ~ bounds : [ ` Lower ( ParameterVariadicPair ( parameters_a , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_b ) ) ) ; ` Lower ( ParameterVariadicPair ( parameters_b , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_a ) ) ) ; ] ( Some [ ParameterVariadicPair ( parameters_a , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_b ) ) ; ] ) ( Some [ ] ) ; let variadic = Type . Variable . Variadic . Tuple . create " Ts " in let variadic2 = Type . Variable . Variadic . Tuple . create " Ts2 " in expect_split_solution ~ variables [ : Type . Variable . TupleVariadic variadic ] ~ bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic2 ) ) ) ; ` Lower ( TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic ) ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic2 ) ) ; ] ) ( Some [ ] ) ; expect_split_solution ~ variables [ : Type . Variable . TupleVariadic variadic ] ~ bounds : [ ` Lower ( TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic2 ) ) ) ; ` Lower ( TupleVariadicPair ( variadic2 , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ : Type . integer ] ~ suffix [ ] : variadic ) ) ) ; ] ( Some [ TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ ] : ~ suffix [ ] : variadic2 ) ) ; ] ) None ; ( ) |
let test_exists _ = let order = ( ) in let unconstrained_a = variable ~ name " : A " Type . Variable . Unconstrained in let unconstrained_b = variable ~ name " : B " Type . Variable . Unconstrained in let constraints_with_unconstrained_b = let pair = Type . Variable . UnaryPair ( unconstrained_a , Type . Variable unconstrained_b ) in DiamondOrderedConstraints . add_lower_bound TypeConstraints . empty ~ order ~ pair |> function | Some constraints -> constraints | None -> failwith " add bound failed " in assert_true ( TypeConstraints . exists_in_bounds constraints_with_unconstrained_b ~ variables [ : Type . Variable . Unary unconstrained_b ] ) ; assert_false ( TypeConstraints . exists_in_bounds constraints_with_unconstrained_b ~ variables [ : Type . Variable . Unary unconstrained_a ] ) ; let parameters_a = Type . Variable . Variadic . Parameters . create " Ta " in let parameters_b = Type . Variable . Variadic . Parameters . create " Tb " in let constraints_with_parameters_b = let pair = Type . Variable . ParameterVariadicPair ( parameters_a , Type . Callable . ParameterVariadicTypeVariable ( empty_head parameters_b ) ) in DiamondOrderedConstraints . add_lower_bound TypeConstraints . empty ~ order ~ pair |> fun constraints_option -> Option . value_exn constraints_option in assert_true ( TypeConstraints . exists_in_bounds constraints_with_parameters_b ~ variables [ : Type . Variable . ParameterVariadic parameters_b ] ) ; assert_false ( TypeConstraints . exists_in_bounds constraints_with_parameters_b ~ variables [ : Type . Variable . ParameterVariadic parameters_a ] ) ; let variadic = Type . Variable . Variadic . Tuple . create " Ts " in let variadic2 = Type . Variable . Variadic . Tuple . create " Ts2 " in let constraints_with_variadic2_in_bounds = let pair = TupleVariadicPair ( variadic , Type . OrderedTypes . Concatenation ( Type . OrderedTypes . Concatenation . create ~ prefix [ : Type . Variable unconstrained_a ] ~ suffix [ : Type . string ] variadic2 ) ) in DiamondOrderedConstraints . add_lower_bound TypeConstraints . empty ~ order ~ pair |> fun constraints_option -> Option . value_exn constraints_option in assert_true ( TypeConstraints . exists_in_bounds constraints_with_variadic2_in_bounds ~ variables [ : Type . Variable . TupleVariadic variadic2 ] ) ; assert_false ( TypeConstraints . exists_in_bounds constraints_with_variadic2_in_bounds ~ variables [ : Type . Variable . TupleVariadic variadic ] ) ; assert_true ( TypeConstraints . exists_in_bounds constraints_with_variadic2_in_bounds ~ variables [ : Type . Variable . Unary unconstrained_a ] ) ; ( ) |
let ( ) = " constraints " >::: [ " add_bound " >:: test_add_bound ; " single_variable " >:: test_single_variable_solution ; " multiple_variables " >:: test_multiple_variable_solution ; " partial_solution " >:: test_partial_solution ; " exists " >:: test_exists ; ] |> Test . run |
type type_forcing_context = | If_conditional | If_no_else_branch | While_loop_conditional | While_loop_body | For_loop_start_index | For_loop_stop_index | For_loop_body | Assert_condition | Sequence_left_hand_side | When_guard |
type type_expected = { ty : type_expr ; explanation : type_forcing_context option ; } |
type existential_restriction = | At_toplevel | In_group | In_rec | With_attributes | In_class_args | In_class_def | In_self_pattern |
type error = | Constructor_arity_mismatch of Longident . t * int * int | Label_mismatch of Longident . t * Ctype . Unification_trace . t | Pattern_type_clash of Ctype . Unification_trace . t * pattern_desc option | Or_pattern_type_clash of Ident . t * Ctype . Unification_trace . t | Multiply_bound_variable of string | Orpat_vars of Ident . t * Ident . t list | Expr_type_clash of Ctype . Unification_trace . t * type_forcing_context option * expression_desc option | Apply_non_function of type_expr | Apply_wrong_label of arg_label * type_expr | Label_multiply_defined of string | Label_missing of Ident . t list | Label_not_mutable of Longident . t | Wrong_name of string * type_expected * string * Path . t * string * string list | Name_type_mismatch of string * Longident . t * ( Path . t * Path . t ) * ( Path . t * Path . t ) list | Invalid_format of string | Undefined_method of type_expr * string * string list option | Undefined_inherited_method of string * string list | Virtual_class of Longident . t | Private_type of type_expr | Private_label of Longident . t * type_expr | Private_constructor of constructor_description * type_expr | Unbound_instance_variable of string * string list | Instance_variable_not_mutable of string | Not_subtype of Ctype . Unification_trace . t * Ctype . Unification_trace . t | Outside_class | Value_multiply_overridden of string | Coercion_failure of type_expr * type_expr * Ctype . Unification_trace . t * bool | Too_many_arguments of bool * type_expr * type_forcing_context option | Abstract_wrong_label of arg_label * type_expr * type_forcing_context option | Scoping_let_module of string * type_expr | Not_a_variant_type of Longident . t | Incoherent_label_order | Less_general of string * Ctype . Unification_trace . t | Modules_not_allowed | Cannot_infer_signature | Not_a_packed_module of type_expr | Unexpected_existential of existential_restriction * string * string list | Invalid_interval | Invalid_for_loop_index | No_value_clauses | Exception_pattern_disallowed | Mixed_value_and_exception_patterns_under_guard | Inlined_record_escape | Inlined_record_expected | Unrefuted_pattern of pattern | Invalid_extension_constructor_payload | Not_an_extension_constructor | Literal_overflow of string | Unknown_literal of string * char | Illegal_letrec_pat | Illegal_letrec_expr | Illegal_class_expr | Empty_pattern | Letop_type_clash of string * Ctype . Unification_trace . t | Andop_type_clash of string * Ctype . Unification_trace . t | Bindings_type_clash of Ctype . Unification_trace . t |
let type_module = ref ( ( fun _env _md -> assert false ) : Env . t -> Parsetree . module_expr -> Typedtree . module_expr ) |
let type_open : ( ? used_slot : bool ref -> override_flag -> Env . t -> Location . t -> Longident . t loc -> Path . t * Env . t ) ref = ref ( fun ? used_slot : _ _ -> assert false ) |
let type_open_decl : ( ? used_slot : bool ref -> Env . t -> Parsetree . open_declaration -> open_declaration * Types . signature * Env . t ) ref = ref ( fun ? used_slot : _ _ -> assert false ) |
let type_package = ref ( fun _ -> assert false ) |
let type_object = ref ( fun _env _s -> assert false : Env . t -> Location . t -> Parsetree . class_structure -> Typedtree . class_structure * Types . class_signature * string list ) |
let re node = Cmt_format . add_saved_type ( Cmt_format . Partial_expression node ) ; Stypes . record ( Stypes . Ti_expr node ) ; node ; ; |
let rp node = Cmt_format . add_saved_type ( Cmt_format . Partial_pattern node ) ; Stypes . record ( Stypes . Ti_pat node ) ; node ; ; |
type recarg = | Allowed | Required | Rejected |
let mk_expected ? explanation ty = { ty ; explanation ; } |
let case lhs rhs = { c_lhs = lhs ; c_guard = None ; c_rhs = rhs } |
let type_constant = function Const_int _ -> instance Predef . type_int | Const_char _ -> instance Predef . type_char | Const_string _ -> instance Predef . type_string | Const_float _ -> instance Predef . type_float | Const_int32 _ -> instance Predef . type_int32 | Const_int64 _ -> instance Predef . type_int64 | Const_nativeint _ -> instance Predef . type_nativeint |
let constant : Parsetree . constant -> ( Asttypes . constant , error ) result = function | Pconst_integer ( i , None ) -> begin try Ok ( Const_int ( Misc . Int_literal_converter . int i ) ) with Failure _ -> Error ( Literal_overflow " int " ) end | Pconst_integer ( i , Some ' l ' ) -> begin try Ok ( Const_int32 ( Misc . Int_literal_converter . int32 i ) ) with Failure _ -> Error ( Literal_overflow " int32 " ) end | Pconst_integer ( i , Some ' L ' ) -> begin try Ok ( Const_int64 ( Misc . Int_literal_converter . int64 i ) ) with Failure _ -> Error ( Literal_overflow " int64 " ) end | Pconst_integer ( i , Some ' n ' ) -> begin try Ok ( Const_nativeint ( Misc . Int_literal_converter . nativeint i ) ) with Failure _ -> Error ( Literal_overflow " nativeint " ) end | Pconst_integer ( i , Some c ) -> Error ( Unknown_literal ( i , c ) ) | Pconst_char c -> Ok ( Const_char c ) | Pconst_string ( s , d ) -> Ok ( Const_string ( s , d ) ) | Pconst_float ( f , None ) -> Ok ( Const_float f ) | Pconst_float ( f , Some c ) -> Error ( Unknown_literal ( f , c ) ) |
let constant_or_raise env loc cst = match constant cst with | Ok c -> c | Error err -> raise ( Error ( loc , env , err ) ) |
let type_option ty = newty ( Tconstr ( Predef . path_option , [ ty ] , ref Mnil ) ) |
let mkexp exp_desc exp_type exp_loc exp_env = { exp_desc ; exp_type ; exp_loc ; exp_env ; exp_extra = [ ] ; exp_attributes = [ ] } |
let option_none env ty loc = let lid = Longident . Lident " None " in let cnone = Env . find_ident_constructor Predef . ident_none env in mkexp ( Texp_construct ( mknoloc lid , cnone , [ ] ) ) ty loc env |
let option_some env texp = let lid = Longident . Lident " Some " in let csome = Env . find_ident_constructor Predef . ident_some env in mkexp ( Texp_construct ( mknoloc lid , csome , [ texp ] ) ) ( type_option texp . exp_type ) texp . exp_loc texp . exp_env |
let extract_option_type env ty = match expand_head env ty with { desc = Tconstr ( path , [ ty ] , _ ) } when Path . same path Predef . path_option -> ty | _ -> assert false |
let extract_concrete_record env ty = match extract_concrete_typedecl env ty with ( p0 , p , { type_kind = Type_record ( fields , _ ) } ) -> ( p0 , p , fields ) | _ -> raise Not_found |
let extract_concrete_variant env ty = match extract_concrete_typedecl env ty with ( p0 , p , { type_kind = Type_variant cstrs } ) -> ( p0 , p , cstrs ) | ( p0 , p , { type_kind = Type_open } ) -> ( p0 , p , [ ] ) | _ -> raise Not_found |
let extract_label_names env ty = try let ( _ , _ , fields ) = extract_concrete_record env ty in List . map ( fun l -> l . Types . ld_id ) fields with Not_found -> assert false |
let unify_exp_types loc env ty expected_ty = try unify env ty expected_ty with Unify trace -> raise ( Error ( loc , env , Expr_type_clash ( trace , None , None ) ) ) | Tags ( l1 , l2 ) -> raise ( Typetexp . Error ( loc , env , Typetexp . Variant_tags ( l1 , l2 ) ) ) |
let gadt_equations_level = ref None |
let get_gadt_equations_level ( ) = match ! gadt_equations_level with Some y -> y | None -> assert false |
let unify_pat_types ( ? refine = false ) loc env ty ty ' = try if refine then unify_gadt ~ equations_level ( : get_gadt_equations_level ( ) ) env ty ty ' else unify ! env ty ty ' with | Unify trace -> raise ( Error ( loc , ! env , Pattern_type_clash ( trace , None ) ) ) | Tags ( l1 , l2 ) -> raise ( Typetexp . Error ( loc , ! env , Typetexp . Variant_tags ( l1 , l2 ) ) ) |
let unify_pat ? refine env pat expected_ty = try unify_pat_types ? refine pat . pat_loc env pat . pat_type expected_ty with Error ( loc , env , Pattern_type_clash ( trace , None ) ) -> raise ( Error ( loc , env , Pattern_type_clash ( trace , Some pat . pat_desc ) ) ) |
let finalize_variant pat = match pat . pat_desc with Tpat_variant ( tag , opat , r ) -> let row = match expand_head pat . pat_env pat . pat_type with { desc = Tvariant row } -> r := row ; row_repr row | _ -> assert false in begin match row_field tag row with | Rabsent -> ( ) | Reither ( true , [ ] , _ , e ) when not row . row_closed -> set_row_field e ( Rpresent None ) | Reither ( false , ty :: tl , _ , e ) when not row . row_closed -> set_row_field e ( Rpresent ( Some ty ) ) ; begin match opat with None -> assert false | Some pat -> let env = ref pat . pat_env in List . iter ( unify_pat env pat ) ( ty :: tl ) end | Reither ( c , _l , true , e ) when not ( row_fixed row ) -> set_row_field e ( Reither ( c , [ ] , false , ref None ) ) | _ -> ( ) end ; | _ -> ( ) |
let has_variants p = exists_pattern ( function { pat_desc = Tpat_variant _ } -> true | _ -> false ) p |
type pattern_variable = { pv_id : Ident . t ; pv_type : type_expr ; pv_loc : Location . t ; pv_as_var : bool ; pv_attributes : attributes ; } |
type module_variable = string loc * Location . t |
let pattern_variables = ref ( [ ] : pattern_variable list ) |
let pattern_force = ref ( [ ] : ( unit -> unit ) list ) |
let pattern_scope = ref ( None : Annot . ident option ) ; ; |
let allow_modules = ref false |
let module_variables = ref ( [ ] : module_variable list ) |
let reset_pattern scope allow = pattern_variables := [ ] ; pattern_force := [ ] ; pattern_scope := scope ; allow_modules := allow ; module_variables := [ ] ; ; ; |
let maybe_add_pattern_variables_ghost loc_let env pv = List . fold_right ( fun { pv_id ; _ } env -> let name = Ident . name pv_id in if Env . bound_value name env then env else begin Env . enter_unbound_value name ( Val_unbound_ghost_recursive loc_let ) env end ) pv env |
let enter_variable ( ? is_module = false ) ( ? is_as_variable = false ) loc name ty attrs = if List . exists ( fun { pv_id ; _ } -> Ident . name pv_id = name . txt ) ! pattern_variables then raise ( Error ( loc , Env . empty , Multiply_bound_variable name . txt ) ) ; let id = Ident . create_local name . txt in pattern_variables := { pv_id = id ; pv_type = ty ; pv_loc = loc ; pv_as_var = is_as_variable ; pv_attributes = attrs } :: ! pattern_variables ; if is_module then begin if not ! allow_modules then raise ( Error ( loc , Env . empty , Modules_not_allowed ) ) ; module_variables := ( name , loc ) :: ! module_variables end else begin Option . iter ( fun s -> Stypes . record ( Stypes . An_ident ( name . loc , name . txt , s ) ) ) ! pattern_scope end ; id |
let sort_pattern_variables vs = List . sort ( fun { pv_id = x ; _ } { pv_id = y ; _ } -> Stdlib . compare ( Ident . name x ) ( Ident . name y ) ) vs |
let enter_orpat_variables loc env p1_vs p2_vs = let p1_vs = sort_pattern_variables p1_vs and p2_vs = sort_pattern_variables p2_vs in let rec unify_vars p1_vs p2_vs = let vars vs = List . map ( fun { pv_id ; _ } -> pv_id ) vs in match p1_vs , p2_vs with | { pv_id = x1 ; pv_type = t1 ; _ } :: rem1 , { pv_id = x2 ; pv_type = t2 ; _ } :: rem2 when Ident . equal x1 x2 -> if x1 == x2 then unify_vars rem1 rem2 else begin begin try unify_var env ( newvar ( ) ) t1 ; unify env t1 t2 with | Unify trace -> raise ( Error ( loc , env , Or_pattern_type_clash ( x1 , trace ) ) ) end ; ( x2 , x1 ) :: unify_vars rem1 rem2 end | [ ] , [ ] -> [ ] | { pv_id ; _ } :: _ , [ ] | [ ] , { pv_id ; _ } :: _ -> raise ( Error ( loc , env , Orpat_vars ( pv_id , [ ] ) ) ) | { pv_id = x ; _ } :: _ , { pv_id = y ; _ } :: _ -> let err = if Ident . name x < Ident . name y then Orpat_vars ( x , vars p2_vs ) else Orpat_vars ( y , vars p1_vs ) in raise ( Error ( loc , env , err ) ) in unify_vars p1_vs p2_vs |
let rec build_as_type env p = match p . pat_desc with Tpat_alias ( p1 , _ , _ ) -> build_as_type env p1 | Tpat_tuple pl -> let tyl = List . map ( build_as_type env ) pl in newty ( Ttuple tyl ) | Tpat_construct ( _ , cstr , pl ) -> let keep = cstr . cstr_private = Private || cstr . cstr_existentials <> [ ] in if keep then p . pat_type else let tyl = List . map ( build_as_type env ) pl in let ty_args , ty_res = instance_constructor cstr in List . iter2 ( fun ( p , ty ) -> unify_pat env { p with pat_type = ty } ) ( List . combine pl tyl ) ty_args ; ty_res | Tpat_variant ( l , p ' , _ ) -> let ty = Option . map ( build_as_type env ) p ' in newty ( Tvariant { row_fields [ = l , Rpresent ty ] ; row_more = newvar ( ) ; row_bound ( ) ; = row_name = None ; row_fixed = None ; row_closed = false } ) | Tpat_record ( lpl , _ ) -> let lbl = snd3 ( List . hd lpl ) in if lbl . lbl_private = Private then p . pat_type else let ty = newvar ( ) in let ppl = List . map ( fun ( _ , l , p ) -> l . lbl_pos , p ) lpl in let do_label lbl = let _ , ty_arg , ty_res = instance_label false lbl in unify_pat env { p with pat_type = ty } ty_res ; let refinable = lbl . lbl_mut = Immutable && List . mem_assoc lbl . lbl_pos ppl && match ( repr lbl . lbl_arg ) . desc with Tpoly _ -> false | _ -> true in if refinable then begin let arg = List . assoc lbl . lbl_pos ppl in unify_pat env { arg with pat_type = build_as_type env arg } ty_arg end else begin let _ , ty_arg ' , ty_res ' = instance_label false lbl in unify ! env ty_arg ty_arg ' ; unify_pat env p ty_res ' end in Array . iter do_label lbl . lbl_all ; ty | Tpat_or ( p1 , p2 , row ) -> begin match row with None -> let ty1 = build_as_type env p1 and ty2 = build_as_type env p2 in unify_pat env { p2 with pat_type = ty2 } ty1 ; ty1 | Some row -> let row = row_repr row in newty ( Tvariant { row with row_closed = false ; row_more = newvar ( ) } ) end | Tpat_any | Tpat_var _ | Tpat_constant _ | Tpat_array _ | Tpat_lazy _ | Tpat_exception _ -> p . pat_type |
let build_or_pat env loc lid = let path , decl = Env . lookup_type ~ loc : lid . loc lid . txt env in let tyl = List . map ( fun _ -> newvar ( ) ) decl . type_params in let row0 = let ty = expand_head env ( newty ( Tconstr ( path , tyl , ref Mnil ) ) ) in match ty . desc with Tvariant row when static_row row -> row | _ -> raise ( Error ( lid . loc , env , Not_a_variant_type lid . txt ) ) in let pats , fields = List . fold_left ( fun ( pats , fields ) ( l , f ) -> match row_field_repr f with Rpresent None -> ( l , None ) :: pats , ( l , Reither ( true , [ ] , true , ref None ) ) :: fields | Rpresent ( Some ty ) -> ( l , Some { pat_desc = Tpat_any ; pat_loc = Location . none ; pat_env = env ; pat_type = ty ; pat_extra [ ] ; = pat_attributes [ ] } ) = :: pats , ( l , Reither ( false , [ ty ] , true , ref None ) ) :: fields | _ -> pats , fields ) ( [ ] , [ ] ) ( row_repr row0 ) . row_fields in let row = { row_fields = List . rev fields ; row_more = newvar ( ) ; row_bound = ( ) ; row_closed = false ; row_fixed = None ; row_name = Some ( path , tyl ) } in let ty = newty ( Tvariant row ) in let gloc = { loc with Location . loc_ghost = true } in let row ' = ref { row with row_more = newvar ( ) } in let pats = List . map ( fun ( l , p ) -> { pat_desc = Tpat_variant ( l , p , row ' ) ; pat_loc = gloc ; pat_env = env ; pat_type = ty ; pat_extra [ ] ; = pat_attributes [ ] } ) = pats in match pats with [ ] -> raise ( Error ( lid . loc , env , Not_a_variant_type lid . txt ) ) | pat :: pats -> let r = List . fold_left ( fun pat pat0 -> { pat_desc = Tpat_or ( pat0 , pat , Some row0 ) ; pat_extra [ ] ; = pat_loc = gloc ; pat_env = env ; pat_type = ty ; pat_attributes [ ] } ) = pat pats in ( path , rp { r with pat_loc = loc } , ty ) |
let split_cases env cases = let add_case lst case = function | None -> lst | Some c_lhs -> { case with c_lhs } :: lst in List . fold_right ( fun ( { c_lhs ; c_guard } as case ) ( vals , exns ) -> match split_pattern c_lhs with | Some _ , Some _ when c_guard <> None -> raise ( Error ( c_lhs . pat_loc , env , Mixed_value_and_exception_patterns_under_guard ) ) | vp , ep -> add_case vals case vp , add_case exns case ep ) cases ( [ ] , [ ] ) |
let rec expand_path env p = let decl = try Some ( Env . find_type p env ) with Not_found -> None in match decl with Some { type_manifest = Some ty } -> begin match repr ty with { desc = Tconstr ( p , _ , _ ) } -> expand_path env p | _ -> assert false end | _ -> let p ' = Env . normalize_type_path None env p in if Path . same p p ' then p else expand_path env p ' |
let compare_type_path env tpath1 tpath2 = Path . same ( expand_path env tpath1 ) ( expand_path env tpath2 ) |
let label_of_kind kind = if kind = " record " then " field " else " constructor " |
module NameChoice ( Name : sig type t type usage val type_kind : string val get_name : t -> string val get_type : t -> type_expr val lookup_all_from_type : Location . t -> usage -> Path . t -> Env . t -> ( t * ( unit -> unit ) ) list val in_env : t -> bool open Name let get_type_path d = match ( repr ( get_type d ) ) . desc with | Tconstr ( p , _ , _ ) -> p | _ -> assert false let lookup_from_type env tpath usage lid = let descrs = lookup_all_from_type lid . loc usage tpath env in match lid . txt with | Longident . Lident s -> begin match List . find ( fun ( nd , _ ) -> get_name nd = s ) descrs with | descr , use -> use ( ) ; descr | exception Not_found -> let names = List . map ( fun ( nd , _ ) -> get_name nd ) descrs in raise ( Error ( lid . loc , env , Wrong_name ( " " , mk_expected ( newvar ( ) ) , type_kind , tpath , s , names ) ) ) end | _ -> raise Not_found let rec unique eq acc = function [ ] -> List . rev acc | x :: rem -> if List . exists ( eq x ) acc then unique eq acc rem else unique eq ( x :: acc ) rem let ambiguous_types env lbl others = let tpath = get_type_path lbl in let others = List . map ( fun ( lbl , _ ) -> get_type_path lbl ) others in let tpaths = unique ( compare_type_path env ) [ tpath ] others in match tpaths with [ _ ] -> [ ] | _ -> let open Printtyp in wrap_printing_env ~ error : true env ( fun ( ) -> reset ( ) ; strings_of_paths Type tpaths ) let disambiguate_by_type env tpath lbls = match lbls with | ( Error _ : _ result ) -> raise Not_found | Ok lbls -> let check_type ( lbl , _ ) = let lbl_tpath = get_type_path lbl in compare_type_path env tpath lbl_tpath in List . find check_type lbls let disambiguate ( ? warn = Location . prerr_warning ) ? scope usage lid env opath lbls = let scope = match scope with None -> lbls | Some l -> l in let lbl = match opath with None -> begin match lbls with | ( Error ( loc ' , env ' , err ) : _ result ) -> Env . lookup_error loc ' env ' err | Ok [ ] -> assert false | Ok ( ( lbl , use ) :: rest ) -> use ( ) ; Printtyp . Conflicts . reset ( ) ; let paths = ambiguous_types env lbl rest in let expansion = Format . asprintf " % t " Printtyp . Conflicts . print_explanations in if paths <> [ ] then warn lid . loc ( Warnings . Ambiguous_name ( [ Longident . last lid . txt ] , paths , false , expansion ) ) ; lbl end | Some ( tpath0 , tpath , pr ) -> let warn_pr ( ) = let label = label_of_kind type_kind in warn lid . loc ( Warnings . Not_principal ( " this type - based " ^ label ^ " disambiguation " ) ) in try let lbl , use = disambiguate_by_type env tpath scope in use ( ) ; if not pr then begin match lbls with | ( Error _ : _ result ) | Ok [ ] -> warn_pr ( ) | Ok ( ( lbl ' , _use ' ) :: rest ) -> let lbl_tpath = get_type_path lbl ' in if not ( compare_type_path env tpath lbl_tpath ) then warn_pr ( ) else Printtyp . Conflicts . reset ( ) ; let paths = ambiguous_types env lbl rest in let expansion = Format . asprintf " % t " Printtyp . Conflicts . print_explanations in if paths <> [ ] then warn lid . loc ( Warnings . Ambiguous_name ( [ Longident . last lid . txt ] , paths , false , expansion ) ) end ; lbl with Not_found -> try let lbl = lookup_from_type env tpath usage lid in if in_env lbl then begin let s = Printtyp . wrap_printing_env ~ error : true env ( fun ( ) -> Printtyp . string_of_path tpath ) in warn lid . loc ( Warnings . Name_out_of_scope ( s , [ Longident . last lid . txt ] , false ) ) ; end ; if not pr then warn_pr ( ) ; lbl with Not_found -> match lbls with | ( Error ( loc ' , env ' , err ) : _ result ) -> Env . lookup_error loc ' env ' err | Ok lbls -> let tp = ( tpath0 , expand_path env tpath ) in let tpl = List . map ( fun ( lbl , _ ) -> let tp0 = get_type_path lbl in let tp = expand_path env tp0 in ( tp0 , tp ) ) lbls in raise ( Error ( lid . loc , env , Name_type_mismatch ( type_kind , lid . txt , tp , tpl ) ) ) in if in_env lbl then begin match scope with | Ok ( ( lab1 , _ ) :: _ ) when lab1 == lbl -> ( ) | _ -> Location . prerr_warning lid . loc ( Warnings . Disambiguated_name ( get_name lbl ) ) end ; lbl end |
let wrap_disambiguate kind ty f x = try f x with Error ( loc , env , Wrong_name ( " " , _ , tk , tp , name , valid_names ) ) -> raise ( Error ( loc , env , Wrong_name ( kind , ty , tk , tp , name , valid_names ) ) ) |
module Label = NameChoice ( struct type t = label_description type usage = unit let type_kind = " record " let get_name lbl = lbl . lbl_name let get_type lbl = lbl . lbl_res let lookup_all_from_type loc ( ) path env = Env . lookup_all_labels_from_type ~ loc path env let in_env lbl = match lbl . lbl_repres with | Record_regular | Record_float | Record_unboxed false -> true | Record_unboxed true | Record_inlined _ | Record_extension _ -> false end ) |
let disambiguate_label_by_ids keep closed ids labels = let check_ids ( lbl , _ ) = let lbls = Hashtbl . create 8 in Array . iter ( fun lbl -> Hashtbl . add lbls lbl . lbl_name ( ) ) lbl . lbl_all ; List . for_all ( Hashtbl . mem lbls ) ids and check_closed ( lbl , _ ) = ( not closed || List . length ids = Array . length lbl . lbl_all ) in let labels ' = List . filter check_ids labels in if keep && labels ' = [ ] then ( false , labels ) else let labels ' ' = List . filter check_closed labels ' in if keep && labels ' ' = [ ] then ( false , labels ' ) else ( true , labels ' ' ) |
let disambiguate_lid_a_list loc closed env opath lid_a_list = let ids = List . map ( fun ( lid , _ ) -> Longident . last lid . txt ) lid_a_list in let w_pr = ref false and w_amb = ref [ ] and w_scope = ref [ ] and w_scope_ty = ref " " in let warn loc msg = let open Warnings in match msg with | Not_principal _ -> w_pr := true | Ambiguous_name ( [ s ] , l , _ , ex ) -> w_amb := ( s , l , ex ) :: ! w_amb | Name_out_of_scope ( ty , [ s ] , _ ) -> w_scope := s :: ! w_scope ; w_scope_ty := ty | _ -> Location . prerr_warning loc msg in let process_label lid = let scope = Env . lookup_all_labels ~ loc : lid . loc lid . txt env in match opath , scope with | None , Error ( loc , env , err ) -> Env . lookup_error loc env err | Some _ , Error _ -> Label . disambiguate ( ) lid env opath scope ~ warn ~ scope | _ , Ok lbls -> let ( ok , lbls ) = match opath with | Some ( _ , _ , true ) -> ( true , lbls ) | _ -> disambiguate_label_by_ids ( opath = None ) closed ids lbls in if ok then Label . disambiguate ( ) lid env opath ( Ok lbls ) ~ warn ~ scope else fst ( List . hd lbls ) in let lbl_a_list = List . map ( fun ( lid , a ) -> lid , process_label lid , a ) lid_a_list in if ! w_pr then Location . prerr_warning loc ( Warnings . Not_principal " this type - based record disambiguation " ) else begin match List . rev ! w_amb with ( _ , types , ex ) :: _ as amb -> let paths = List . map ( fun ( _ , lbl , _ ) -> Label . get_type_path lbl ) lbl_a_list in let path = List . hd paths in let fst3 ( x , _ , _ ) = x in if List . for_all ( compare_type_path env path ) ( List . tl paths ) then Location . prerr_warning loc ( Warnings . Ambiguous_name ( List . map fst3 amb , types , true , ex ) ) else List . iter ( fun ( s , l , ex ) -> Location . prerr_warning loc ( Warnings . Ambiguous_name ( [ s ] , l , false , ex ) ) ) amb | _ -> ( ) end ; if ! w_scope <> [ ] then Location . prerr_warning loc ( Warnings . Name_out_of_scope ( ! w_scope_ty , List . rev ! w_scope , true ) ) ; lbl_a_list |
let rec find_record_qual = function | [ ] -> None | ( { txt = Longident . Ldot ( modname , _ ) } , _ ) :: _ -> Some modname | _ :: rest -> find_record_qual rest |
let map_fold_cont f xs k = List . fold_right ( fun x k ys -> f x ( fun y -> k ( y :: ys ) ) ) xs ( fun ys -> k ( List . rev ys ) ) [ ] |
let type_label_a_list ? labels loc closed env type_lbl_a opath lid_a_list k = let lbl_a_list = match lid_a_list , labels with ( { txt = Longident . Lident s } , _ ) :: _ , Some labels when Hashtbl . mem labels s -> List . map ( function lid , a -> match lid . txt with Longident . Lident s -> lid , Hashtbl . find labels s , a | _ -> assert false ) lid_a_list | _ -> let lid_a_list = match find_record_qual lid_a_list with None -> lid_a_list | Some modname -> List . map ( fun ( lid , a as lid_a ) -> match lid . txt with Longident . Lident s -> { lid with txt = Longident . Ldot ( modname , s ) } , a | _ -> lid_a ) lid_a_list in disambiguate_lid_a_list loc closed env opath lid_a_list in let lbl_a_list = List . sort ( fun ( _ , lbl1 , _ ) ( _ , lbl2 , _ ) -> compare lbl1 . lbl_pos lbl2 . lbl_pos ) lbl_a_list in map_fold_cont type_lbl_a lbl_a_list k ; ; |
let check_recordpat_labels loc lbl_pat_list closed = match lbl_pat_list with | [ ] -> ( ) | ( _ , label1 , _ ) :: _ -> let all = label1 . lbl_all in let defined = Array . make ( Array . length all ) false in let check_defined ( _ , label , _ ) = if defined . ( label . lbl_pos ) then raise ( Error ( loc , Env . empty , Label_multiply_defined label . lbl_name ) ) else defined . ( label . lbl_pos ) <- true in List . iter check_defined lbl_pat_list ; if closed = Closed && Warnings . is_active ( Warnings . Non_closed_record_pattern " " ) then begin let undefined = ref [ ] in for i = 0 to Array . length all - 1 do if not defined . ( i ) then undefined := all . ( i ) . lbl_name :: ! undefined done ; if ! undefined <> [ ] then begin let u = String . concat " , " ( List . rev ! undefined ) in Location . prerr_warning loc ( Warnings . Non_closed_record_pattern u ) end end |
module Constructor = NameChoice ( struct type t = constructor_description type usage = Env . constructor_usage let type_kind = " variant " let get_name cstr = cstr . cstr_name let get_type cstr = cstr . cstr_res let lookup_all_from_type loc usage path env = Env . lookup_all_constructors_from_type ~ loc usage path env let in_env _ = true end ) |
let unify_head_only ~ refine loc env ty constr = let ( _ , ty_res ) = instance_constructor constr in let ty_res = repr ty_res in match ty_res . desc with | Tconstr ( p , args , m ) -> ty_res . desc <- Tconstr ( p , List . map ( fun _ -> newvar ( ) ) args , m ) ; enforce_constraints ! env ty_res ; unify_pat_types ~ refine loc env ty_res ty | _ -> assert false |
type half_typed_case = { typed_pat : pattern ; pat_type_for_unif : type_expr ; untyped_case : Parsetree . case ; branch_env : Env . t ; pat_vars : pattern_variable list ; unpacks : module_variable list ; contains_gadt : bool ; } |
let rec has_literal_pattern p = match p . ppat_desc with | Ppat_constant _ | Ppat_interval _ -> true | Ppat_any | Ppat_variant ( _ , None ) | Ppat_construct ( _ , None ) | Ppat_type _ | Ppat_var _ | Ppat_unpack _ | Ppat_extension _ -> false | Ppat_exception p | Ppat_variant ( _ , Some p ) | Ppat_construct ( _ , Some p ) | Ppat_constraint ( p , _ ) | Ppat_alias ( p , _ ) | Ppat_lazy p | Ppat_open ( _ , p ) -> has_literal_pattern p | Ppat_tuple ps | Ppat_array ps -> List . exists has_literal_pattern ps | Ppat_record ( ps , _ ) -> List . exists ( fun ( _ , p ) -> has_literal_pattern p ) ps | Ppat_or ( p , q ) -> has_literal_pattern p || has_literal_pattern q |
let check_scope_escape loc env level ty = try Ctype . check_scope_escape env level ty with Unify trace -> raise ( Error ( loc , env , Pattern_type_clash ( trace , None ) ) ) |
type pattern_checking_mode = | Normal | Counter_example of counter_example_checking_info explosion_fuel : int ; splitting_mode : splitting_mode ; constrs : ( string , Types . constructor_description ) Hashtbl . t ; labels : ( string , Types . label_description ) Hashtbl . t ; } | Backtrack_or | Refine_or of { inside_nonsplit_or : bool ; } exception Need_backtrack |
type state = { snapshot : Btype . snapshot ; levels : Ctype . levels ; env : Env . t ; } |
let save_state env = { snapshot = Btype . snapshot ( ) ; levels = Ctype . save_levels ( ) ; env = ! env ; } |
let set_state s env = Btype . backtrack s . snapshot ; Ctype . set_levels s . levels ; env := s . env |
let rec find_valid_alternative f pat = match pat . ppat_desc with | Ppat_or ( p1 , p2 ) -> ( try find_valid_alternative f p1 with Error _ -> find_valid_alternative f p2 ) | _ -> f pat |
let no_explosion = function | Normal -> Normal | Counter_example info -> Counter_example { info with explosion_fuel = 0 } |
let get_splitting_mode = function | Normal -> None | Counter_example { splitting_mode } -> Some splitting_mode |
let enter_nonsplit_or mode = match mode with | Normal -> Normal | Counter_example info -> let splitting_mode = match info . splitting_mode with | Backtrack_or -> assert false | Refine_or _ -> Refine_or { inside_nonsplit_or = true } in Counter_example { info with splitting_mode } |
let rec type_pat ( ? exception_allowed = false ) ~ no_existentials ~ mode ~ env sp expected_ty k = Builtin_attributes . warning_scope sp . ppat_attributes ( fun ( ) -> type_pat_aux ~ exception_allowed ~ no_existentials ~ mode ~ env sp expected_ty k ) ~ env sp expected_ty k = let type_pat ( ? exception_allowed = false ) ( ? mode = mode ) ( ? env = env ) = type_pat ~ exception_allowed ~ no_existentials ~ mode ~ env in let loc = sp . ppat_loc in let refine = match mode with Normal -> false | Counter_example _ -> true in let rup k x = if mode = Normal then ( ignore ( rp x ) ) ; unify_pat ~ refine env x ( instance expected_ty ) ; k x in let rp k x : pattern = if mode = Normal then k ( rp x ) else k x in let construction_not_used_in_counterexamples = ( mode = Normal ) in let must_backtrack_on_gadt = match get_splitting_mode mode with | None -> false | Some Backtrack_or -> false | Some ( Refine_or { inside_nonsplit_or } ) -> inside_nonsplit_or in match sp . ppat_desc with Ppat_any -> let k ' d = rp k { pat_desc = d ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } in begin match mode with | Normal -> k ' Tpat_any | Counter_example { explosion_fuel ; _ } when explosion_fuel <= 0 -> k ' Tpat_any | Counter_example ( { explosion_fuel ; _ } as info ) -> begin match Parmatch . ppat_of_type ! env expected_ty with | exception Parmatch . Empty -> raise ( Error ( loc , ! env , Empty_pattern ) ) | ( sp , constrs , labels ) -> if sp . ppat_desc = Parsetree . Ppat_any then k ' Tpat_any else if must_backtrack_on_gadt then raise Need_backtrack else let explosion_fuel = match sp . ppat_desc with Parsetree . Ppat_or _ -> explosion_fuel - 5 | _ -> explosion_fuel - 1 in let mode = Counter_example { info with explosion_fuel ; constrs ; labels } in type_pat ~ mode sp expected_ty k end end | Ppat_var name -> let ty = instance expected_ty in let id = if name . txt = " * extension " * then Ident . create_local name . txt else enter_variable loc name ty sp . ppat_attributes in rp k { pat_desc = Tpat_var ( id , name ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } | Ppat_unpack name -> assert construction_not_used_in_counterexamples ; let t = instance expected_ty in begin match name . txt with | None -> rp k { pat_desc = Tpat_any ; pat_loc = sp . ppat_loc ; pat_extra [ = Tpat_unpack , name . loc , sp . ppat_attributes ] ; pat_type = t ; pat_attributes = [ ] ; pat_env = ! env } | Some s -> let v = { name with txt = s } in let id = enter_variable loc v t ~ is_module : true sp . ppat_attributes in rp k { pat_desc = Tpat_var ( id , v ) ; pat_loc = sp . ppat_loc ; pat_extra [ = Tpat_unpack , loc , sp . ppat_attributes ] ; pat_type = t ; pat_attributes = [ ] ; pat_env = ! env } end | Ppat_constraint ( { ppat_desc = Ppat_var name ; ppat_loc = lloc ; ppat_attributes = attrs } , ( { ptyp_desc = Ptyp_poly _ } as sty ) ) -> assert construction_not_used_in_counterexamples ; let cty , force = Typetexp . transl_simple_type_delayed ! env sty in let ty = cty . ctyp_type in unify_pat_types ~ refine lloc env ty ( instance expected_ty ) ; pattern_force := force :: ! pattern_force ; begin match ty . desc with | Tpoly ( body , tyl ) -> begin_def ( ) ; let _ , ty ' = instance_poly ~ keep_names : true false tyl body in end_def ( ) ; generalize ty ' ; let id = enter_variable lloc name ty ' attrs in rp k { pat_desc = Tpat_var ( id , name ) ; pat_loc = lloc ; pat_extra = [ Tpat_constraint cty , loc , sp . ppat_attributes ] ; pat_type = ty ; pat_attributes = [ ] ; pat_env = ! env } | _ -> assert false end | Ppat_alias ( sq , name ) -> assert construction_not_used_in_counterexamples ; type_pat sq expected_ty ( fun q -> begin_def ( ) ; let ty_var = build_as_type env q in end_def ( ) ; generalize ty_var ; let id = enter_variable ~ is_as_variable : true loc name ty_var sp . ppat_attributes in rp k { pat_desc = Tpat_alias ( q , id , name ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = q . pat_type ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } ) | Ppat_constant cst -> let cst = constant_or_raise ! env loc cst in rup k { pat_desc = Tpat_constant cst ; pat_loc = loc ; pat_extra [ ] ; = pat_type = type_constant cst ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } | Ppat_interval ( Pconst_char c1 , Pconst_char c2 ) -> let open Ast_helper . Pat in let gloc = { loc with Location . loc_ghost = true } in let rec loop c1 c2 = if c1 = c2 then constant ~ loc : gloc ( Pconst_char c1 ) else or_ ~ loc : gloc ( constant ~ loc : gloc ( Pconst_char c1 ) ) ( loop ( Char . chr ( Char . code c1 + 1 ) ) c2 ) in let p = if c1 <= c2 then loop c1 c2 else loop c2 c1 in let p = { p with ppat_loc = loc } in type_pat ~ mode ( : no_explosion mode ) p expected_ty k | Ppat_interval _ -> raise ( Error ( loc , ! env , Invalid_interval ) ) | Ppat_tuple spl -> assert ( List . length spl >= 2 ) ; let spl_ann = List . map ( fun p -> ( p , newgenvar ( ) ) ) spl in let ty = newgenty ( Ttuple ( List . map snd spl_ann ) ) in begin_def ( ) ; let expected_ty = instance expected_ty in end_def ( ) ; generalize_structure expected_ty ; unify_pat_types ~ refine loc env ty expected_ty ; map_fold_cont ( fun ( p , t ) -> type_pat p t ) spl_ann ( fun pl -> rp k { pat_desc = Tpat_tuple pl ; pat_loc = loc ; pat_extra [ ] ; = pat_type = newty ( Ttuple ( List . map ( fun p -> p . pat_type ) pl ) ) ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } ) | Ppat_construct ( lid , sarg ) -> let opath = try let ( p0 , p , _ ) = extract_concrete_variant ! env expected_ty in Some ( p0 , p , true ) with Not_found -> None in let constr = match lid . txt , mode with | Longident . Lident s , Counter_example { constrs ; _ } -> assert ( Hashtbl . mem constrs s ) ; Hashtbl . find constrs s | _ -> let candidates = Env . lookup_all_constructors Env . Pattern ~ loc : lid . loc lid . txt ! env in wrap_disambiguate " This variant pattern is expected to have " ( mk_expected expected_ty ) ( Constructor . disambiguate Env . Pattern lid ! env opath ) candidates in if constr . cstr_generalized && must_backtrack_on_gadt then raise Need_backtrack ; begin match no_existentials , constr . cstr_existentials with | None , _ | _ , [ ] -> ( ) | Some r , ( _ :: _ as exs ) -> let exs = List . map ( Ctype . existential_name constr ) exs in let name = constr . cstr_name in raise ( Error ( loc , ! env , Unexpected_existential ( r , name , exs ) ) ) end ; if constr . cstr_generalized then unify_head_only ~ refine loc env ( instance expected_ty ) constr ; let sargs = match sarg with None -> [ ] | Some { ppat_desc = Ppat_tuple spl } when constr . cstr_arity > 1 || Builtin_attributes . explicit_arity sp . ppat_attributes -> spl | Some ( { ppat_desc = Ppat_any } as sp ) when constr . cstr_arity <> 1 -> if constr . cstr_arity = 0 then Location . prerr_warning sp . ppat_loc Warnings . Wildcard_arg_to_constant_constr ; replicate_list sp constr . cstr_arity | Some sp -> [ sp ] in if Builtin_attributes . warn_on_literal_pattern constr . cstr_attributes then begin match List . filter has_literal_pattern sargs with | sp :: _ -> Location . prerr_warning sp . ppat_loc Warnings . Fragile_literal_pattern | _ -> ( ) end ; if List . length sargs <> constr . cstr_arity then raise ( Error ( loc , ! env , Constructor_arity_mismatch ( lid . txt , constr . cstr_arity , List . length sargs ) ) ) ; begin_def ( ) ; let ( ty_args , ty_res ) = instance_constructor ~ in_pattern ( : env , get_gadt_equations_level ( ) ) constr in let expected_ty = instance expected_ty in unify_pat_types loc env ty_res expected_ty ~ refine ( : refine || constr . cstr_generalized && no_existentials = None ) ; end_def ( ) ; generalize_structure expected_ty ; generalize_structure ty_res ; List . iter generalize_structure ty_args ; let rec check_non_escaping p = match p . ppat_desc with | Ppat_or ( p1 , p2 ) -> check_non_escaping p1 ; check_non_escaping p2 | Ppat_alias ( p , _ ) -> check_non_escaping p | Ppat_constraint _ -> raise ( Error ( p . ppat_loc , ! env , Inlined_record_escape ) ) | _ -> ( ) in if constr . cstr_inlined <> None then List . iter check_non_escaping sargs ; map_fold_cont ( fun ( p , t ) -> type_pat p t ) ( List . combine sargs ty_args ) ( fun args -> rp k { pat_desc = Tpat_construct ( lid , constr , args ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } ) | Ppat_variant ( l , sarg ) -> let arg_type = match sarg with None -> [ ] | Some _ -> [ newgenvar ( ) ] in let row = { row_fields = [ l , Reither ( sarg = None , arg_type , true , ref None ) ] ; row_bound = ( ) ; row_closed = false ; row_more = newgenvar ( ) ; row_fixed = None ; row_name = None } in begin_def ( ) ; let expected_ty = instance expected_ty in end_def ( ) ; generalize_structure expected_ty ; if l = Parmatch . some_private_tag then assert ( match mode with Normal -> false | Counter_example _ -> true ) else unify_pat_types ~ refine loc env ( newgenty ( Tvariant row ) ) expected_ty ; let k arg = rp k { pat_desc = Tpat_variant ( l , arg , ref { row with row_more = newvar ( ) } ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } in begin match sarg , arg_type with Some p , [ ty ] -> type_pat p ty ( fun p -> k ( Some p ) ) | _ -> k None end | Ppat_record ( lid_sp_list , closed ) -> assert ( lid_sp_list <> [ ] ) ; let opath , record_ty = try let ( p0 , p , _ ) = extract_concrete_record ! env expected_ty in begin_def ( ) ; let ty = instance expected_ty in end_def ( ) ; generalize_structure ty ; Some ( p0 , p , true ) , ty with Not_found -> None , newvar ( ) in let type_label_pat ( label_lid , label , sarg ) k = begin_def ( ) ; let ( _ , ty_arg , ty_res ) = instance_label false label in begin try unify_pat_types ~ refine loc env ty_res ( instance record_ty ) with Error ( _loc , _env , Pattern_type_clash ( trace , _ ) ) -> raise ( Error ( label_lid . loc , ! env , Label_mismatch ( label_lid . txt , trace ) ) ) end ; end_def ( ) ; generalize_structure ty_res ; generalize_structure ty_arg ; type_pat sarg ty_arg ( fun arg -> k ( label_lid , label , arg ) ) in let k ' k lbl_pat_list = check_recordpat_labels loc lbl_pat_list closed ; rup k { pat_desc = Tpat_record ( lbl_pat_list , closed ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance record_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } in begin match mode with | Normal -> k ( wrap_disambiguate " This record pattern is expected to have " ( mk_expected expected_ty ) ( type_label_a_list loc false ! env type_label_pat opath lid_sp_list ) ( k ' ( fun x -> x ) ) ) | Counter_example { labels ; _ } -> type_label_a_list ~ labels loc false ! env type_label_pat opath lid_sp_list ( k ' k ) end | Ppat_array spl -> let ty_elt = newgenvar ( ) in begin_def ( ) ; let expected_ty = instance expected_ty in end_def ( ) ; generalize_structure expected_ty ; unify_pat_types ~ refine loc env ( Predef . type_array ty_elt ) expected_ty ; map_fold_cont ( fun p -> type_pat p ty_elt ) spl ( fun pl -> rp k { pat_desc = Tpat_array pl ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } ) | Ppat_or ( sp1 , sp2 ) -> let may_split , must_split = match get_splitting_mode mode with | None -> false , false | Some Backtrack_or -> true , true | Some ( Refine_or _ ) -> true , false in let state = save_state env in let split_or sp = assert may_split ; let typ pat = type_pat ~ exception_allowed pat expected_ty k in find_valid_alternative ( fun pat -> set_state state env ; typ pat ) sp in if must_split then split_or sp else begin let initial_pattern_variables = ! pattern_variables in let initial_module_variables = ! module_variables in let equation_level = ! gadt_equations_level in let outter_lev = get_current_level ( ) in begin_def ( ) ; let lev = get_current_level ( ) in gadt_equations_level := Some lev ; let env1 = ref ! env in let inside_or = enter_nonsplit_or mode in let p1 = try Some ( type_pat ~ exception_allowed ~ mode : inside_or sp1 expected_ty ~ env : env1 ( fun x -> x ) ) with Need_backtrack -> None in let p1_variables = ! pattern_variables in let p1_module_variables = ! module_variables in pattern_variables := initial_pattern_variables ; module_variables := initial_module_variables ; let env2 = ref ! env in let p2 = try Some ( type_pat ~ exception_allowed ~ mode : inside_or sp2 expected_ty ~ env : env2 ( fun x -> x ) ) with Need_backtrack -> None in end_def ( ) ; gadt_equations_level := equation_level ; let p2_variables = ! pattern_variables in List . iter ( fun { pv_type ; pv_loc ; _ } -> check_scope_escape pv_loc ! env1 outter_lev pv_type ) p1_variables ; List . iter ( fun { pv_type ; pv_loc ; _ } -> check_scope_escape pv_loc ! env2 outter_lev pv_type ) p2_variables ; begin match p1 , p2 with | None , None -> let inside_nonsplit_or = match get_splitting_mode mode with | None | Some Backtrack_or -> false | Some ( Refine_or { inside_nonsplit_or } ) -> inside_nonsplit_or in if inside_nonsplit_or then raise Need_backtrack else split_or sp | Some p , None | None , Some p -> rp k p | Some p1 , Some p2 -> let alpha_env = enter_orpat_variables loc ! env p1_variables p2_variables in pattern_variables := p1_variables ; module_variables := p1_module_variables ; rp k { pat_desc = Tpat_or ( p1 , alpha_pat alpha_env p2 , None ) ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } end end | Ppat_lazy sp1 -> let nv = newgenvar ( ) in unify_pat_types ~ refine loc env ( Predef . type_lazy_t nv ) expected_ty ; type_pat ~ mode ( : no_explosion mode ) sp1 nv ( fun p1 -> rp k { pat_desc = Tpat_lazy p1 ; pat_loc = loc ; pat_extra [ ] ; = pat_type = instance expected_ty ; pat_attributes = sp . ppat_attributes ; pat_env = ! env } ) | Ppat_constraint ( sp , sty ) -> begin_def ( ) ; let cty , force = Typetexp . transl_simple_type_delayed ! env sty in let ty = cty . ctyp_type in end_def ( ) ; generalize_structure ty ; let ty , expected_ty ' = instance ty , ty in unify_pat_types ~ refine loc env ty ( instance expected_ty ) ; type_pat ~ exception_allowed sp expected_ty ' ( fun p -> pattern_force := force :: ! pattern_force ; let extra = ( Tpat_constraint cty , loc , sp . ppat_attributes ) in let p = match p . pat_desc with Tpat_var ( id , s ) -> { p with pat_type = ty ; pat_desc = Tpat_alias ( { p with pat_desc = Tpat_any ; pat_attributes = [ ] } , id , s ) ; pat_extra = [ extra ] ; } | _ -> { p with pat_type = ty ; pat_extra = extra :: p . pat_extra } in k p ) | Ppat_type lid -> let ( path , p , ty ) = build_or_pat ! env loc lid in unify_pat_types ~ refine loc env ty ( instance expected_ty ) ; k { p with pat_extra = ( Tpat_type ( path , lid ) , loc , sp . ppat_attributes ) :: p . pat_extra } | Ppat_open ( lid , p ) -> let path , new_env = ! type_open Asttypes . Fresh ! env sp . ppat_loc lid in let new_env = ref new_env in type_pat ~ exception_allowed ~ env : new_env p expected_ty ( fun p -> env := Env . copy_local ! env ~ from :! new_env ; k { p with pat_extra ( = Tpat_open ( path , lid , ! new_env ) , loc , sp . ppat_attributes ) :: p . pat_extra } ) | Ppat_exception p -> if not exception_allowed then raise ( Error ( loc , ! env , Exception_pattern_disallowed ) ) else begin type_pat p Predef . type_exn ( fun p_exn -> rp k { pat_desc = Tpat_exception p_exn ; pat_loc = sp . ppat_loc ; pat_extra = [ ] ; pat_type = expected_ty ; pat_env = ! env ; pat_attributes = sp . ppat_attributes ; } ) end | Ppat_extension ext -> raise ( Error_forward ( Builtin_attributes . error_of_extension ext ) ) |
let type_pat ? exception_allowed ? no_existentials ( ? mode = Normal ) ( ? lev = get_current_level ( ) ) env sp expected_ty = Misc . protect_refs [ Misc . R ( gadt_equations_level , Some lev ) ] ( fun ( ) -> let r = type_pat ? exception_allowed ~ no_existentials ~ mode ~ env sp expected_ty ( fun x -> x ) in iter_pattern ( fun p -> p . pat_env <- ! env ) r ; r ) |
let partial_pred ~ lev ~ splitting_mode ( ? explode = 0 ) env expected_ty constrs labels p = let env = ref env in let state = save_state env in let mode = Counter_example { splitting_mode ; explosion_fuel = explode ; constrs ; labels ; } in try reset_pattern None true ; let typed_p = Ctype . with_passive_variants ( type_pat ~ lev ~ mode env p ) expected_ty in set_state state env ; Some typed_p with Error _ -> set_state state env ; None |
let check_partial ( ? lev = get_current_level ( ) ) env expected_ty loc cases = let explode = match cases with [ _ ] -> 5 | _ -> 0 in let splitting_mode = Refine_or { inside_nonsplit_or = false } in Parmatch . check_partial ( partial_pred ~ lev ~ splitting_mode ~ explode env expected_ty ) loc cases |
let check_unused ( ? lev = get_current_level ( ) ) env expected_ty cases = Parmatch . check_unused ( fun refute constrs labels spat -> match partial_pred ~ lev ~ splitting_mode : Backtrack_or ~ explode : 5 env expected_ty constrs labels spat with Some pat when refute -> raise ( Error ( spat . ppat_loc , env , Unrefuted_pattern pat ) ) | r -> r ) cases |
let iter_pattern_variables_type f : pattern_variable list -> unit = List . iter ( fun { pv_type ; _ } -> f pv_type ) |
let add_pattern_variables ? check ? check_as env pv = List . fold_right ( fun { pv_id ; pv_type ; pv_loc ; pv_as_var ; pv_attributes } env -> let check = if pv_as_var then check_as else check in Env . add_value ? check pv_id { val_type = pv_type ; val_kind = Val_reg ; Types . val_loc = pv_loc ; val_attributes = pv_attributes ; } env ) pv env |
let type_pattern ? exception_allowed ~ lev env spat scope expected_ty = reset_pattern scope true ; let new_env = ref env in let pat = type_pat ? exception_allowed ~ lev new_env spat expected_ty in let pvs = get_ref pattern_variables in let unpacks = get_ref module_variables in ( pat , ! new_env , get_ref pattern_force , pvs , unpacks ) |
let type_pattern_list no_existentials env spatl scope expected_tys allow = reset_pattern scope allow ; let new_env = ref env in let type_pat ( attrs , pat ) ty = Builtin_attributes . warning_scope ~ ppwarning : false attrs ( fun ( ) -> type_pat ~ no_existentials new_env pat ty ) in let patl = List . map2 type_pat spatl expected_tys in let pvs = get_ref pattern_variables in let unpacks = get_ref module_variables in let new_env = add_pattern_variables ! new_env pvs in ( patl , new_env , get_ref pattern_force , pvs , unpacks ) |
let type_class_arg_pattern cl_num val_env met_env l spat = reset_pattern None false ; let nv = newvar ( ) in let pat = type_pat ~ no_existentials : In_class_args ( ref val_env ) spat nv in if has_variants pat then begin Parmatch . pressure_variants val_env [ pat ] ; iter_pattern finalize_variant pat end ; List . iter ( fun f -> f ( ) ) ( get_ref pattern_force ) ; if is_optional l then unify_pat ( ref val_env ) pat ( type_option ( newvar ( ) ) ) ; let ( pv , met_env ) = List . fold_right ( fun { pv_id ; pv_type ; pv_loc ; pv_as_var ; pv_attributes } ( pv , env ) -> let check s = if pv_as_var then Warnings . Unused_var s else Warnings . Unused_var_strict s in let id ' = Ident . create_local ( Ident . name pv_id ) in ( ( id ' , pv_id , pv_type ) :: pv , Env . add_value id ' { val_type = pv_type ; val_kind = Val_ivar ( Immutable , cl_num ) ; val_attributes = pv_attributes ; Types . val_loc = pv_loc ; } ~ check env ) ) ! pattern_variables ( [ ] , met_env ) in let val_env = add_pattern_variables val_env ( get_ref pattern_variables ) in ( pat , pv , val_env , met_env ) |
let type_self_pattern cl_num privty val_env met_env par_env spat = let open Ast_helper in let spat = Pat . mk ( Ppat_alias ( Pat . mk ( Ppat_alias ( spat , mknoloc " selfpat " ) ) , -* mknoloc ( " selfpat " - ^ cl_num ) ) ) in reset_pattern None false ; let nv = newvar ( ) in let pat = type_pat ~ no_existentials : In_self_pattern ( ref val_env ) spat nv in List . iter ( fun f -> f ( ) ) ( get_ref pattern_force ) ; let meths = ref Meths . empty in let vars = ref Vars . empty in let pv = ! pattern_variables in pattern_variables := [ ] ; let ( val_env , met_env , par_env ) = List . fold_right ( fun { pv_id ; pv_type ; pv_loc ; pv_as_var ; pv_attributes } ( val_env , met_env , par_env ) -> let name = Ident . name pv_id in ( Env . enter_unbound_value name Val_unbound_self val_env , Env . add_value pv_id { val_type = pv_type ; val_kind = Val_self ( meths , vars , cl_num , privty ) ; val_attributes = pv_attributes ; Types . val_loc = pv_loc ; } ~ check ( : fun s -> if pv_as_var then Warnings . Unused_var s else Warnings . Unused_var_strict s ) met_env , Env . enter_unbound_value name Val_unbound_self par_env ) ) pv ( val_env , met_env , par_env ) in ( pat , meths , vars , val_env , met_env , par_env ) |
let delayed_checks = ref [ ] |
let reset_delayed_checks ( ) = delayed_checks := [ ] |
let add_delayed_check f = delayed_checks := ( f , Warnings . backup ( ) ) :: ! delayed_checks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.