text
stringlengths
0
601k
let name_ts_rule_body ( body : Tree_sitter_t . rule_body ) = let open Tree_sitter_t in let rec name_rule_body body = match body with | SYMBOL ident -> ident | STRING s -> Punct . to_alphanum s | BLANK -> " blank " | PATTERN pat -> " pat_ " ^ hash_string_hex pat | REPEAT x -> " rep_ " ^ name_rule_body x | REPEAT1 x -> " rep1_ " ^ name_rule_body x | CHOICE ( x :: _ ) -> " choice_ " ^ name_rule_body x | CHOICE [ ] -> " choice " | SEQ xs -> List . map name_rule_body xs |> String . concat " _ " | PREC ( p , x ) -> sprintf " prec_ % s_ " ( name_of_prec_value p ) ^ name_rule_body x | PREC_DYNAMIC ( n , x ) -> sprintf " pdyn_ % s_ " ( name_of_num_prec n ) ^ name_rule_body x | PREC_LEFT ( p , x ) -> sprintf " pleft_ % s_ " ( name_of_opt_prec_value p ) ^ name_rule_body x | PREC_RIGHT ( p , x ) -> sprintf " pright_ % s_ " ( name_of_opt_prec_value p ) ^ name_rule_body x | ALIAS alias -> name_rule_body alias . content | FIELD ( field_name , _x ) -> field_name | IMMEDIATE_TOKEN x -> " imm_tok_ " ^ name_rule_body x | TOKEN x -> " tok_ " ^ name_rule_body x in let full_name = name_rule_body body in Abbrev . words full_name
let name_rule_body body = let rec name_rule_body body = match body with | Symbol ident -> ident | Token token -> name_of_token token | Blank -> " blank " | Repeat body -> " rep_ " ^ name_rule_body body | Repeat1 body -> " rep1_ " ^ name_rule_body body | Choice ( ( _name , body ) :: _ ) -> " choice_ " ^ name_rule_body body | Choice [ ] -> " choice " | Optional body -> " opt_ " ^ name_rule_body body | Seq l -> List . map name_rule_body l |> String . concat " _ " | Alias ( ident , _ ) -> ident in let full_name = name_rule_body body in Abbrev . words full_name
let hash_rule_body body = let buf = Buffer . create 100 in let rec aux = function | Symbol ident | Alias ( ident , _ ) -> Buffer . add_string buf ident | Token token -> Buffer . add_string buf token . name | Blank -> Buffer . add_string buf " blank " | Repeat body -> Buffer . add_string buf " repeat ( " ; aux body ; Buffer . add_char buf ' ) ' | Repeat1 body -> Buffer . add_string buf " repeat1 ( " ; aux body ; Buffer . add_char buf ' ) ' | Choice cases -> Buffer . add_string buf " choice ( " ; List . iter ( fun ( name , _ ) -> bprintf buf " % s , " name ) cases ; Buffer . add_char buf ' ) ' | Optional body -> Buffer . add_string buf " optional ( " ; aux body ; Buffer . add_char buf ' ) ' | Seq l -> Buffer . add_string buf " seq ( " ; List . iter aux l ; Buffer . add_char buf ' ) ' in aux body ; let name = Buffer . contents buf in hash_string_hex name
let assign_case_names ? rule_name : opt_rule_name cases = let initial_naming = List . mapi ( fun pos rule_body -> let case_name = name_rule_body rule_body in let name = force_capitalize case_name in ( name , ( pos , rule_body ) ) ) cases in let grouped = Util_list . group_by_key initial_naming in let disambiguated_naming = List . map ( fun ( name , group ) -> match group with | [ ( pos , rule_body ) ] -> [ ( pos , ( name , rule_body ) ) ] | [ ] -> assert false | rule_bodies -> List . map ( fun ( pos , rule_body ) -> let hex_id = hash_rule_body rule_body in ( pos , ( name ^ " _ " ^ hex_id , rule_body ) ) ) rule_bodies ) grouped |> List . flatten |> List . sort ( fun ( a , _ ) ( b , _ ) -> compare a b ) |> List . map snd in let names = List . map fst disambiguated_naming in if not ( Util_list . is_deduplicated names ) then failwith ( sprintf " \ % s " ( match opt_rule_name with | None -> " < no name " > | Some name -> name ) ( List . map ( fun name -> " " ^ name ) names |> String . concat " \ n " ) ) ; disambiguated_naming
let again = ref false
let rec signature : Env . t -> Signature . t -> Signature . t = fun env sg -> let env = Env . open_signature sg env in signature_items env sg fun env s -> let open Signature in let items = List . map ( fun item -> match item with | Module ( r , m ) -> Module ( r , module_ env m ) | ModuleType mt -> ModuleType ( module_type env mt ) | Include i -> Include ( include_ env i ) | item -> item ) s . items in { s with items } match m . type_ with | Alias _ -> m | ModuleType expr -> { m with type_ = ModuleType ( module_type_expr env ( m . id :> Id . Signature . t ) expr ) ; } match m . expr with | None -> m | Some expr -> { m with expr = Some ( module_type_expr env ( m . id :> Id . Signature . t ) expr ) ; } let open Odoc_model . Lang . ModuleType in let p , strengthen = match t . t_desc with ModPath p -> ( p , false ) | StructInclude p -> ( p , true ) in let cp = Component . Of_Lang . ( module_path ( empty ( ) ) p ) in let open Expand_tools in let open Utils . ResultMonad in aux_expansion_of_module_alias env ~ strengthen cp >>= handle_expansion env id >>= fun ( _env , e ) -> Ok e match expr with | Path _ -> expr | Functor ( Unit , expr ) -> Functor ( Unit , module_type_expr env id expr ) | Functor ( Named p , expr ) -> let env = Env . add_functor_parameter ( Named p ) env in Functor ( Named ( functor_parameter env p ) , module_type_expr env id expr ) | Signature sg -> Signature ( signature env sg ) | With w -> With { w with w_expr = u_module_type_expr env id w . w_expr } | TypeOf t -> ( match module_type_expr_typeof env id t with | Ok e -> let se = Lang_of . ( simple_expansion ( empty ( ) ) id e ) in TypeOf { t with t_expansion = Some ( simple_expansion env se ) } | Error e when Errors . is_unexpanded_module_type_of ( e :> Errors . Tools_error . any ) -> again := true ; expr | Error _e -> expr ) match expr with | Path _ -> expr | Signature sg -> Signature ( signature env sg ) | With ( subs , w ) -> With ( subs , u_module_type_expr env id w ) | TypeOf t -> ( match module_type_expr_typeof env id t with | Ok e -> let se = Lang_of . ( simple_expansion ( empty ( ) ) id e ) in TypeOf { t with t_expansion = Some ( simple_expansion env se ) } | Error e when Errors . is_unexpanded_module_type_of ( e :> Errors . Tools_error . any ) -> again := true ; expr | Error _e -> expr ) { p with expr = module_type_expr env ( p . id :> Id . Signature . t ) p . expr } Env . t -> ModuleType . simple_expansion -> ModuleType . simple_expansion = fun env -> function | Signature sg -> Signature ( signature env sg ) | Functor ( Named n , sg ) -> Functor ( Named ( functor_parameter env n ) , simple_expansion env sg ) | Functor ( Unit , sg ) -> Functor ( Unit , simple_expansion env sg ) let decl = let env = Env . close_signature i . expansion . content env in match i . decl with | Alias _ -> i . decl | ModuleType t -> ModuleType ( u_module_type_expr env i . parent t ) in let content = let { Include . content ; _ } = i . expansion in signature_items env content in { i with expansion = { i . expansion with content } ; decl }
let signature env = let rec loop sg = again := false ; let sg ' = signature env sg in Tools . reset_caches ( ) ; if ! again then if sg ' = sg then sg else loop sg ' else sg ' in loop
module Variant_kind = struct type t = Polymorphic | Non_polymorphic let to_string_prefix = function | Polymorphic -> " ` " | Non_polymorphic -> " " end
module Result = struct type t = | Obj_boxed_traversable | Obj_boxed_not_traversable | Obj_immediate | Obj_immediate_but_should_be_boxed | Unit | Abstract of Path . t | Array of Types . type_expr * Env . t | List of Types . type_expr * Env . t | Tuple of Types . type_expr list * Env . t | Char | Int | Float | Float_array | Constant_constructor of string * Variant_kind . t | Non_constant_constructor of Path . t * Types . constructor_declaration list * Types . type_expr list * Types . type_expr list * Env . t * Variant_kind . t | Record of Path . t * Types . type_expr list * Types . type_expr list * Types . label_declaration list * Types . record_representation * Env . t | Open | Ref of Types . type_expr * Env . t | String | Closure | Lazy | Object | Abstract_tag | Format6 | Stdlib_set of { env : Env . t ; element_ty : Types . type_expr ; } | Stdlib_map of { key_env : Env . t ; key_ty : Types . type_expr ; datum_env : Env . t ; datum_ty : Types . type_expr ; } | Stdlib_hashtbl of { key_env : Env . t ; key_ty : Types . type_expr ; datum_env : Env . t ; datum_ty : Types . type_expr ; } | Custom | Module of Types . module_type | Unknown let to_string = function | Obj_boxed_traversable -> " Obj_boxed_traversable " | Obj_boxed_not_traversable -> " Obj_boxed_not_traversable " | Obj_immediate -> " Obj_immediate " | Obj_immediate_but_should_be_boxed -> " Obj_immediate_but_should_be_boxed " | Unit -> " Unit " | Abstract _ -> " Abstract " | Array _ -> " Array " | List _ -> " List " | Tuple _ -> " Tuple " | Char -> " Char " | Int -> " Int " | Float -> " Float " | Float_array -> " Float_array " | Constant_constructor _ -> " Constant_constructor " | Non_constant_constructor _ -> " Non_constant_constructor " | Record _ -> " Record " | Open -> " Open " | Ref _ -> " Ref " | String -> " String " | Closure -> " Closure " | Lazy -> " Lazy " | Object -> " Object " | Abstract_tag -> " Abstract_tag " | Format6 -> " Format6 " | Stdlib_set _ -> " Stdlib . Set " | Stdlib_map _ -> " Stdlib . Map " | Stdlib_hashtbl _ -> " Stdlib . Hashtbl " | Custom -> " Custom " | Module _ -> " Module " | Unknown -> " Unknown " end
module Make ( D : Debugger . S ) ( Cmt_cache : Cmt_cache_intf . S ) = struct module V = D . Value module Abstraction_breaker = Abstraction_breaker . Make ( D ) ( Cmt_cache ) type maybe_boxed = Unboxed of V . t | Boxed of V . t | Absent type t = { abstraction_breaker : Abstraction_breaker . t ; cmt_cache : Cmt_cache . t ; } let create ~ cmt_cache = { abstraction_breaker = Abstraction_breaker . create ~ cmt_cache ; cmt_cache ; } let extract_constant_ctors ~ cases = let constant_ctors , _ = List . fold_left cases ~ init ( [ ] , : 0 ) ~ f ( : fun ( constant_ctors , next_ctor_number ) ctor_decl -> let ident = ctor_decl . Types . cd_id in match ctor_decl . Types . cd_args with | Cstr_tuple [ ] -> ( next_ctor_number , ident ) :: constant_ctors , next_ctor_number + 1 | Cstr_tuple _ | Cstr_record _ -> constant_ctors , next_ctor_number ) in constant_ctors let format6_path = Path . ( Pdot ( Pident ( Ident . create_persistent " CamlinternalFormatBasics " ) , " format6 " , 0 ) ) let check_predef_paths ~ path ~ args ~ env ~ scrutinee : Result . t option = if Path . same path Predef . path_array then match scrutinee with | Unboxed _ -> Some Obj_immediate_but_should_be_boxed | Absent | Boxed _ -> match args with | [ arg ] -> Some ( Array ( arg , env ) ) | _ -> Some Obj_boxed_traversable else if Path . same path Predef . path_list then match args with | [ arg ] -> Some ( List ( arg , env ) ) | _ -> match scrutinee with | Unboxed _ -> Some Obj_immediate | Boxed _ -> Some Obj_boxed_traversable | Absent -> Some Unknown else if Path . same path Predef . path_int then match scrutinee with | Unboxed _ | Absent -> Some Int | Boxed _ -> Some Obj_boxed_traversable else if Path . same path Predef . path_char then match scrutinee with | Unboxed _ | Absent -> Some Char | Boxed _ -> Some Obj_boxed_traversable else if Path . same path Predef . path_unit then match scrutinee with | Unboxed _ | Absent -> Some Unit | Boxed _ -> Some Obj_boxed_traversable else if Path . same path format6_path then match scrutinee with | Unboxed _ -> Some Obj_immediate | Boxed _ -> Some Format6 | Absent -> Some Unknown else None let check_special_cases _t env ( path : Path . t ) ~ args : Result . t option = match path with | Pdot ( Papply ( Pdot ( Pident mod_name , functor_name , _ ) , applied_to ) , " t " , _ ) -> begin match Ident . name mod_name , functor_name with | " Stdlib__set " , " Make " -> begin match args with | [ ] -> let element_ty_path : Path . t = Pdot ( applied_to , " t " , 0 ) in let type_desc : Types . type_desc = Tconstr ( element_ty_path , [ ] , ref Types . Mnil ) in let element_ty = Btype . newgenty type_desc in Some ( Stdlib_set { env ; element_ty ; } ) | _ -> None end | " Stdlib__map " , " Make " -> begin match args with | [ datum_ty ] -> let key_ty_path : Path . t = Pdot ( applied_to , " t " , 0 ) in let type_desc : Types . type_desc = Tconstr ( key_ty_path , [ ] , ref Types . Mnil ) in let key_ty = Btype . newgenty type_desc in Some ( Stdlib_map { key_env = env ; key_ty ; datum_env = env ; datum_ty ; } ) | _ -> None end | " Stdlib__hashtbl " , " Make " -> begin match args with | [ datum_ty ] -> let key_ty_path : Path . t = Pdot ( applied_to , " t " , 0 ) in let type_desc : Types . type_desc = Tconstr ( key_ty_path , [ ] , ref Types . Mnil ) in let key_ty = Btype . newgenty type_desc in Some ( Stdlib_hashtbl { key_env = env ; key_ty ; datum_env = env ; datum_ty ; } ) | _ -> None end | _ , _ -> None end | _ -> None let rec examine_type_expr t ~ formatter ~ paths_visited_so_far ~ type_expr ~ env ~ scrutinee : Result . t = let type_expr = Ctype . expand_head env type_expr in match type_expr . Types . desc with | Types . Tconstr ( path , args , _abbrev_memo_ref ) -> begin match check_predef_paths ~ path ~ args ~ env ~ scrutinee with | Some result -> result | None -> if debug then Printf . printf " examine_type_expr : Env . find_type ' % s ' : " ( print_path path ) ; begin match try Some ( Env . find_type path env ) with Not_found -> None with | None -> if debug then Printf . printf " not found . \ n " ; %! begin match scrutinee with | Absent -> Unknown | Unboxed _ -> Obj_immediate | Boxed _ -> if debug then Printf . printf " examine_type_expr error case 1 , load path is : % s \ n " %! ( String . concat " , " ! Config . load_path ) ; Obj_boxed_traversable end | Some type_decl -> if debug then Printf . printf " found . \ n " ; %! examine_type_decl t ~ formatter ~ paths_visited_so_far ~ type_expr ~ env ~ path ~ args ~ type_decl ~ scrutinee end end | Types . Tvariant row_desc -> begin match scrutinee with | Absent -> Unknown | Boxed _ -> if debug then Printf . printf " examine_type_expr error case 2 \ n " ; %! Obj_boxed_traversable | Unboxed scrutinee -> let ctor_names_and_hashes = let labels = List . map row_desc . Types . row_fields ~ f : fst in List . map labels ~ f ( : fun label -> label , Btype . hash_variant label ) in match V . int scrutinee with | None -> Obj_immediate | Some desired_hash -> let matches = List . filter ctor_names_and_hashes ~ f ( : fun ( _ctor_name , hash ) -> hash = desired_hash ) in begin match matches with | [ ( ctor_name , _hash ) ] -> Constant_constructor ( ctor_name , Vk . Polymorphic ) | _ :: _ | [ ] -> Obj_immediate end end | Types . Ttuple component_types -> begin match scrutinee with | Absent | Boxed _ -> Tuple ( component_types , env ) | Unboxed _ -> Obj_immediate_but_should_be_boxed end | Types . Tarrow _ -> begin match scrutinee with | Absent | Boxed _ -> Closure | Unboxed _ -> Obj_immediate_but_should_be_boxed end | Types . Tvar _ | Types . Tobject _ | Types . Tfield _ | Types . Tnil | Types . Tsubst _ | Types . Tunivar _ | Types . Tpoly _ | Types . Tpackage _ -> begin match scrutinee with | Absent | Boxed _ -> let what = match ( Btype . repr type_expr ) . Types . desc with | Types . Tvar _ -> " Tvar " | Types . Tobject _ -> " Tobject " | Types . Tfield _ -> " Tfield " | Types . Tnil -> " Tnil " | Types . Tsubst _ -> " Tsubst " | Types . Tunivar _ -> " Tunivar " | Types . Tpoly _ -> " Tpoly " | Types . Tpackage _ -> " Tpackage " | _ -> assert false in if debug then Printf . printf " examine_type_expr error case 3 % s \ n " %! what ; Obj_boxed_traversable | Unboxed _ -> Obj_immediate end | Types . Tlink _type_expr -> assert false and examine_type_decl t ~ formatter ~ paths_visited_so_far ~ type_expr ~ env ~ path ~ args ~ type_decl ~ scrutinee : Result . t = let params = type_decl . Types . type_params in if List . length params <> List . length args then begin if debug then Printf . printf " type params / args don ' t match \ n " ; %! Abstract path end else begin match type_decl . Types . type_manifest with | Some type_expr -> examine_type_expr t ~ formatter ~ paths_visited_so_far ~ type_expr ~ env ~ scrutinee | None -> begin match type_decl . Types . type_kind with | Types . Type_variant cases -> begin match scrutinee with | Absent -> Unknown | Boxed _ -> let kind = Vk . Non_polymorphic in Non_constant_constructor ( path , cases , params , args , env , kind ) | Unboxed scrutinee -> let constant_ctors = extract_constant_ctors ~ cases in match V . int scrutinee with | None -> Obj_immediate | Some value -> if value >= 0 && value < List . length constant_ctors then let ident = try Some ( List . assoc value constant_ctors ) with Not_found -> None in begin match ident with | Some ident -> Constant_constructor ( Ident . name ident , Vk . Non_polymorphic ) | None -> Obj_immediate end else Obj_immediate end | Types . Type_abstract -> if List . mem path ~ set : paths_visited_so_far then begin if debug then begin Printf . printf " loop resolving % s \ n " %! ( print_path path ) end ; Abstract path end else begin let paths_visited_so_far = path :: paths_visited_so_far in discover_manifest t ~ formatter ~ paths_visited_so_far ~ type_expr ~ path ~ args ~ env ~ scrutinee end | Types . Type_record ( field_decls , record_repr ) -> begin match scrutinee with | Absent | Boxed _ -> if scrutinee <> Absent && List . length field_decls = 1 && List . length args = 1 && Ident . name ( ( List . hd field_decls ) . Types . ld_id ) = " contents " && Path . name path = " Pervasives . ref " then Ref ( List . hd args , env ) else Record ( path , params , args , field_decls , record_repr , env ) | Unboxed _ -> Obj_immediate end | Types . Type_open -> Open end end and discover_manifest t ~ formatter ~ paths_visited_so_far ~ type_expr ~ path ~ args ~ env ~ scrutinee : Result . t = match check_special_cases t env path ~ args with | Some result -> result | None -> let manifest = Abstraction_breaker . find_manifest_of_abstract_type t . abstraction_breaker ~ formatter ~ path ~ env in match manifest with | None -> Abstract path | Some ( path , type_decl , env ) -> examine_type_decl t ~ formatter ~ paths_visited_so_far ~ type_expr ~ env ~ path ~ args ~ type_decl ~ scrutinee let find_type_information t ~ formatter ~ type_expr_and_env ~ scrutinee = if debug then begin Format . printf " find_type_information starting ( scrutinee % a ) , \ type info present ? % s \ n " %! V . print scrutinee ( match type_expr_and_env with None -> " no " | Some _ -> " yes " ) end ; let absent = V . is_null scrutinee in let result : Result . t = try if absent || V . is_int scrutinee then match type_expr_and_env with | None -> if absent then Unknown else Obj_immediate | Some ( type_expr , env ) -> examine_type_expr t ~ formatter ~ paths_visited_so_far [ ] : ~ type_expr ~ env ~ scrutinee ( : Unboxed scrutinee ) else let tag = V . tag_exn scrutinee in match tag with | tag when tag < Obj . lazy_tag -> begin match type_expr_and_env with | None -> Obj_boxed_traversable | Some ( type_expr , env ) -> examine_type_expr t ~ formatter ~ paths_visited_so_far [ ] : ~ type_expr ~ env ~ scrutinee ( : Boxed scrutinee ) end | tag when tag = Obj . string_tag -> String | tag when tag = Obj . double_tag -> Float | tag when ( tag = Obj . closure_tag || tag = Obj . infix_tag ) -> Closure | tag when tag = Obj . lazy_tag -> Lazy | tag when tag = Obj . object_tag -> Object | tag when tag = Obj . forward_tag -> Obj_boxed_traversable | tag when tag = Obj . abstract_tag -> Abstract_tag | tag when tag = Obj . custom_tag -> Custom | tag when tag = Obj . double_array_tag -> Float_array | tag when tag < Obj . no_scan_tag -> Obj_boxed_traversable | _tag -> Obj_boxed_not_traversable with _ -> Obj_immediate in if debug then begin Printf . printf " find_type_information returning % s \ n " %! ( Result . to_string result ) end ; result let find_type_information t ~ formatter ( type_and_env : ( Cmt_file . core_or_module_type * Env . t ) option ) ~ scrutinee = match type_and_env with | None -> find_type_information t ~ formatter ~ type_expr_and_env : None ~ scrutinee | Some ( Core type_expr , env ) -> let type_expr_and_env = Some ( type_expr , env ) in find_type_information t ~ formatter ~ type_expr_and_env ~ scrutinee | Some ( Module mod_type , _env ) -> if V . is_null scrutinee then Unknown else if V . is_int scrutinee then Obj_immediate else let tag = V . tag_exn scrutinee in if tag = 0 then Module mod_type else if tag < Obj . lazy_tag then Obj_boxed_traversable else Obj_boxed_not_traversable end
module type TYPE = sig val _type : env -> ( Loc . t , Loc . t ) Ast . Type . t val type_identifier : env -> ( Loc . t , Loc . t ) Ast . Identifier . t val type_params : env -> ( Loc . t , Loc . t ) Ast . Type . TypeParams . t option val type_args : env -> ( Loc . t , Loc . t ) Ast . Type . TypeArgs . t option val generic : env -> Loc . t * ( Loc . t , Loc . t ) Ast . Type . Generic . t val _object : is_class : bool -> env -> Loc . t * ( Loc . t , Loc . t ) Type . Object . t val interface_helper : env -> ( Loc . t * ( Loc . t , Loc . t ) Ast . Type . Generic . t ) list * ( Loc . t * ( Loc . t , Loc . t ) Ast . Type . Object . t ) val function_param_list : env -> ( Loc . t , Loc . t ) Type . Function . Params . t val annotation : env -> ( Loc . t , Loc . t ) Ast . Type . annotation val annotation_opt : env -> ( Loc . t , Loc . t ) Ast . Type . annotation_or_hint val predicate_opt : env -> ( Loc . t , Loc . t ) Ast . Type . Predicate . t option val annotation_and_predicate_opt : env -> ( Loc . t , Loc . t ) Ast . Type . annotation_or_hint * ( Loc . t , Loc . t ) Ast . Type . Predicate . t option end
module Type ( Parse : Parser_common . PARSER ) : TYPE = struct type param_list_or_type = | ParamList of ( Loc . t , Loc . t ) Type . Function . Params . t ' | Type of ( Loc . t , Loc . t ) Type . t let maybe_variance env = let loc = Peek . loc env in match Peek . token env with | T_PLUS -> let leading = Peek . comments env in Eat . token env ; Some ( loc , { Variance . kind = Variance . Plus ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) | T_MINUS -> let leading = Peek . comments env in Eat . token env ; Some ( loc , { Variance . kind = Variance . Minus ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) | _ -> None let rec _type env = union env and annotation env = if not ( should_parse_types env ) then error env Parse_error . UnexpectedTypeAnnotation ; with_loc ( fun env -> Expect . token env T_COLON ; _type env ) env and union env = let leading = if Peek . token env = T_BIT_OR then ( let leading = Peek . comments env in Eat . token env ; leading ) else [ ] in let left = intersection env in union_with env ~ leading left and union_with = let rec unions leading acc env = match Peek . token env with | T_BIT_OR -> Expect . token env T_BIT_OR ; unions leading ( intersection env :: acc ) env | _ -> ( match List . rev acc with | t0 :: t1 :: ts -> Type . Union { Type . Union . types = ( t0 , t1 , ts ) ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } | _ -> assert false ) in fun env ( ? leading = [ ] ) left -> if Peek . token env = T_BIT_OR then with_loc ~ start_loc ( : fst left ) ( unions leading [ left ] ) env else left and intersection env = let leading = if Peek . token env = T_BIT_AND then ( let leading = Peek . comments env in Eat . token env ; leading ) else [ ] in let left = anon_function_without_parens env in intersection_with env ~ leading left and intersection_with = let rec intersections leading acc env = match Peek . token env with | T_BIT_AND -> Expect . token env T_BIT_AND ; intersections leading ( anon_function_without_parens env :: acc ) env | _ -> ( match List . rev acc with | t0 :: t1 :: ts -> Type . Intersection { Type . Intersection . types = ( t0 , t1 , ts ) ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } | _ -> assert false ) in fun env ( ? leading = [ ] ) left -> if Peek . token env = T_BIT_AND then with_loc ~ start_loc ( : fst left ) ( intersections leading [ left ] ) env else left and anon_function_without_parens env = let param = prefix env in anon_function_without_parens_with env param and anon_function_without_parens_with env param = match Peek . token env with | T_ARROW when not ( no_anon_function_type env ) -> let start_loc , tparams , params = let param = anonymous_function_param env param in ( fst param , None , ( fst param , { Ast . Type . Function . Params . params = [ param ] ; this_ = None ; rest = None ; comments = None ; } ) ) in function_with_params env start_loc tparams params | _ -> param and prefix env = match Peek . token env with | T_PLING -> with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_PLING ; Type . Nullable { Type . Nullable . argument = prefix env ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env | _ -> postfix env and postfix env = let t = primary env in postfix_with env t and postfix_with ( ? in_optional_indexed_access = false ) env t = if Peek . is_line_terminator env then t else match Peek . token env with | T_PLING_PERIOD -> Eat . token env ; if Peek . token env <> T_LBRACKET then error env Parse_error . InvalidOptionalIndexedAccess ; Expect . token env T_LBRACKET ; postfix_brackets ~ in_optional_indexed_access : true ~ optional_indexed_access : true env t | T_LBRACKET -> Eat . token env ; postfix_brackets ~ in_optional_indexed_access ~ optional_indexed_access : false env t | T_PERIOD -> ( match Peek . ith_token ~ i : 1 env with | T_LBRACKET -> error env ( Parse_error . InvalidIndexedAccess { has_bracket = true } ) ; Expect . token env T_PERIOD ; Expect . token env T_LBRACKET ; postfix_brackets ~ in_optional_indexed_access ~ optional_indexed_access : false env t | _ -> error env ( Parse_error . InvalidIndexedAccess { has_bracket = false } ) ; t ) | _ -> t and postfix_brackets ~ in_optional_indexed_access ~ optional_indexed_access env t = let t = with_loc ~ start_loc ( : fst t ) ( fun env -> if ( not optional_indexed_access ) && Eat . maybe env T_RBRACKET then let trailing = Eat . trailing_comments env in Type . Array { Type . Array . argument = t ; comments = Flow_ast_utils . mk_comments_opt ~ trailing ( ) ; } else let index = _type env in Expect . token env T_RBRACKET ; let trailing = Eat . trailing_comments env in let indexed_access = { Type . IndexedAccess . _object = t ; index ; comments = Flow_ast_utils . mk_comments_opt ~ trailing ( ) ; } in if in_optional_indexed_access then Type . OptionalIndexedAccess { Type . OptionalIndexedAccess . indexed_access ; optional = optional_indexed_access ; } else Type . IndexedAccess indexed_access ) env in postfix_with env ~ in_optional_indexed_access t and primary env = let loc = Peek . loc env in match Peek . token env with | T_MULT -> let leading = Peek . comments env in Expect . token env T_MULT ; let trailing = Eat . trailing_comments env in ( loc , Type . Exists ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_LESS_THAN -> _function env | T_LPAREN -> function_or_group env | T_LCURLY | T_LCURLYBAR -> let loc , o = _object env ~ is_class : false ~ allow_exact : true ~ allow_spread : true in ( loc , Type . Object o ) | T_INTERFACE -> with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_INTERFACE ; let extends , body = interface_helper env in Type . Interface { Type . Interface . extends ; body ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env | T_TYPEOF -> with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_TYPEOF ; Type . Typeof { Type . Typeof . argument = primary env ; internal = false ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env | T_LBRACKET -> tuple env | T_IDENTIFIER _ | T_STATIC -> let loc , g = generic env in ( loc , Type . Generic g ) | T_STRING ( loc , value , raw , octal ) -> if octal then strict_error env Parse_error . StrictOctalLiteral ; let leading = Peek . comments env in Expect . token env ( T_STRING ( loc , value , raw , octal ) ) ; let trailing = Eat . trailing_comments env in ( loc , Type . StringLiteral { Ast . StringLiteral . value ; raw ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) | T_NUMBER_SINGLETON_TYPE { kind ; value ; raw } -> let leading = Peek . comments env in Expect . token env ( T_NUMBER_SINGLETON_TYPE { kind ; value ; raw } ) ; let trailing = Eat . trailing_comments env in if kind = LEGACY_OCTAL then strict_error env Parse_error . StrictOctalLiteral ; ( loc , Type . NumberLiteral { Ast . NumberLiteral . value ; raw ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) | T_BIGINT_SINGLETON_TYPE { kind ; approx_value ; raw } -> let bigint = raw in let leading = Peek . comments env in Expect . token env ( T_BIGINT_SINGLETON_TYPE { kind ; approx_value ; raw } ) ; let trailing = Eat . trailing_comments env in ( loc , Type . BigIntLiteral { Ast . BigIntLiteral . approx_value ; bigint ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) | ( T_TRUE | T_FALSE ) as token -> let leading = Peek . comments env in Expect . token env token ; let trailing = Eat . trailing_comments env in let value = token = T_TRUE in ( loc , Type . BooleanLiteral { BooleanLiteral . value ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) | _ -> ( match primitive env with | Some t -> ( loc , t ) | None -> error_unexpected env ; ( loc , Type . Any None ) ) and is_primitive = function | T_ANY_TYPE | T_MIXED_TYPE | T_EMPTY_TYPE | T_BOOLEAN_TYPE _ | T_NUMBER_TYPE | T_BIGINT_TYPE | T_STRING_TYPE | T_SYMBOL_TYPE | T_VOID_TYPE | T_NULL -> true | _ -> false and primitive env = let leading = Peek . comments env in let token = Peek . token env in match token with | T_ANY_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Any ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_MIXED_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Mixed ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_EMPTY_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Empty ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_BOOLEAN_TYPE _ -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Boolean ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_NUMBER_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Number ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_BIGINT_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . BigInt ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_STRING_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . String ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_SYMBOL_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Symbol ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_VOID_TYPE -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Void ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | T_NULL -> Eat . token env ; let trailing = Eat . trailing_comments env in Some ( Type . Null ( Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) ) | _ -> None and tuple = let rec types env acc = match Peek . token env with | T_EOF | T_RBRACKET -> List . rev acc | _ -> let acc = _type env :: acc in if Peek . token env <> T_RBRACKET then Expect . token env T_COMMA ; types env acc in fun env -> with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_LBRACKET ; let tl = types ( with_no_anon_function_type false env ) [ ] in Expect . token env T_RBRACKET ; let trailing = Eat . trailing_comments env in Type . Tuple { Type . Tuple . types = tl ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) env and anonymous_function_param _env annot = ( fst annot , let open Type . Function . Param in { name = None ; annot ; optional = false } ) and function_param_with_id env = with_loc ( fun env -> Eat . push_lex_mode env Lex_mode . NORMAL ; let name = Parse . identifier env in Eat . pop_lex_mode env ; if not ( should_parse_types env ) then error env Parse_error . UnexpectedTypeAnnotation ; let optional = Eat . maybe env T_PLING in Expect . token env T_COLON ; let annot = _type env in { Type . Function . Param . name = Some name ; annot ; optional } ) env and function_param_list_without_parens = let param env = match Peek . ith_token ~ i : 1 env with | T_COLON | T_PLING -> function_param_with_id env | _ -> let annot = _type env in anonymous_function_param env annot in let rec param_list env this_ acc = match Peek . token env with | ( T_EOF | T_ELLIPSIS | T_RPAREN ) as t -> let rest = if t = T_ELLIPSIS then let rest = with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_ELLIPSIS ; { Type . Function . RestParam . argument = param env ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in Some rest else None in { Ast . Type . Function . Params . params = List . rev acc ; rest ; this_ ; comments = None ; } | T_IDENTIFIER { raw = " this " ; _ } when Peek . ith_token ~ i : 1 env == T_COLON || Peek . ith_token ~ i : 1 env == T_PLING -> if this_ <> None || acc <> [ ] then error env Parse_error . ThisParamMustBeFirst ; let this_ = with_loc ( fun env -> let leading = Peek . comments env in Eat . token env ; if Peek . token env == T_PLING then error env Parse_error . ThisParamMayNotBeOptional ; { Type . Function . ThisParam . annot = annotation env ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in if Peek . token env <> T_RPAREN then Expect . token env T_COMMA ; param_list env ( Some this_ ) acc | _ -> let acc = param env :: acc in if Peek . token env <> T_RPAREN then Expect . token env T_COMMA ; param_list env this_ acc in fun env -> param_list env None and function_param_list env = with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_LPAREN ; let params = function_param_list_without_parens env [ ] in let internal = Peek . comments env in Expect . token env T_RPAREN ; let trailing = Eat . trailing_comments env in { params with Ast . Type . Function . Params . comments = Flow_ast_utils . mk_comments_with_internal_opt ~ leading ~ trailing ~ internal ( ) ; } ) env and param_list_or_type env = let leading = Peek . comments env in Expect . token env T_LPAREN ; let ret = let env = with_no_anon_function_type false env in match Peek . token env with | T_EOF | T_ELLIPSIS -> ParamList ( function_param_list_without_parens env [ ] ) | T_RPAREN -> ParamList { Ast . Type . Function . Params . this_ = None ; params = [ ] ; rest = None ; comments = None ; } | T_IDENTIFIER _ | T_STATIC -> function_param_or_generic_type env | token when is_primitive token -> ( match Peek . ith_token ~ i : 1 env with | T_PLING | T_COLON -> ParamList ( function_param_list_without_parens env [ ] ) | _ -> Type ( _type env ) ) | _ -> Type ( _type env ) in let ret = match ret with | ParamList _ -> ret | Type _ when no_anon_function_type env -> ret | Type t -> ( match Peek . token env with | T_RPAREN -> if Peek . ith_token ~ i : 1 env = T_ARROW then let param = anonymous_function_param env t in ParamList ( function_param_list_without_parens env [ param ] ) else Type t | T_COMMA -> Expect . token env T_COMMA ; let param = anonymous_function_param env t in ParamList ( function_param_list_without_parens env [ param ] ) | _ -> ret ) in let internal = Peek . comments env in Expect . token env T_RPAREN ; let trailing = Eat . trailing_comments env in let ret = match ret with | ParamList params -> ParamList { params with Ast . Type . Function . Params . comments = Flow_ast_utils . mk_comments_with_internal_opt ~ leading ~ trailing ~ internal ( ) ; } | Type t -> Type ( add_comments t leading trailing ) in ret and function_param_or_generic_type env = match Peek . ith_token ~ i : 1 env with | T_PLING | T_COLON -> ParamList ( function_param_list_without_parens env [ ] ) | _ -> let id = type_identifier env in Type ( generic_type_with_identifier env id |> postfix_with env |> anon_function_without_parens_with env |> intersection_with env |> union_with env ) and function_or_group env = let start_loc = Peek . loc env in match with_loc param_list_or_type env with | loc , ParamList params -> function_with_params env start_loc None ( loc , params ) | _ , Type _type -> _type and _function env = let start_loc = Peek . loc env in let tparams = type_params_remove_trailing env ( type_params env ) in let params = function_param_list env in function_with_params env start_loc tparams params and function_with_params env start_loc tparams ( params : ( Loc . t , Loc . t ) Ast . Type . Function . Params . t ) = with_loc ~ start_loc ( fun env -> Expect . token env T_ARROW ; let return = _type env in let open Type in Function { Function . params ; return ; tparams ; comments = None } ) env and _object = let methodish env start_loc tparams = with_loc ~ start_loc ( fun env -> let params = function_param_list env in Expect . token env T_COLON ; let return = _type env in { Type . Function . params ; return ; tparams ; comments = None } ) env in let method_property env start_loc static key ~ leading = let key = object_key_remove_trailing env key in let tparams = type_params_remove_trailing env ( type_params env ) in let value = methodish env start_loc tparams in let value = ( fst value , Type . Function ( snd value ) ) in let open Type . Object in Property ( fst value , { Property . key ; value = Property . Init value ; optional = false ; static = static <> None ; proto = false ; _method = true ; variance = None ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) in let call_property env start_loc static ~ leading = let prop = with_loc ~ start_loc ( fun env -> let start_loc = Peek . loc env in let tparams = type_params_remove_trailing env ( type_params env ) in let value = methodish env start_loc tparams in let open Type . Object . CallProperty in { value ; static = static <> None ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in Type . Object . CallProperty prop in let init_property env start_loc ~ variance ~ static ~ proto ~ leading key = ignore proto ; if not ( should_parse_types env ) then error env Parse_error . UnexpectedTypeAnnotation ; let prop = with_loc ~ start_loc ( fun env -> let optional = Eat . maybe env T_PLING in Expect . token env T_COLON ; let value = _type env in let open Type . Object . Property in { key ; value = Init value ; optional ; static = static <> None ; proto = proto <> None ; _method = false ; variance ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in Type . Object . Property prop in let getter_or_setter ~ is_getter ~ leading env start_loc static key = let prop = with_loc ~ start_loc ( fun env -> let key_loc , key = key in let key = object_key_remove_trailing env key in let value = methodish env start_loc None in let _ , { Type . Function . params ; _ } = value in ( match ( is_getter , params ) with | true , ( _ , { Type . Function . Params . this_ = Some _ ; _ } ) -> error_at env ( key_loc , Parse_error . GetterMayNotHaveThisParam ) | false , ( _ , { Type . Function . Params . this_ = Some _ ; _ } ) -> error_at env ( key_loc , Parse_error . SetterMayNotHaveThisParam ) | ( true , ( _ , { Type . Function . Params . params = [ ] ; rest = None ; this_ = None ; comments = _ ; } ) ) -> ( ) | false , ( _ , { Type . Function . Params . rest = Some _ ; _ } ) -> error_at env ( key_loc , Parse_error . SetterArity ) | false , ( _ , { Type . Function . Params . params = [ _ ] ; _ } ) -> ( ) | true , _ -> error_at env ( key_loc , Parse_error . GetterArity ) | false , _ -> error_at env ( key_loc , Parse_error . SetterArity ) ) ; let open Type . Object . Property in { key ; value = ( if is_getter then Get value else Set value ) ; optional = false ; static = static <> None ; proto = false ; _method = false ; variance = None ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in Type . Object . Property prop in let indexer_property env start_loc static variance ~ leading = let indexer = with_loc ~ start_loc ( fun env -> let leading = leading @ Peek . comments env in Expect . token env T_LBRACKET ; let id = if Peek . ith_token ~ i : 1 env = T_COLON then ( let id = identifier_name env in Expect . token env T_COLON ; Some id ) else None in let key = _type env in Expect . token env T_RBRACKET ; let trailing = Eat . trailing_comments env in Expect . token env T_COLON ; let value = _type env in { Type . Object . Indexer . id ; key ; value ; static = static <> None ; variance ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) env in Type . Object . Indexer indexer in let internal_slot env start_loc static ~ leading = let islot = with_loc ~ start_loc ( fun env -> let leading = leading @ Peek . comments env in Expect . token env T_LBRACKET ; Expect . token env T_LBRACKET ; let id = identifier_name env in Expect . token env T_RBRACKET ; Expect . token env T_RBRACKET ; let optional , _method , value , trailing = match Peek . token env with | T_LESS_THAN | T_LPAREN -> let tparams = type_params_remove_trailing env ( type_params env ) in let value = let fn_loc , fn = methodish env start_loc tparams in ( fn_loc , Type . Function fn ) in ( false , true , value , [ ] ) | _ -> let optional = Eat . maybe env T_PLING in let trailing = Eat . trailing_comments env in Expect . token env T_COLON ; let value = _type env in ( optional , false , value , trailing ) in { Type . Object . InternalSlot . id ; value ; optional ; static = static <> None ; _method ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) env in Type . Object . InternalSlot islot in let spread_property env start_loc ~ leading = let spread = with_loc ~ start_loc ( fun env -> { Type . Object . SpreadProperty . argument = _type env ; comments = Flow_ast_utils . mk_comments_opt ~ leading ( ) ; } ) env in Type . Object . SpreadProperty spread in let semicolon exact env = match Peek . token env with | T_COMMA | T_SEMICOLON -> Eat . token env | T_RCURLYBAR when exact -> ( ) | T_RCURLY when not exact -> ( ) | _ -> error_unexpected env in let error_unexpected_variance env = function | Some ( loc , _ ) -> error_at env ( loc , Parse_error . UnexpectedVariance ) | None -> ( ) in let error_unexpected_proto env = function | Some loc -> error_at env ( loc , Parse_error . UnexpectedProto ) | None -> ( ) in let error_invalid_property_name env is_class static key = let is_static = static <> None in let is_constructor = String . equal " constructor " in let is_prototype = String . equal " prototype " in match key with | Expression . Object . Property . Identifier ( loc , { Identifier . name ; comments = _ } ) when is_class && ( is_constructor name || ( is_static && is_prototype name ) ) -> error_at env ( loc , Parse_error . InvalidClassMemberName { name ; static = is_static ; method_ = false ; private_ = false } ) | _ -> ( ) in let rec properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env ( ( props , inexact , internal ) as acc ) = assert ( not ( is_class && allow_spread ) ) ; assert ( ( not allow_inexact ) || allow_spread ) ; let start_loc = Peek . loc env in match Peek . token env with | T_EOF -> ( List . rev props , inexact , internal ) | T_RCURLYBAR when exact -> ( List . rev props , inexact , internal ) | T_RCURLY when not exact -> ( List . rev props , inexact , internal ) | T_ELLIPSIS when allow_spread -> ( let leading = Peek . comments env in Eat . token env ; match Peek . token env with | T_COMMA | T_SEMICOLON | T_RCURLY | T_RCURLYBAR -> ( semicolon exact env ; match Peek . token env with | T_RCURLY when allow_inexact -> ( List . rev props , true , leading ) | T_RCURLYBAR -> error_at env ( start_loc , Parse_error . InexactInsideExact ) ; ( List . rev props , inexact , internal ) | _ -> error_at env ( start_loc , Parse_error . UnexpectedExplicitInexactInObject ) ; properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env acc ) | _ -> let prop = spread_property env start_loc ~ leading in semicolon exact env ; properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env ( prop :: props , inexact , internal ) ) | T_ELLIPSIS -> ( Eat . token env ; match Peek . token env with | T_COMMA | T_SEMICOLON | T_RCURLY | T_RCURLYBAR -> error_at env ( start_loc , Parse_error . InexactInsideNonObject ) ; semicolon exact env ; properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env acc | _ -> error_list env ( Peek . errors env ) ; error_at env ( start_loc , Parse_error . UnexpectedSpreadType ) ; Eat . token env ; semicolon exact env ; properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env acc ) | _ -> let prop = property env start_loc ~ is_class ~ allow_static : is_class ~ allow_proto : is_class ~ variance : None ~ static : None ~ proto : None ~ leading [ ] : in semicolon exact env ; properties ~ is_class ~ allow_inexact ~ allow_spread ~ exact env ( prop :: props , inexact , internal ) and property env ~ is_class ~ allow_static ~ allow_proto ~ variance ~ static ~ proto ~ leading start_loc = match Peek . token env with | ( T_PLUS | T_MINUS ) when variance = None -> let variance = maybe_variance env in property env ~ is_class ~ allow_static : false ~ allow_proto : false ~ variance ~ static ~ proto ~ leading start_loc | T_STATIC when allow_static -> assert ( variance = None ) ; let static = Some ( Peek . loc env ) in let leading = leading @ Peek . comments env in Eat . token env ; property env ~ is_class ~ allow_static : false ~ allow_proto : false ~ variance ~ static ~ proto ~ leading start_loc | T_IDENTIFIER { raw = " proto " ; _ } when allow_proto -> assert ( variance = None ) ; let proto = Some ( Peek . loc env ) in let leading = leading @ Peek . comments env in Eat . token env ; property env ~ is_class ~ allow_static : false ~ allow_proto : false ~ variance ~ static ~ proto ~ leading start_loc | T_LBRACKET -> ( error_unexpected_proto env proto ; match Peek . ith_token ~ i : 1 env with | T_LBRACKET -> error_unexpected_variance env variance ; internal_slot env start_loc static ~ leading | _ -> indexer_property env start_loc static variance ~ leading ) | T_LESS_THAN | T_LPAREN -> error_unexpected_proto env proto ; error_unexpected_variance env variance ; call_property env start_loc static ~ leading | token -> ( match ( static , proto , token ) with | Some _ , Some _ , _ -> failwith " Can not have both ` static ` and ` proto ` " | Some static_loc , None , ( T_PLING | T_COLON ) -> let key = Expression . Object . Property . Identifier ( Flow_ast_utils . ident_of_source ( static_loc , " static " ) ? comments ( : Flow_ast_utils . mk_comments_opt ~ leading ( ) ) ) in let static = None in init_property env start_loc ~ variance ~ static ~ proto ~ leading [ ] : key | None , Some proto_loc , ( T_PLING | T_COLON ) -> let key = Expression . Object . Property . Identifier ( Flow_ast_utils . ident_of_source ( proto_loc , " proto " ) ? comments ( : Flow_ast_utils . mk_comments_opt ~ leading ( ) ) ) in let proto = None in init_property env start_loc ~ variance ~ static ~ proto ~ leading [ ] : key | _ -> ( let object_key env = Eat . push_lex_mode env Lex_mode . NORMAL ; let result = Parse . object_key env in Eat . pop_lex_mode env ; result in let leading_key = Peek . comments env in match object_key env with | ( _ , ( Expression . Object . Property . Identifier ( _ , { Identifier . name = ( " get " | " set " ) as name ; comments = _ ; } ) as key ) ) -> ( match Peek . token env with | T_LESS_THAN | T_LPAREN -> error_unexpected_proto env proto ; error_unexpected_variance env variance ; method_property env start_loc static key ~ leading | T_COLON | T_PLING -> init_property env start_loc ~ variance ~ static ~ proto ~ leading key | _ -> ignore ( object_key_remove_trailing env key ) ; let key = object_key env in let is_getter = name = " get " in let leading = leading @ leading_key in error_unexpected_proto env proto ; error_unexpected_variance env variance ; getter_or_setter ~ is_getter ~ leading env start_loc static key ) | _ , key -> ( match Peek . token env with | T_LESS_THAN | T_LPAREN -> error_unexpected_proto env proto ; error_unexpected_variance env variance ; method_property env start_loc static key ~ leading | _ -> error_invalid_property_name env is_class static key ; init_property env start_loc ~ variance ~ static ~ proto ~ leading key ) ) ) in fun ~ is_class ~ allow_exact ~ allow_spread env -> let exact = allow_exact && Peek . token env = T_LCURLYBAR in let allow_inexact = allow_exact && not exact in with_loc ( fun env -> let leading = Peek . comments env in Expect . token env ( if exact then T_LCURLYBAR else T_LCURLY ) ; let properties , inexact , internal = let env = with_no_anon_function_type false env in properties ~ is_class ~ allow_inexact ~ exact ~ allow_spread env ( [ ] , false , [ ] ) in let internal = internal @ Peek . comments env in Expect . token env ( if exact then T_RCURLYBAR else T_RCURLY ) ; let trailing = Eat . trailing_comments env in { Type . Object . exact ; properties ; inexact ; comments = Flow_ast_utils . mk_comments_with_internal_opt ~ leading ~ trailing ~ internal ( ) ; } ) env and interface_helper = let rec supers env acc = let super = generic env in let acc = super :: acc in match Peek . token env with | T_COMMA -> Expect . token env T_COMMA ; supers env acc | _ -> List . rev acc in fun env -> let extends = if Peek . token env = T_EXTENDS then ( Expect . token env T_EXTENDS ; let extends = supers env [ ] in generic_type_list_remove_trailing env extends ) else [ ] in let body = _object env ~ allow_exact : false ~ allow_spread : false ~ is_class : false in ( extends , body ) and type_identifier env = let loc , { Identifier . name ; comments } = identifier_name env in if is_reserved_type name then error_at env ( loc , Parse_error . UnexpectedReservedType ) ; ( loc , { Identifier . name ; comments } ) and bounded_type env = with_loc ( fun env -> let name = type_identifier env in let bound = if Peek . token env = T_COLON then Ast . Type . Available ( annotation env ) else Ast . Type . Missing ( Peek . loc_skip_lookahead env ) in ( name , bound ) ) env and type_params = let rec params env ~ require_default acc = let open Type . TypeParam in let loc , ( variance , name , bound , default , require_default ) = with_loc ( fun env -> let variance = maybe_variance env in let loc , ( name , bound ) = bounded_type env in let default , require_default = match Peek . token env with | T_ASSIGN -> Eat . token env ; ( Some ( _type env ) , true ) | _ -> if require_default then error_at env ( loc , Parse_error . MissingTypeParamDefault ) ; ( None , require_default ) in ( variance , name , bound , default , require_default ) ) env in let param = ( loc , { name ; bound ; variance ; default } ) in let acc = param :: acc in match Peek . token env with | T_EOF | T_GREATER_THAN -> List . rev acc | _ -> Expect . token env T_COMMA ; if Peek . token env = T_GREATER_THAN then List . rev acc else params env ~ require_default acc in fun env -> if Peek . token env = T_LESS_THAN then ( if not ( should_parse_types env ) then error env Parse_error . UnexpectedTypeAnnotation ; Some ( with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_LESS_THAN ; let params = params env ~ require_default : false [ ] in let internal = Peek . comments env in Expect . token env T_GREATER_THAN ; let trailing = Eat . trailing_comments env in { Type . TypeParams . params ; comments = Flow_ast_utils . mk_comments_with_internal_opt ~ leading ~ trailing ~ internal ( ) ; } ) env ) ) else None and type_args = let rec args env acc = match Peek . token env with | T_EOF | T_GREATER_THAN -> List . rev acc | _ -> let acc = _type env :: acc in if Peek . token env <> T_GREATER_THAN then Expect . token env T_COMMA ; args env acc in fun env -> if Peek . token env = T_LESS_THAN then Some ( with_loc ( fun env -> let leading = Peek . comments env in Expect . token env T_LESS_THAN ; let env = with_no_anon_function_type false env in let arguments = args env [ ] in let internal = Peek . comments env in Expect . token env T_GREATER_THAN ; let trailing = Eat . trailing_comments env in { Type . TypeArgs . arguments ; comments = Flow_ast_utils . mk_comments_with_internal_opt ~ leading ~ trailing ~ internal ( ) ; } ) env ) else None and generic env = raw_generic_with_identifier env ( type_identifier env ) and raw_generic_with_identifier = let rec identifier env ( q_loc , qualification ) = if Peek . token env = T_PERIOD && Peek . ith_is_type_identifier ~ i : 1 env then let loc , q = with_loc ~ start_loc : q_loc ( fun env -> Expect . token env T_PERIOD ; let id = type_identifier env in { Type . Generic . Identifier . qualification ; id } ) env in let qualification = Type . Generic . Identifier . Qualified ( loc , q ) in identifier env ( loc , qualification ) else ( q_loc , qualification ) in fun env id -> with_loc ~ start_loc ( : fst id ) ( fun env -> let id = ( fst id , Type . Generic . Identifier . Unqualified id ) in let id = let _id_loc , id = identifier env id in if Peek . token env <> T_LESS_THAN then id else let { remove_trailing ; _ } = trailing_and_remover env in remove_trailing id ( fun remover id -> remover # generic_identifier_type id ) in let targs = type_args env in { Type . Generic . id ; targs ; comments = None } ) env and generic_type_with_identifier env id = let loc , generic = raw_generic_with_identifier env id in ( loc , Type . Generic generic ) and annotation_opt env = match Peek . token env with | T_COLON -> Type . Available ( annotation env ) | _ -> Type . Missing ( Peek . loc_skip_lookahead env ) and add_comments ( loc , t ) leading trailing = let merge_comments inner = Flow_ast_utils . merge_comments ~ inner ~ outer ( : Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) in let merge_comments_with_internal inner = Flow_ast_utils . merge_comments_with_internal ~ inner ~ outer ( : Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ) in let open Ast . Type in ( loc , match t with | Any comments -> Any ( merge_comments comments ) | Mixed comments -> Mixed ( merge_comments comments ) | Empty comments -> Empty ( merge_comments comments ) | Void comments -> Void ( merge_comments comments ) | Null comments -> Null ( merge_comments comments ) | Number comments -> Number ( merge_comments comments ) | BigInt comments -> BigInt ( merge_comments comments ) | String comments -> String ( merge_comments comments ) | Boolean comments -> Boolean ( merge_comments comments ) | Symbol comments -> Symbol ( merge_comments comments ) | Exists comments -> Exists ( merge_comments comments ) | Nullable ( { Nullable . comments ; _ } as t ) -> Nullable { t with Nullable . comments = merge_comments comments } | Function ( { Function . comments ; _ } as t ) -> Function { t with Function . comments = merge_comments comments } | Object ( { Object . comments ; _ } as t ) -> Object { t with Object . comments = merge_comments_with_internal comments } | Interface ( { Interface . comments ; _ } as t ) -> Interface { t with Interface . comments = merge_comments comments } | Array ( { Array . comments ; _ } as t ) -> Array { t with Array . comments = merge_comments comments } | Generic ( { Generic . comments ; _ } as t ) -> Generic { t with Generic . comments = merge_comments comments } | IndexedAccess ( { IndexedAccess . comments ; _ } as t ) -> IndexedAccess { t with IndexedAccess . comments = merge_comments comments } | OptionalIndexedAccess { OptionalIndexedAccess . indexed_access = { IndexedAccess . comments ; _ } as indexed_access ; optional ; } -> OptionalIndexedAccess { OptionalIndexedAccess . indexed_access = { indexed_access with IndexedAccess . comments = merge_comments comments ; } ; optional ; } | Union ( { Union . comments ; _ } as t ) -> Union { t with Union . comments = merge_comments comments } | Intersection ( { Intersection . comments ; _ } as t ) -> Intersection { t with Intersection . comments = merge_comments comments } | Typeof ( { Typeof . comments ; _ } as t ) -> Typeof { t with Typeof . comments = merge_comments comments } | Tuple ( { Tuple . comments ; _ } as t ) -> Tuple { t with Tuple . comments = merge_comments comments } | StringLiteral ( { StringLiteral . comments ; _ } as t ) -> StringLiteral { t with StringLiteral . comments = merge_comments comments } | NumberLiteral ( { NumberLiteral . comments ; _ } as t ) -> NumberLiteral { t with NumberLiteral . comments = merge_comments comments } | BigIntLiteral ( { BigIntLiteral . comments ; _ } as t ) -> BigIntLiteral { t with BigIntLiteral . comments = merge_comments comments } | BooleanLiteral ( { BooleanLiteral . comments ; _ } as t ) -> BooleanLiteral { t with BooleanLiteral . comments = merge_comments comments } ) let predicate = with_loc ( fun env -> let open Ast . Type . Predicate in let leading = Peek . comments env in Expect . token env T_CHECKS ; if Peek . token env = T_LPAREN then ( let leading = leading @ Peek . comments env in Expect . token env T_LPAREN ; Eat . push_lex_mode env Lex_mode . NORMAL ; let exp = Parse . conditional env in Eat . pop_lex_mode env ; Expect . token env T_RPAREN ; let trailing = Eat . trailing_comments env in { kind = Declared exp ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) else let trailing = Eat . trailing_comments env in { kind = Ast . Type . Predicate . Inferred ; comments = Flow_ast_utils . mk_comments_opt ~ leading ~ trailing ( ) ; } ) let predicate_opt env = let env = with_no_anon_function_type false env in match Peek . token env with T_CHECKS -> Some ( predicate env ) | _ -> None let annotation_and_predicate_opt env = let open Ast . Type in match ( Peek . token env , Peek . ith_token ~ i : 1 env ) with | T_COLON , T_CHECKS -> Expect . token env T_COLON ; ( Missing ( Peek . loc_skip_lookahead env ) , predicate_opt env ) | T_COLON , _ -> let annotation = let annotation = annotation_opt env in if Peek . token env = T_CHECKS then type_annotation_hint_remove_trailing env annotation else annotation in let predicate = predicate_opt env in ( annotation , predicate ) | _ -> ( Missing ( Peek . loc_skip_lookahead env ) , None ) let wrap f env = let env = env |> with_strict true in Eat . push_lex_mode env Lex_mode . TYPE ; let ret = f env in Eat . pop_lex_mode env ; ret let _type = wrap _type let type_identifier = wrap type_identifier let type_params = wrap type_params let type_args = wrap type_args let _object ~ is_class env = wrap ( _object ~ is_class ~ allow_exact : false ~ allow_spread : false ) env let interface_helper = wrap interface_helper let function_param_list = wrap function_param_list let annotation = wrap annotation let annotation_opt = wrap annotation_opt let predicate_opt = wrap predicate_opt let annotation_and_predicate_opt = wrap annotation_and_predicate_opt let generic = wrap generic end
module Make ( D : Debugger . S ) ( Cmt_cache : Cmt_cache_intf . S ) ( Type_helper : Type_helper_intf . S with module Cmt_cache := Cmt_cache with module D := D ) = struct type t = { cmt_cache : Cmt_cache . t ; } let create cmt_cache = { cmt_cache ; } let print_given_type_and_env ? variable_name ? always_print formatter ( type_and_env : ( Cmt_file . core_or_module_type * _ * _ ) option ) = match type_and_env with | None -> false | Some ( Core type_expr , env , _is_parameter ) -> let type_expr = Btype . repr type_expr in let print ( ) = begin match variable_name with | None -> ( ) | Some name -> Format . fprintf formatter " { @< variable_name_colour >% s } " @ name end ; Format . fprintf formatter " @ : { @< type_colour " ; > Printtyp . wrap_printing_env ~ error : false env ( fun ( ) -> Printtyp . reset_and_mark_loops type_expr ; Printtyp . type_expr formatter type_expr ) ; Format . fprintf formatter " } " ; @ true in begin match type_expr . desc with | Tvar _ | Tunivar _ | Tnil | Tlink _ | Tsubst _ -> begin match always_print with | None -> false | Some ( ) -> print ( ) end | Tarrow _ | Ttuple _ | Tconstr _ | Tobject _ | Tfield _ | Tvariant _ | Tpoly _ | Tpackage _ -> print ( ) end | Some ( Module modtype , _ , _is_parameter ) -> begin match variable_name with | None -> ( ) | Some name -> Format . fprintf formatter " { @< module_name_colour >% s } " @ name end ; Format . fprintf formatter " @ : { @< type_colour " ; > Printtyp . modtype formatter modtype ; Format . fprintf formatter " } " ; @ true let print ? variable_name t formatter ~ dwarf_type = let type_and_env = match Cmt_cache . find_cached_type t . cmt_cache ~ cached_type : dwarf_type with | Some type_and_env -> Some type_and_env | None -> Type_helper . type_and_env_from_dwarf_type ~ dwarf_type ~ cmt_cache : t . cmt_cache D . Frame . none in let env = match type_and_env with | None -> Env . empty | Some ( _ , env , _ ) -> env in Printtyp . wrap_printing_env ~ error : false env ( fun ( ) -> print_given_type_and_env ? variable_name ~ always_print ( ) : formatter type_and_env ) end
module type S = sig module Cmt_cache : Cmt_cache_intf . S type t val create : Cmt_cache . t -> t val print_given_type_and_env : ? variable_name : string -> ? always_print : unit -> Format . formatter -> ( Cmt_file . core_or_module_type * Env . t * Is_parameter . t ) option -> bool val print : ? variable_name : string -> t -> Format . formatter -> dwarf_type : string -> bool end
let var ( n : int ) int = Var ( Var " v " ^ string_of_int n ) n
let const c = Term ( c [ ] ) ,
let new_int , reset_new_int = let c = ref ( - 1 ) 1 in ( fun ( ) -> incr c ; ! c ) c , ( fun ( ) -> c := - 1 )
let unop_type k = match k with | Ml_fst -> let a = var ( new_int ( new_int ) new_int ) new_int and b = var ( new_int ( new_int ) new_int ) new_int in pair ( paira , b ) b , a | Ml_snd -> let a = var ( new_int ( new_int ) new_int ) new_int and b = var ( new_int ( new_int ) new_int ) new_int in pair ( paira , b ) b , b
let binop_type k = match k with | Ml_add | Ml_sub | Ml_mult -> ( const " int " , const " int " , const " int ) " | Ml_eq | Ml_gt | Ml_less -> ( const " int " , const " int " , const " bool ) "
let generate_type_constraints e = begin reset_new_int ( reset_new_int ) reset_new_int ; let rec gen n tenv = function | <: me < $ int : _ $ >> -> [ var n , const " int ] " | <: me < $ bool : _ $ >> -> [ var n , const " bool ] " | <: me < fst $ _ $ >> -> let t1 , t2 = unop_type Ml_fst and ne = new_int ( ) in [ ( var n , t2 ) t2 ; ( var ne , t1 ) t1 ] t1 | <: me < snd $ _ $ >> -> let t1 , t2 = unop_type Ml_snd and ne = new_int ( ) in [ ( var n , t2 ) t2 ; ( var ne , t1 ) t1 ] t1 | <: me < $ e1 $ + $ e2 $ >> | <: me < $ e1 $ - $ e2 $ >> | <: me < $ e1 $ * $ e2 $ >> -> let n1 = new_int ( new_int ) new_int and n2 = new_int ( new_int ) new_int in ( var n , const " int ) " :: | <: me < $ e1 $ = $ e2 $ >> | <: me < $ e1 $ < $ e2 $ >> | <: me < $ e1 $ > $ e2 $ >> -> let n1 = new_int ( ) and n2 = new_int ( ) in ( var n , const " bool ) " :: ( var n1 , const " int ) " | <: me < ( $ e1 , $ $ e2 $ ) >> -> let n1 = new_int ( ) and n2 = new_int ( ) in ( var n , pair ( var n1 , var n2 ) n2 ) n2 :: | <: me < $ lid : x $ >> -> [ var n , List . assoc x tenv ] | <: me < if $ e1 $ then $ e2 $ else $ e3 $ >> -> let n1 = new_int ( ) and n2 = new_int ( ) and n3 = new_int ( ) in ( var n , var n2 ) n2 :: ( var n2 , var n3 ) n3 :: ( var n1 , const " bool ) " | <: me < fun $ patt : x $ -> $ e $ >> -> let n1 = new_int ( ) and n2 = new_int ( ) in ( var n , arrow ( arrowvar n1 , var n2 ) n2 ) :: | <: me < $ e1 $ $ e2 $ >> -> let n1 = new_int ( ) and n2 = new_int ( new_int ) new_int in ( var n1 , arrow ( arrowvar n2 , var n ) n ) n :: | <: me < let $ patt : x $ = $ e1 $ in $ e2 $ >> -> let n1 = new_int ( ) and n2 = new_int ( ) in ( var n , var n2 ) :: | <: me < let rec $ patt : x $ = $ e1 $ in $ e2 $ >> -> let n1 = new_int ( ) and n2 = new_int ( ) in ( var n , var n2 ) n2 :: | Ml_Ant ( _ , _ ) _ | Ml_fun ( Ml_patAnt ( _ , _ ) _ , _ ) | Ml_let ( Ml_patAnt ( _ , _ ) _ , _ , _ ) | Ml_letrec ( Ml_patAnt ( _ , _ ) _ , _ , _ ) -> failwithf " not supported ast " in gen ( new_int ( ) ) [ ] e
type simple = A of int
type u = A of int
type u = [ ` a | ` b ] ; ;
type u = v = A of int ; ;
type u = v = private A of int ; ;
type ' a ab = [ < ` a ` | b ] as ' a
type ' a ac = ' a constraint ' a = [ < ` a | ` c ]
type ( ' a , ' b ) m = [ < ` m of ' a ab & ' a ac ] as ' b
type _ a = A : int -> int a
type _ a = A : int -> int a | B : int -> float a
type ( ' u , ' v ) a = | A of int list * bool | B of bool
type gram = { gfilter : filter ; gkeywords ( : string , int ref ) Hashtbl . t ; glexer : ( FanLoc . t -> ( char Stream . t -> ( token * FanLoc . t ) Stream . t ) ) ; warning_verbose : bool ref ; error_verbose : bool ref } [ ` Smeta of ( string * symbol list * Action . t ) | ` Snterm of internal_entry | ` Snterml of ( internal_entry * string ) | ` Slist0 of symbol | ` Slist0sep of ( symbol * symbol ) | ` Slist1 of symbol | ` Slist1sep of ( symbol * symbol ) | ` Sopt of symbol | ` Stry of symbol | ` Sself | ` Snext | ` Stoken of token_pattern | ` Skeyword of string | ` Stree of tree ]
type ' + a my = H of ' a | D ; ;
type ( ' + a , ' - b ) u = H of ' a | D of ( ' b -> int )
type ' a item_or_def = | SdStr of ' a | SdDef of string ( * string list * Ast . expr ) option | SdUnd of string | SdITE of bool ' * a item_or_def list ' * a item_or_def list | SdLazy of ' a Lazy . t
type s = ? u : int -> int -> int
let parse_expr ( ? keywords = Lexer_raw . keywords [ ] ) expr = let lexbuf = Lexing . from_string expr in let state = Lexer_raw . make keywords in let rec lexer = function | Lexer_raw . Fail ( e , l ) -> raise ( Lexer_raw . Error ( e , l ) ) | Lexer_raw . Return token -> token | Lexer_raw . Refill k -> lexer ( k ( ) ) in let lexer lexbuf = lexer ( Lexer_raw . token_without_comments state lexbuf ) in Parser_raw . parse_expression lexer lexbuf
let lookup_module name env = let path , md = Env . find_module_by_name name env in path , md . Types . md_type , md . Types . md_attributes
let verbosity = ref 0
module Printtyp = struct include Printtyp let expand_type env ty = Env . with_cmis @@ fun ( ) -> if ! verbosity = 0 then ty else let ty = Subst . type_expr Subst . identity ty in let marks = Hashtbl . create 7 in let mark ty = if Hashtbl . mem marks ty . Types . id then false else ( Hashtbl . add marks ty . Types . id ( ) ; true ) in let rec iter d ty0 = let ty ' = Ctype . repr ty0 in if mark ty ' then let open Types in let ty ' ' = Ctype . full_expand env ty ' in if ty ' ' . desc == ty ' . desc then Btype . iter_type_expr ( iter d ) ty0 else begin let desc = match ty ' ' . desc with | Tvariant row -> Tvariant { row with row_name = None } | Tobject ( ty , _ ) -> Tobject ( ty , ref None ) | desc -> desc in ty0 . desc <- desc ; if d > 0 then Btype . iter_type_expr ( iter ( pred d ) ) ty0 end in iter ! verbosity ty ; ty let expand_type_decl env ty = match ty . Types . type_manifest with | Some m -> { ty with Types . type_manifest = Some ( expand_type env m ) } | None -> ty let expand_sig env mty = Env . with_cmis @@ fun ( ) -> Env . scrape_alias env mty let verbose_type_scheme env ppf t = Printtyp . type_scheme ppf ( expand_type env t ) let verbose_type_declaration env id ppf t = Printtyp . type_declaration id ppf ( expand_type_decl env t ) let verbose_modtype env ppf t = Printtyp . modtype ppf ( expand_sig env t ) let select_verbose a b env = ( if ! verbosity = 0 then a else b env ) let type_scheme env ppf ty = select_verbose type_scheme verbose_type_scheme env ppf ty let type_declaration env id ppf = select_verbose type_declaration verbose_type_declaration env id ppf let modtype env ppf mty = select_verbose modtype verbose_modtype env ppf mty let wrap_printing_env env ~ verbosity : v f = let_ref verbosity v ( fun ( ) -> wrap_printing_env env f ) end
let rec mod_smallerthan n m = if n < 0 then None else let open Types in match m with | Mty_ident _ -> Some 1 | Mty_signature s -> begin match List . length_lessthan n s with | None -> None | Some _ -> List . fold_left s ~ init ( : Some 0 ) ~ f : begin fun acc item -> let sub n1 m = match mod_smallerthan ( n - n1 ) m with | Some n2 -> Some ( n1 + n2 ) | None -> None in match acc , Raw_compat . si_modtype_opt item with | None , _ -> None | Some n ' , _ when n ' > n -> None | Some n1 , Some mty -> sub n1 mty | Some n ' , _ -> Some ( succ n ' ) end end | Mty_functor _ -> let ( m1 , m2 ) = unpack_functor m in begin match mod_smallerthan n m2 , m1 with | None , _ -> None | result , Unit -> result | Some n1 , Named ( _ , mt ) -> match mod_smallerthan ( n - n1 ) mt with | None -> None | Some n2 -> Some ( n1 + n2 ) end | _ -> Some 1
let print_short_modtype verbosity env ppf md = match mod_smallerthan 1000 md with | None when verbosity = 0 -> Format . pp_print_string ppf " " ; | _ -> Printtyp . modtype env ppf md
let print_type_with_decl ~ verbosity env ppf typ = if verbosity > 0 then match ( Ctype . repr typ ) . Types . desc with | Types . Tconstr ( path , params , _ ) -> let decl = Env . with_cmis @@ fun ( ) -> Env . find_type path env in let is_abstract = match decl . Types . type_kind with | Types . Type_abstract -> true | _ -> false in let print_expr = is_abstract || params <> [ ] in if print_expr then Printtyp . type_scheme env ppf typ ; if not is_abstract then begin if print_expr then begin Format . pp_print_newline ppf ( ) ; Format . pp_print_newline ppf ( ) ; end ; let ident = match path with | Path . Papply _ -> assert false | Path . Pdot _ -> Ident . create_persistent ( Path . last path ) | Path . Pident ident -> ident in Printtyp . type_declaration env ident ppf decl end | _ -> Printtyp . type_scheme env ppf typ else Printtyp . type_scheme env ppf typ
let print_exn ppf exn = match Location . error_of_exn exn with | None | Some ` Already_displayed -> Format . pp_print_string ppf ( Printexc . to_string exn ) | Some ( ` Ok report ) -> Location . print_main ppf report
let print_type ppf env lid = let p , t = Env . find_type_by_name lid . Asttypes . txt env in Printtyp . type_declaration env ( Ident . create_persistent ( Path . last p ) ) ppf t
let print_modtype ppf verbosity env lid = let _p , mtd = Env . find_modtype_by_name lid . Asttypes . txt env in match mtd . mtd_type with | Some mt -> print_short_modtype verbosity env ppf mt | None -> Format . pp_print_string ppf " "
let print_modpath ppf verbosity env lid = let _path , md = Env . find_module_by_name lid . Asttypes . txt env in print_short_modtype verbosity env ppf ( md . md_type )
let print_constr ppf env lid = let cstr_desc = Env . find_constructor_by_name lid . Asttypes . txt env in ! Oprint . out_type ppf ( Browse_misc . print_constructor cstr_desc )
let type_in_env ( ? verbosity = 0 ) ? keywords ~ context env ppf expr = let print_expr expression = let ( str , _sg , _ ) = Env . with_cmis @@ fun ( ) -> Typemod . type_toplevel_phrase env [ Ast_helper . Str . eval expression ] in let open Typedtree in let exp = Raw_compat . dest_tstr_eval str in print_type_with_decl ~ verbosity env ppf exp . exp_type in Printtyp . wrap_printing_env env ~ verbosity @@ fun ( ) -> Msupport . uncatch_errors @@ fun ( ) -> match parse_expr ? keywords expr with | exception exn -> print_exn ppf exn ; false | e -> let extract_specific_parsing_info e = match e . Parsetree . pexp_desc with | Parsetree . Pexp_ident longident -> ` Ident longident | Parsetree . Pexp_construct ( longident , _ ) -> ` Constr longident | _ -> ` Other in let open Context in match extract_specific_parsing_info e with | ` Ident longident | ` Constr longident -> begin try begin match context with | Label lbl_des -> Printtyp . type_expr ppf lbl_des . lbl_arg ; | Type -> print_type ppf env longident | Module_type -> print_modtype ppf verbosity env longident | Module_path -> print_modpath ppf verbosity env longident | Constructor _ -> print_constr ppf env longident | _ -> raise Fallback end ; true with _ -> try print_expr e ; true with exn -> try print_modpath ppf verbosity env longident ; true with _ -> try print_modtype ppf verbosity env longident ; true with _ -> try print_constr ppf env longident ; true with _ -> print_exn ppf exn ; false end | ` Other -> try print_expr e ; true with exn -> print_exn ppf exn ; false
let read_doc_attributes attrs = let rec loop = function | ( { Location . txt = ( " doc " | " ocaml . doc " ) ; loc = _ } , payload ) :: _ -> Ast_helper . extract_str_payload payload | _ :: rest -> loop rest | [ ] -> None in loop ( List . map ~ f : Ast_helper . Attr . as_tuple attrs )
let is_deprecated = List . exists ~ f ( : fun ( attr : Parsetree . attribute ) -> match Ast_helper . Attr . as_tuple attr with | { Location . txt = ( " deprecated " | " ocaml . deprecated " ) ; loc = _ } , _ -> true | _ -> false )
module List = struct let map t ~ f = List . rev ( List . rev_map f t ) end
module Make ( Pos : sig type t val sexp_of_t : t -> Type . t end ) = struct module T = struct type t = | Atom of Pos . t * string * string option | List of Pos . t * t_or_comment list * Pos . t and t_or_comment = | Sexp of t | Comment of comment and comment = | Plain_comment of Pos . t * string | Sexp_comment of Pos . t * comment list * t end include T module type S = sig include module type of T val sexp_of_t : t -> Type . t val sexp_of_comment : comment -> Type . t val sexp_of_t_or_comment : t_or_comment -> Type . t end module To_sexp : sig val of_t : t -> Type . t val of_comment : comment -> Type . t val of_t_or_comment : t_or_comment -> Type . t end = struct let of_pos = Pos . sexp_of_t let of_string x = Type . Atom x let of_list of_a xs = Type . List ( List . map ~ f : of_a xs ) let of_option of_a = function | Some x -> Type . List [ of_a x ] | None -> Type . List [ ] ; ; let rec of_t = function | Atom ( v1 , v2 , v3 ) -> Type . List [ Type . Atom " Atom " ; of_pos v1 ; of_string v2 ; of_option of_string v3 ] | List ( v1 , v2 , v3 ) -> Type . List [ Type . Atom " List " ; of_pos v1 ; of_list of_t_or_comment v2 ; of_pos v3 ] and of_t_or_comment = function | Sexp t -> Type . List [ Type . Atom " Sexp " ; of_t t ] | Comment c -> Type . List [ Type . Atom " Comment " ; of_comment c ] and of_comment = function | Plain_comment ( v1 , v2 ) -> Type . List [ Type . Atom " Plain_comment " ; of_pos v1 ; of_string v2 ] | Sexp_comment ( v1 , v2 , v3 ) -> Type . List [ Type . Atom " Sexp_comment " ; of_pos v1 ; of_list of_comment v2 ; of_t v3 ] ; ; end let sexp_of_t = To_sexp . of_t let sexp_of_comment = To_sexp . of_comment let sexp_of_t_or_comment = To_sexp . of_t_or_comment end
module Parsed = Make ( Src_pos . Absolute )
let relativize = let rel ~ outer_p p = Src_pos . Absolute . diff p outer_p in let rec aux_t ~ outer_p = function | Parsed . Atom ( pos , s , sopt ) -> Atom ( rel pos ~ outer_p , s , sopt ) | Parsed . List ( start_pos , tocs , end_pos ) -> List ( rel start_pos ~ outer_p , List . map tocs ~ f ( : fun toc -> aux_toc ~ outer_p : start_pos toc ) , rel end_pos ~ outer_p ) and aux_toc ~ outer_p = function | Parsed . Sexp t -> Sexp ( aux_t t ~ outer_p ) | Parsed . Comment c -> Comment ( aux_c c ~ outer_p ) and aux_c ~ outer_p = function | Parsed . Plain_comment ( pos , txt ) -> Plain_comment ( rel pos ~ outer_p , txt ) | Parsed . Sexp_comment ( pos , cs , t ) -> Sexp_comment ( rel pos ~ outer_p , List . map cs ~ f ( : fun c -> aux_c ~ outer_p c ) , aux_t t ~ outer_p ) in fun toc -> aux_toc toc ~ outer_p : Src_pos . Absolute . origin ; ;
let find_value loc f = try find_value f with Not_found -> error loc ( Eglobal_undefined ( Value , f ) )
let find_type loc f = try find_type f with Not_found -> error loc ( Eglobal_undefined ( Type , f ) )
let find_constr loc c = try find_constr c with Not_found -> error loc ( Eglobal_undefined ( Constr , c ) )
let find_label loc l = try find_label l with Not_found -> error loc ( Eglobal_undefined ( Label , l ) )
let unify loc expected_ty actual_ty = try Ztypes . unify expected_ty actual_ty with | Ztypes . Unify -> error loc ( Etype_clash ( actual_ty , expected_ty ) )
let equal_sizes loc expected_size actual_size = try Ztypes . equal_sizes expected_size actual_size with | Ztypes . Unify -> error loc ( Esize_clash ( actual_size , expected_size ) )
let unify_expr expr expected_ty actual_ty = try Ztypes . unify expected_ty actual_ty with | Ztypes . Unify -> error expr . e_loc ( Etype_clash ( actual_ty , expected_ty ) )
let unify_pat pat expected_ty actual_ty = try Ztypes . unify expected_ty actual_ty with | Ztypes . Unify -> error pat . p_loc ( Etype_clash ( actual_ty , expected_ty ) )
let less_than loc actual_k expected_k = try Ztypes . less_than actual_k expected_k with | Ztypes . Unify -> error loc ( Ekind_clash ( actual_k , expected_k ) )
let type_is_in_kind loc expected_k ty = try Ztypes . kind expected_k ty with | Ztypes . Unify -> error loc ( Etype_kind_clash ( expected_k , ty ) )
let lift loc left_k right_k = try Ztypes . lift left_k right_k with | Ztypes . Unify -> error loc ( Ekind_clash ( right_k , left_k ) )
let sort_less_than loc sort expected_k = match expected_k , sort with | Tstatic _ , Sstatic -> ( ) | Tstatic _ , _ -> error loc ( Ekind_clash ( Deftypes . Tany , expected_k ) ) | _ -> ( )
let check_is_vec loc actual_ty = try let ty_arg , size = Ztypes . filter_vec actual_ty in ty_arg , size with | Ztypes . Unify -> error loc Esize_of_vec_is_undetermined
let rec expansive { e_desc = desc } = match desc with | Elocal _ | Eglobal _ | Econst _ | Econstr0 _ -> false | Etuple ( e_list ) -> List . exists expansive e_list | Erecord ( l_e_list ) -> List . exists ( fun ( _ , e ) -> expansive e ) l_e_list | Erecord_access ( e , _ ) | Etypeconstraint ( e , _ ) -> expansive e | Erecord_with ( e , l_e_list ) -> expansive e || List . exists ( fun ( _ , e ) -> expansive e ) l_e_list | _ -> true
let check_statefull loc expected_k = if not ( Ztypes . is_statefull_kind expected_k ) then error loc Ekind_not_combinatorial
type state = { mutable s_reset : bool option ; s_parameters : typ list }
let check_target_state loc expected_reset actual_reset = match expected_reset with | None -> Some ( actual_reset ) | Some ( expected_reset ) -> if expected_reset <> actual_reset then warning loc ( Wreset_target_state ( actual_reset , expected_reset ) ) ; Some ( expected_reset )
let turn_vars_into_memories h { dv = dv } = let add n acc = let ( { t_sort = sort ; t_typ = typ } as tentry ) = Env . find n h in match sort with | Smem ( { m_init = Noinit } as m ) -> Env . add n { tentry with t_sort = Smem { m with m_init = InitEq } } acc | Sstatic | Sval | Svar _ | Smem _ -> acc in let first_h = S . fold add dv Env . empty in first_h , Env . append first_h h
let immediate = function | Ebool _ -> Initial . typ_bool | Eint ( i ) -> Initial . typ_int | Efloat ( i ) -> Initial . typ_float | Echar ( c ) -> Initial . typ_char | Estring ( c ) -> Initial . typ_string | Evoid -> Initial . typ_unit
let incorporate_into_env first_h h = let mark n { t_sort = sort } = let tentry = Env . find n h in match sort with | Smem ( { m_init = InitEq } as m ) -> tentry . t_sort <- Smem { m with m_init = Noinit } | _ -> ( ) in Env . iter mark first_h
let vars pat = Vars . fv_pat S . empty S . empty pat
let var loc h n = try Env . find n h with Not_found -> error loc ( Evar_undefined ( n ) )
let typ_of_var loc h n = let { t_typ = typ } = var loc h n in typ
let last loc h n = let { t_sort = sort ; t_typ = typ } as entry = var loc h n in begin match sort with | Sstatic | Sval | Svar _ | Smem { m_next = Some ( true ) } -> | Smem ( m ) -> entry . t_sort <- Smem { m with m_previous = true } end ; typ
let derivative loc h n = let { t_typ = typ ; t_sort = sort } as entry = var loc h n in match sort with | Sstatic | Sval | Svar _ -> | Smem ( m ) -> entry . t_sort <- Smem { m with m_kind = Some ( Cont ) } ; typ
let pluseq loc h n = let ( { t_typ = typ ; t_sort = sort } as entry ) = var loc h n in match sort with | Svar { v_combine = Some _ } -> typ | Sstatic | Sval | Svar { v_combine = None } | Smem { m_combine = None } -> error loc ( Ecombination_function ( n ) ) | Smem ( { m_next = n_opt } as m ) -> match n_opt with | None -> entry . t_sort <- Smem { m with m_next = Some ( false ) } ; typ | Some ( false ) -> typ | Some ( true ) -> error loc ( Ealready_with_different_kinds ( Next , Multi , n ) )
let init loc h n = let { t_typ = typ ; t_sort = sort } as entry = var loc h n in match sort with | Sstatic | Sval | Svar _ -> assert false | Smem ( { m_init = i } as m ) -> match i with | Noinit -> entry . t_sort <- Smem { m with m_init = InitEq } ; typ | InitEq -> typ | InitDecl _ -> error loc ( Ealready ( Initial , n ) )
let next loc h n = let { t_typ = typ ; t_sort = sort } as entry = var loc h n in match sort with | Sstatic | Sval | Svar _ -> assert false | Smem { m_previous = true } -> error loc ( Enext_forbidden ( n ) ) | Smem ( { m_next = n_opt } as m ) -> match n_opt with | None -> entry . t_sort <- Smem { m with m_next = Some ( true ) } ; typ | Some ( true ) -> typ | Some ( false ) -> error loc ( Ealready_with_different_kinds ( Current , Next , n ) )
let def loc h n = let { t_sort = sort } as entry = var loc h n in match sort with | Sstatic | Sval | Svar _ -> ( ) | Smem ( { m_next = n_opt } as m ) -> match n_opt with | None -> entry . t_sort <- Smem { m with m_next = Some ( false ) } | Some ( false ) -> ( ) | Some ( true ) -> error loc ( Ealready_with_different_kinds ( Next , Current , n ) )
let global loc expected_k lname = let { qualid = qualid ; info = { value_static = is_static ; value_typ = tys } } = find_value loc lname in less_than loc ( if is_static then Tstatic true else expected_k ) expected_k ; qualid , Ztypes . instance_of_type tys
let global_with_instance loc expected_k lname = let { qualid = qualid ; info = { value_static = is_static ; value_typ = tys } } = find_value loc lname in less_than loc ( if is_static then Tstatic true else expected_k ) expected_k ; let typ_instance , typ_body = Ztypes . instance_and_vars_of_type tys in qualid , typ_instance , typ_body
let label loc l = let { qualid = qualid ; info = tys_label } = find_label loc l in qualid , Ztypes . label_instance tys_label
let constr loc c = let { qualid = qualid ; info = tys_c } = find_constr loc c in qualid , Ztypes . constr_instance tys_c
let rec get_all_labels loc ty = match ty . t_desc with | Tconstr ( qual , _ , _ ) -> let { info = { type_desc = ty_c } } = find_type loc ( Lident . Modname ( qual ) ) in begin match ty_c with Record_type ( l ) -> l | _ -> assert false end | Tlink ( link ) -> get_all_labels loc link | _ -> assert false
let check_definitions_for_every_name defined_names n_list = List . fold_left ( fun { dv = dv ; di = di ; der = der ; nv = nv ; mv = mv } { vardec_name = n ; vardec_default = d_opt ; vardec_loc = loc } -> let in_dv = S . mem n dv in let in_di = S . mem n di in let in_der = S . mem n der in let in_nv = S . mem n nv in let in_mv = S . mem n mv in if not ( in_dv || in_di || in_der || in_nv || in_mv ) then error loc ( Eequation_is_missing ( n ) ) ; { dv = if in_dv then S . remove n dv else dv ; di = if in_di then S . remove n di else di ; der = if in_der then S . remove n der else der ; nv = if in_nv then S . remove n nv else nv ; mv = if in_mv then S . remove n mv else mv } ) defined_names n_list
let combine loc expected_ty lname = let { qualid = qualid ; info = { value_typ = tys } } = find_value loc lname in let ty = Ztypes . instance_of_type tys in let ty_combine = Ztypes . type_of_combine ( ) in unify loc ty_combine ty
let constant loc expected_k expected_ty = function | Cimmediate ( i ) -> let actual_ty = immediate ( i ) in unify loc expected_ty actual_ty | Cglobal ( lname ) -> let qualid , actual_ty = global loc expected_k lname in unify loc expected_ty actual_ty
let vardec_list expected_k n_list inames = let default loc expected_ty c_opt = function | Init ( v ) -> if not ( Ztypes . is_statefull_kind expected_k ) then error loc Ekind_not_combinatorial ; constant loc expected_k expected_ty v ; Deftypes . Smem ( Deftypes . cmem c_opt { empty_mem with m_init = InitDecl ( v ) } ) | Default ( v ) -> constant loc expected_k expected_ty v ; Deftypes . default ( Some ( v ) ) c_opt in let vardec h0 { vardec_name = n ; vardec_default = d_opt ; vardec_combine = c_opt ; vardec_loc = loc } = let expected_ty = Ztypes . new_var ( ) in Zmisc . optional_unit ( combine loc ) expected_ty c_opt ; let sort = match d_opt with | Some ( d ) -> default loc expected_ty c_opt d | None -> match expected_k with | Tstatic _ -> Deftypes . static | Tany | Tdiscrete false -> Deftypes . default None c_opt | Tdiscrete true | Tcont | Tproba -> ( if S . mem n inames then Deftypes . imem else Deftypes . empty_mem ) ) in Env . add n { t_typ = expected_ty ; t_sort = sort } h0 in List . fold_left vardec Env . empty n_list
let rec build ( names , inames ) { eq_desc = desc } = let block_with_bounded ( names , inames ) let vardec acc { vardec_name = n } = S . add n acc in let bounded = List . fold_left vardec S . empty b_vars in let ( local_names , local_inames ) = build_list ( S . empty , S . empty ) eq_list in bounded , ( S . union names ( S . diff local_names bounded ) , S . union inames ( S . diff local_inames bounded ) ) in let block ( names , inames ) b = snd ( block_with_bounded ( names , inames ) b ) in match desc with | EQeq ( p , _ ) -> Vars . fv_pat S . empty names p , inames | EQder ( n , _ , _ , _ ) | EQpluseq ( n , _ ) | EQnext ( n , _ , _ ) | EQemit ( n , _ ) -> S . add n names , inames | EQinit ( n , _ ) -> S . add n names , S . add n inames | EQreset ( eq_list , _ ) | EQand ( eq_list ) | EQbefore ( eq_list ) -> build_list ( names , inames ) eq_list | EQblock ( b ) -> block ( names , inames ) b | EQpresent ( ph_list , b_opt ) -> let handler ( names , inames ) { p_body = b } = block ( names , inames ) b in let names , inames = List . fold_left handler ( names , inames ) ph_list in Zmisc . optional block ( names , inames ) b_opt | EQmatch ( _ , _ , mh_list ) -> let handler ( names , inames ) { m_body = b } = block ( names , inames ) b in List . fold_left handler ( names , inames ) mh_list | EQautomaton ( is_weak , sh_list , _ ) -> let escape ( names , inames ) { e_block = b_opt } = Zmisc . optional block ( names , inames ) b_opt in let handler ( names , inames ) { s_body = b ; s_trans = esc_list } = let bounded , ( names , inames ) = block_with_bounded ( names , inames ) b in let esc_names , esc_inames = List . fold_left escape ( names , inames ) esc_list in S . union names ( if is_weak then S . diff esc_names bounded else esc_names ) , S . union inames ( if is_weak then S . diff esc_inames bounded else esc_inames ) in List . fold_left handler ( names , inames ) sh_list | EQforall { for_index = in_list ; for_init = init_list } -> let index ( names , inames ) { desc = desc } = match desc with | Einput _ | Eindex _ -> names , inames | Eoutput ( _ , n ) -> S . add n names , inames in let init ( names , inames ) { desc = desc } = match desc with | Einit_last ( n , _ ) -> S . add n names , inames in let names , inames = List . fold_left index ( names , inames ) in_list in List . fold_left init ( names , inames ) init_list List . fold_left build ( names , inames ) eq_list
let env_of_eq_list expected_k eq_list = let names , inames = build_list ( S . empty , S . empty ) eq_list in S . fold ( fun n acc -> let sort = match expected_k with | Deftypes . Tstatic _ -> Deftypes . static | Deftypes . Tany | Deftypes . Tdiscrete false -> Deftypes . variable | Deftypes . Tcont | Deftypes . Tdiscrete true | Deftypes . Tproba -> else Deftypes . Smem ( Deftypes . empty_mem ) in Env . add n { t_typ = Ztypes . new_var ( ) ; t_sort = sort } acc ) names Env . empty
let intro_sort_of_var expected_k = match expected_k with | Deftypes . Tstatic _ -> Deftypes . static | Deftypes . Tany | Deftypes . Tdiscrete false -> Deftypes . Sval | Deftypes . Tcont | Deftypes . Tdiscrete true | Deftypes . Tproba -> Deftypes . Smem ( Deftypes . empty_mem )
let env_of_scondpat expected_k scpat = let rec env_of acc { desc = desc } = match desc with | Econdand ( sc1 , sc2 ) -> env_of ( env_of acc sc1 ) sc2 | Econdor ( sc , _ ) | Econdon ( sc , _ ) -> env_of acc sc | Econdexp _ -> acc | Econdpat ( _ , pat ) -> Vars . fv_pat S . empty acc pat in let acc = env_of S . empty scpat in S . fold ( fun n acc -> Env . add n { t_typ = Ztypes . new_var ( ) ; t_sort = intro_sort_of_var expected_k } acc ) acc Env . empty
let env_of_statepat expected_k spat = let rec env_of acc { desc = desc } = match desc with | Estate0pat _ -> acc | Estate1pat ( _ , l ) -> List . fold_left ( fun acc n -> S . add n acc ) acc l in let acc = env_of S . empty spat in S . fold ( fun n acc -> Env . add n { t_typ = Ztypes . new_var ( ) ; t_sort = intro_sort_of_var expected_k } acc ) acc Env . empty
let env_of_pattern expected_k h0 pat = let acc = Vars . fv_pat S . empty S . empty pat in S . fold ( fun n acc -> Env . add n { t_typ = Ztypes . new_var ( ) ; t_sort = intro_sort_of_var expected_k } acc ) acc h0
let env_of_pattern_list expected_k env p_list = let p_list , p = Zmisc . firsts p_list in let env = List . fold_left ( env_of_pattern ( Deftypes . Tstatic true ) ) env p_list in env_of_pattern expected_k env p