text
stringlengths
12
786k
module Lift3 ( X : sig type ( ' a1 , ' a2 , ' a3 ) t end ) = struct let lift ( type a1 b1 a2 b2 a3 b3 ) ( T : ( a1 , b1 ) t ) ( T : ( a2 , b2 ) t ) ( T : ( a3 , b3 ) t ) : ( ( a1 , a2 , a3 ) X . t , ( b1 , b2 , b3 ) X . t ) t = T ; ; end
let detuple2 ( type a1 a2 b1 b2 ) ( T : ( a1 * a2 , b1 * b2 ) t ) : ( a1 , b1 ) t * ( a2 , b2 ) t = T , T ; ;
let tuple2 ( type a1 a2 b1 b2 ) ( T : ( a1 , b1 ) t ) ( T : ( a2 , b2 ) t ) : ( a1 * a2 , b1 * b2 ) t = T
module type Injective = sig type ' a t val strip : ( ' a t , ' b t ) equal -> ( ' a , ' b ) equal end
module type Injective2 = sig type ( ' a1 , ' a2 ) t val strip : ( ( ' a1 , ' a2 ) t , ( ' b1 , ' b2 ) t ) equal -> ( ' a1 , ' b1 ) equal * ( ' a2 , ' b2 ) equal end
module Composition_preserves_injectivity ( M1 : Injective ) ( M2 : Injective ) = struct type ' a t = ' a M1 . t M2 . t let strip e = M1 . strip ( M2 . strip e ) end
module Obj = struct module Extension_constructor = struct [ @@@ ocaml . warning " - 3 " ] let id = Caml . Obj . extension_id let of_val = Caml . Obj . extension_constructor end end
module Id = struct module Uid = Int module Witness = struct module Key = struct type _ t = . . type type_witness_int = [ ` type_witness of int ] [ @@ deriving_inline sexp_of ] let sexp_of_type_witness_int = ( fun ( ` type_witness v__005_ ) -> Sexplib0 . Sexp . List [ Sexplib0 . Sexp . Atom " type_witness " ; sexp_of_int v__005_ ] : type_witness_int -> Sexplib0 . Sexp . t ) ; ; [ @@@ end ] let sexp_of_t _sexp_of_a t = ` type_witness ( Obj . Extension_constructor . id ( Obj . Extension_constructor . of_val t ) ) |> sexp_of_type_witness_int ; ; end module type S = sig type t type _ Key . t += Key : t Key . t end type ' a t = ( module S with type t = ' a ) let sexp_of_t ( type a ) sexp_of_a ( module M : S with type t = a ) = M . Key |> Key . sexp_of_t sexp_of_a ; ; let create ( type t ) ( ) = let module M = struct type nonrec t = t type _ Key . t += Key : t Key . t end in ( module M : S with type t = t ) ; ; let uid ( type a ) ( module M : S with type t = a ) = Obj . Extension_constructor . id ( Obj . Extension_constructor . of_val M . Key ) ; ; let some_t = Some T let same ( type a b ) ( a : a t ) ( b : b t ) : ( a , b ) equal option = let module A = ( val a : S with type t = a ) in let module B = ( val b : S with type t = b ) in match A . Key with | B . Key -> some_t | _ -> None ; ; end type ' a t = { witness : ' a Witness . t ; name : string ; to_sexp : ' a -> Sexp . t } let sexp_of_t _ { witness ; name ; to_sexp } : Sexp . t = if am_testing then Atom name else List [ List [ Atom " name " ; Atom name ] ; List [ Atom " witness " ; witness |> Witness . sexp_of_t to_sexp ] ] ; ; let to_sexp t = t . to_sexp let name t = t . name let create ~ name to_sexp = { witness = Witness . create ( ) ; name ; to_sexp } let uid t = Witness . uid t . witness let hash t = uid t let hash_fold_t s t = hash_fold_int s ( uid t ) let same_witness t1 t2 = Witness . same t1 . witness t2 . witness let same t1 t2 = Option . is_some ( same_witness t1 t2 ) let same_witness_exn t1 t2 = match same_witness t1 t2 with | Some w -> w | None -> Error . raise_s ( Sexp . message " Type_equal . Id . same_witness_exn got different ids " [ ( " " , sexp_of_pair ( sexp_of_t sexp_of_opaque ) ( sexp_of_t sexp_of_opaque ) ( t1 , t2 ) ) ] ) ; ; end
[ %% expect { | ^ bool because it is in the condition of an if - statement } ] ; ; | [ %% expect { | ^ bool because it is in the condition of an if - statement } ] ; ; | [ %% expect { | ^ int } ] ; ; | [ %% expect { | ^ bool because it is in the condition of an if - statement } ] ; ; | [ %% expect { | ^ bool because it is in the condition of an if - statement } ] ; ; | [ %% expect { | ^ unit because it is in the result of a conditional with no else branch } ] ; ; | [ %% expect { | ^^^^^^^^^^^^ bool because it is in the condition of an if - statement } ] ; ; | [ %% expect { | ^^ bool because it is in the condition of a while - loop } ] ; ; | [ %% expect { | ^^^^^^^^^^^^^^^^^^^^^^^ unit because it is in the body of a while - loop } ] ; ; | [ %% expect { | ^^ int because it is in a for - loop start index } ] ; ; | [ %% expect { | ^^ int because it is in a for - loop stop index } ] ; ; | [ %% expect { | ^^^^^^^^^^^^^^^^^^^^^^^ unit because it is in the body of a for - loop } ] ; ; | [ %% expect { | ^^ bool because it is in the condition of an assertion } ] ; ; | [ %% expect { | ^^^^^^^^^^^^^^^^^^ unit because it is in the left - hand side of a sequence } ] ; ; |
let ordered_list_with x y = if x <= y then [ x ; y ] else if x > y then [ y ; x ] [ %% expect { | ^^^^ because it is in the result of a conditional with no else branch The constructor :: does not belong to type unit } ] ; ; | ( function | y when y + 1 -> ( ) | _ -> ( ) ) ; ; [ %% expect { | ^^^^^ bool because it is in a when - guard } ] ; ; |
module Helper ( A : Variant_and_record_intf . S ) ( B : Variant_and_record_intf . S ) = struct type map = { map : ' a . ' a A . t -> ' a B . t } let map_variant ( type variant ) { map } ( variant : variant A . Variant . t ) = let map_create = function | A . Tag . Args fct -> B . Tag_internal . Args fct | A . Tag . Const k -> B . Tag_internal . Const k in let map_tag tag = match tag with | A . Variant . Tag tag -> let label = A . Tag . label tag in let rep = map ( A . Tag . traverse tag ) in let arity = A . Tag . arity tag in let args_labels = A . Tag . args_labels tag in let index = A . Tag . index tag in let ocaml_repr = A . Tag . ocaml_repr tag in let tyid = A . Tag . tyid tag in let create = map_create ( A . Tag . create tag ) in B . Variant_internal . Tag ( B . Tag . internal_use_only { B . Tag_internal . label ; rep ; arity ; args_labels ; index ; ocaml_repr ; tyid ; create } ) in let typename = A . Variant . typename_of_t variant in let polymorphic = A . Variant . is_polymorphic variant in let tags = Array . init ( A . Variant . length variant ) ( fun index -> map_tag ( A . Variant . tag variant index ) ) in let value ( a : variant ) = match A . Variant . value variant a with | A . Variant . Value ( atag , a ) -> ( fun ( type args ) ( atag : ( variant , args ) A . Tag . t ) ( a : args ) -> let ( B . Variant_internal . Tag btag ) = tags . ( A . Tag . index atag ) in ( fun ( type ex ) ( btag : ( variant , ex ) B . Tag . t ) -> let Type_equal . T = Typename . same_witness_exn ( A . Tag . tyid atag ) ( B . Tag . tyid btag ) in let btag = ( btag : ( variant , args ) B . Tag . t ) in B . Variant_internal . Value ( btag , a ) ) btag ) atag a in B . Variant . internal_use_only { B . Variant_internal . typename ; tags ; polymorphic ; value } ; ; let map_record ( type record ) { map } ( record : record A . Record . t ) = let map_field field = match field with | A . Record . Field field -> let label = A . Field . label field in let rep = map ( A . Field . traverse field ) in let index = A . Field . index field in let is_mutable = A . Field . is_mutable field in let tyid = A . Field . tyid field in let get = A . Field . get field in B . Record_internal . Field ( B . Field . internal_use_only { B . Field_internal . label ; rep ; index ; is_mutable ; tyid ; get } ) in let typename = A . Record . typename_of_t record in let has_double_array_tag = A . Record . has_double_array_tag record in let fields = Array . init ( A . Record . length record ) ( fun index -> map_field ( A . Record . field record index ) ) in let create { B . Record_internal . get } = let get ( type a ) ( afield : ( _ , a ) A . Field . t ) = match fields . ( A . Field . index afield ) with | B . Record_internal . Field bfield -> ( fun ( type ex ) ( bfield : ( record , ex ) B . Field . t ) -> let Type_equal . T = Typename . same_witness_exn ( A . Field . tyid afield ) ( B . Field . tyid bfield ) in let bfield = ( bfield : ( record , a ) B . Field . t ) in get bfield ) bfield in A . Record . create record { A . Record . get } in B . Record . internal_use_only { B . Record_internal . typename ; fields ; has_double_array_tag ; create } ; ; end
module type Named = sig type ' a computation module Context : sig type t val create : unit -> t end type ' a t val init : Context . t -> ' a Typename . t -> ' a t val get_wip_computation : ' a t -> ' a computation val set_final_computation : ' a t -> ' a computation -> ' a computation val share : _ Typerep . t -> bool end
module type Computation = sig type ' a t include Variant_and_record_intf . S with type ' a t := ' a t val int : int t val int32 : int32 t val int64 : int64 t val nativeint : nativeint t val char : char t val float : float t val string : string t val bytes : bytes t val bool : bool t val unit : unit t val option : ' a t -> ' a option t val list : ' a t -> ' a list t val array : ' a t -> ' a array t val lazy_t : ' a t -> ' a lazy_t t val ref_ : ' a t -> ' a ref t val function_ : ' a t -> ' b t -> ( ' a -> ' b ) t val tuple2 : ' a t -> ' b t -> ( ' a * ' b ) t val tuple3 : ' a t -> ' b t -> ' c t -> ( ' a * ' b * ' c ) t val tuple4 : ' a t -> ' b t -> ' c t -> ' d t -> ( ' a * ' b * ' c * ' d ) t val tuple5 : ' a t -> ' b t -> ' c t -> ' d t -> ' e t -> ( ' a * ' b * ' c * ' d * ' e ) t val record : ' a Record . t -> ' a t val variant : ' a Variant . t -> ' a t module Named : Named with type ' a computation := ' a t end
module Make_named_for_closure ( X : sig type ' a input type ' a output type ' a t = ' a input -> ' a output end ) = struct module Context = struct type t = unit let create = ignore end type ' a t = { runtime_dereference : ' a X . t ; runtime_reference : ' a X . t ref ; compiletime_dereference : ' a X . t option ref } exception Undefined of string let init ( ) name = let path = Typename . Uid . name ( Typename . uid name ) in let r = ref ( fun _ -> raise ( Undefined path ) ) in { runtime_dereference = ( fun input -> ! r input ) ; runtime_reference = r ; compiletime_dereference = ref None } ; ; let get_wip_computation shared = match shared . compiletime_dereference . contents with | Some clos -> clos | None -> shared . runtime_dereference ; ; let set_final_computation shared computation = let compiletime_dereference = shared . compiletime_dereference in match compiletime_dereference . contents with | Some _ -> assert false | None -> if Base . phys_equal shared . runtime_dereference computation then assert false ; compiletime_dereference := Some computation ; shared . runtime_reference := computation ; computation ; ; let share _ = true end
module Ident = struct type t = { name : string ; implements : Typename . Uid . t -> bool } exception Broken_dependency of string let check_dependencies name required = match required with | [ ] -> fun _ -> ( ) | _ -> fun uid -> List . iter ( fun { name = name ' ; implements } -> if not ( implements uid ) then ( let message = Printf . sprintf " Type_generic % S requires % S for uid % S \ n " name name ' ( Typename . Uid . name uid ) in prerr_endline message ; raise ( Broken_dependency message ) ) ) required ; ; end
module type Extending = sig type ' a t type ' a computation = ' a t val ident : Ident . t exception Not_implemented of string * string module type S = sig type t include Typerepable . S with type t := t val compute : t computation end module type S1 = sig type ' a t include Typerepable . S1 with type ' a t := ' a t val compute : ' a computation -> ' a t computation end module type S2 = sig type ( ' a , ' b ) t include Typerepable . S2 with type ( ' a , ' b ) t := ( ' a , ' b ) t val compute : ' a computation -> ' b computation -> ( ' a , ' b ) t computation end module type S3 = sig type ( ' a , ' b , ' c ) t include Typerepable . S3 with type ( ' a , ' b , ' c ) t := ( ' a , ' b , ' c ) t val compute : ' a computation -> ' b computation -> ' c computation -> ( ' a , ' b , ' c ) t computation end module type S4 = sig type ( ' a , ' b , ' c , ' d ) t include Typerepable . S4 with type ( ' a , ' b , ' c , ' d ) t := ( ' a , ' b , ' c , ' d ) t val compute : ' a computation -> ' b computation -> ' c computation -> ' d computation -> ( ' a , ' b , ' c , ' d ) t computation end module type S5 = sig type ( ' a , ' b , ' c , ' d , ' e ) t include Typerepable . S5 with type ( ' a , ' b , ' c , ' d , ' e ) t := ( ' a , ' b , ' c , ' d , ' e ) t val compute : ' a computation -> ' b computation -> ' c computation -> ' d computation -> ' e computation -> ( ' a , ' b , ' c , ' d , ' e ) t computation end val register0 : ( module S ) -> unit val register1 : ( module S1 ) -> unit val register2 : ( module S2 ) -> unit val register3 : ( module S3 ) -> unit val register4 : ( module S4 ) -> unit val register5 : ( module S5 ) -> unit val register : ' a Typerep . t -> ' a computation -> unit end
module type S_implementation = sig include Extending val raise_not_implemented : string -> ' a type implementation = { generic : ' a . ' a Typerep . t -> ' a computation } val _using_extended_implementation : implementation -> ' a Typerep . Named . t -> ' a Typerep . t lazy_t option -> ' a computation val find_extended_implementation : implementation -> ' a Typerep . Named . t -> ' a computation option end
module type S = sig include Extending val of_typerep : ' a Typerep . t -> [ ` generic of ' a computation ] module Computation : Computation with type ' a t = ' a t end
module Make_S_implementation ( X : sig type ' a t val name : string val required : Ident . t list end ) : S_implementation with type ' a t = ' a X . t = struct type ' a t = ' a X . t type ' a computation = ' a t include Type_generic_intf . M ( struct type ' a t = ' a computation end ) module Uid_table = struct include Hashtbl . Make ( Typename . Uid ) let find table key = if Lazy . is_val table then ( let table = Lazy . force table in try Some ( find table key ) with | Base . Not_found_s _ | Caml . Not_found -> None ) else None ; ; let check_dependencies = Ident . check_dependencies X . name X . required let replace table key value = check_dependencies key ; replace ( Lazy . force table ) key value ; ; let mem table key = if Lazy . is_val table then ( let table = Lazy . force table in mem table key ) else false ; ; end let size = 256 let table0 = lazy ( Uid_table . create size ) let table1 = lazy ( Uid_table . create size ) let table2 = lazy ( Uid_table . create size ) let table3 = lazy ( Uid_table . create size ) let table4 = lazy ( Uid_table . create size ) let table5 = lazy ( Uid_table . create size ) let is_registered uid = Uid_table . mem table0 uid || Uid_table . mem table1 uid || Uid_table . mem table2 uid || Uid_table . mem table3 uid || Uid_table . mem table4 uid || Uid_table . mem table5 uid ; ; let ident = { Ident . name = X . name ; implements = is_registered } module Find0 ( T : Typerep . Named . T0 ) : sig val compute : unit -> T . named computation option end = struct let compute ( ) = match Uid_table . find table0 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S = ( val rep : S ) in let witness = Typename . same_witness_exn S . typename_of_t T . typename_of_named in let module L = Type_equal . Lift ( struct type ' a t = ' a computation end ) in Some ( Type_equal . conv ( L . lift witness ) S . compute ) ; ; end module Find1 ( T : Typerep . Named . T1 ) : sig val compute : unit -> ( T . a computation -> T . a T . named computation ) option end = struct let compute ( ) = match Uid_table . find table1 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S1 = ( val rep : S1 ) in let module Conv = Typename . Same_witness_exn_1 ( S1 ) ( struct type ' a t = ' a T . named let typename_of_t = T . typename_of_named end ) in let module L = Type_equal . Lift ( struct type ' a t = T . a computation -> ' a computation end ) in Some ( Type_equal . conv ( L . lift Conv . ( witness . eq ) ) S1 . compute ) ; ; end module Find2 ( T : Typerep . Named . T2 ) : sig val compute : unit -> ( T . a computation -> T . b computation -> ( T . a , T . b ) T . named computation ) option end = struct let compute ( ) = match Uid_table . find table2 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S2 = ( val rep : S2 ) in let module Conv = Typename . Same_witness_exn_2 ( S2 ) ( struct type ( ' a , ' b ) t = ( ' a , ' b ) T . named let typename_of_t = T . typename_of_named end ) in let module L = Type_equal . Lift ( struct type ' a t = T . a computation -> T . b computation -> ' a computation end ) in Some ( Type_equal . conv ( L . lift Conv . ( witness . eq ) ) S2 . compute ) ; ; end module Find3 ( T : Typerep . Named . T3 ) : sig val compute : unit -> ( T . a computation -> T . b computation -> T . c computation -> ( T . a , T . b , T . c ) T . named computation ) option end = struct let compute ( ) = match Uid_table . find table3 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S3 = ( val rep : S3 ) in let module Conv = Typename . Same_witness_exn_3 ( S3 ) ( struct type ( ' a , ' b , ' c ) t = ( ' a , ' b , ' c ) T . named let typename_of_t = T . typename_of_named end ) in let module L = Type_equal . Lift ( struct type ' a t = T . a computation -> T . b computation -> T . c computation -> ' a computation end ) in Some ( Type_equal . conv ( L . lift Conv . ( witness . eq ) ) S3 . compute ) ; ; end module Find4 ( T : Typerep . Named . T4 ) : sig val compute : unit -> ( T . a computation -> T . b computation -> T . c computation -> T . d computation -> ( T . a , T . b , T . c , T . d ) T . named computation ) option end = struct let compute ( ) = match Uid_table . find table4 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S4 = ( val rep : S4 ) in let module Conv = Typename . Same_witness_exn_4 ( S4 ) ( struct type ( ' a , ' b , ' c , ' d ) t = ( ' a , ' b , ' c , ' d ) T . named let typename_of_t = T . typename_of_named end ) in let module L = Type_equal . Lift ( struct type ' a t = T . a computation -> T . b computation -> T . c computation -> T . d computation -> ' a computation end ) in Some ( Type_equal . conv ( L . lift Conv . ( witness . eq ) ) S4 . compute ) ; ; end module Find5 ( T : Typerep . Named . T5 ) : sig val compute : unit -> ( T . a computation -> T . b computation -> T . c computation -> T . d computation -> T . e computation -> ( T . a , T . b , T . c , T . d , T . e ) T . named computation ) option end = struct let compute ( ) = match Uid_table . find table5 ( Typename . uid T . typename_of_t ) with | None -> None | Some rep -> let module S5 = ( val rep : S5 ) in let module Conv = Typename . Same_witness_exn_5 ( S5 ) ( struct type ( ' a , ' b , ' c , ' d , ' e ) t = ( ' a , ' b , ' c , ' d , ' e ) T . named let typename_of_t = T . typename_of_named end ) in let module L = Type_equal . Lift ( struct type ' a t = T . a computation -> T . b computation -> T . c computation -> T . d computation -> T . e computation -> ' a computation end ) in Some ( Type_equal . conv ( L . lift Conv . ( witness . eq ) ) S5 . compute ) ; ; end let unit = Typename . static let register0 compute = let module S = ( val compute : S ) in let uid = Typename . uid S . typename_of_t in Uid_table . replace table0 uid compute ; ; let register1 compute = let module S1 = ( val compute : S1 ) in let uid = Typename . uid ( S1 . typename_of_t unit ) in Uid_table . replace table1 uid compute ; ; let register2 compute = let module S2 = ( val compute : S2 ) in let uid = Typename . uid ( S2 . typename_of_t unit unit ) in Uid_table . replace table2 uid compute ; ; let register3 compute = let module S3 = ( val compute : S3 ) in let uid = Typename . uid ( S3 . typename_of_t unit unit unit ) in Uid_table . replace table3 uid compute ; ; let register4 compute = let module S4 = ( val compute : S4 ) in let uid = Typename . uid ( S4 . typename_of_t unit unit unit unit ) in Uid_table . replace table4 uid compute ; ; let register5 compute = let module S5 = ( val compute : S5 ) in let uid = Typename . uid ( S5 . typename_of_t unit unit unit unit unit ) in Uid_table . replace table5 uid compute ; ; let register ( type a ) typerep_of_a compute = let module S = struct type t = a let typename_of_t = Typerep . typename_of_t typerep_of_a let typerep_of_t = typerep_of_a let compute = compute end in register0 ( module S : S ) ; ; type implementation = { generic : ' a . ' a Typerep . t -> ' a computation } let find_extended_implementation ( type a ) aux = function | Typerep . Named . T0 rep -> let module T = ( val rep : Typerep . Named . T0 with type t = a ) in let module Custom = Find0 ( T ) in ( match Custom . compute ( ) with | Some custom -> let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) | Typerep . Named . T1 rep -> let module T = ( val rep : Typerep . Named . T1 with type t = a ) in let module Custom = Find1 ( T ) in ( match Custom . compute ( ) with | Some custom -> let custom = ( custom ( aux . generic T . a ) : T . a T . named computation ) in let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) | Typerep . Named . T2 rep -> let module T = ( val rep : Typerep . Named . T2 with type t = a ) in let module Custom = Find2 ( T ) in ( match Custom . compute ( ) with | Some custom -> let custom = ( custom ( aux . generic T . a ) ( aux . generic T . b ) : ( T . a , T . b ) T . named computation ) in let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) | Typerep . Named . T3 rep -> let module T = ( val rep : Typerep . Named . T3 with type t = a ) in let module Custom = Find3 ( T ) in ( match Custom . compute ( ) with | Some custom -> let custom = ( custom ( aux . generic T . a ) ( aux . generic T . b ) ( aux . generic T . c ) : ( T . a , T . b , T . c ) T . named computation ) in let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) | Typerep . Named . T4 rep -> let module T = ( val rep : Typerep . Named . T4 with type t = a ) in let module Custom = Find4 ( T ) in ( match Custom . compute ( ) with | Some custom -> let custom = ( custom ( aux . generic T . a ) ( aux . generic T . b ) ( aux . generic T . c ) ( aux . generic T . d ) : ( T . a , T . b , T . c , T . d ) T . named computation ) in let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) | Typerep . Named . T5 rep -> let module T = ( val rep : Typerep . Named . T5 with type t = a ) in let module Custom = Find5 ( T ) in ( match Custom . compute ( ) with | Some custom -> let custom = ( custom ( aux . generic T . a ) ( aux . generic T . b ) ( aux . generic T . c ) ( aux . generic T . d ) ( aux . generic T . e ) : ( T . a , T . b , T . c , T . d , T . e ) T . named computation ) in let Type_equal . T = T . witness in Some ( custom : a computation ) | None -> None ) ; ; exception Not_implemented of string * string let raise_not_implemented string = raise ( Not_implemented ( X . name , string ) ) let _using_extended_implementation aux rep content = match find_extended_implementation aux rep with | Some computation -> computation | None -> ( match content with | Some ( lazy content ) -> aux . generic content | None -> let typename = Typerep . Named . typename_of_t rep in let name = Typename . Uid . name ( Typename . uid typename ) in raise_not_implemented name ) ; ; end
module _ = Hashtbl . Make ( Typename . Key )
module Make ( X : sig type ' a t val name : string val required : Ident . t list include Computation with type ' a t := ' a t end ) = struct module Computation = X include Make_S_implementation ( X ) module Memo = Typename . Table ( struct type ' a t = ' a X . Named . t end ) module Helper = Helper ( Typerep ) ( Computation ) let of_typerep rep = let context = X . Named . Context . create ( ) in let memo_table = Memo . create 32 in let rec of_typerep : type a . a Typerep . t -> a t = function | Typerep . Int -> X . int | Typerep . Int32 -> X . int32 | Typerep . Int64 -> X . int64 | Typerep . Nativeint -> X . nativeint | Typerep . Char -> X . char | Typerep . Float -> X . float | Typerep . String -> X . string | Typerep . Bytes -> X . bytes | Typerep . Bool -> X . bool | Typerep . Unit -> X . unit | Typerep . Option rep -> X . option ( of_typerep rep ) | Typerep . List rep -> X . list ( of_typerep rep ) | Typerep . Array rep -> X . array ( of_typerep rep ) | Typerep . Lazy rep -> X . lazy_t ( of_typerep rep ) | Typerep . Ref rep -> X . ref_ ( of_typerep rep ) | Typerep . Function ( dom , rng ) -> X . function_ ( of_typerep dom ) ( of_typerep rng ) | Typerep . Tuple tuple -> ( match tuple with | Typerep . Tuple . T2 ( a , b ) -> let ra = of_typerep a in let rb = of_typerep b in X . tuple2 ra rb | Typerep . Tuple . T3 ( a , b , c ) -> let ra = of_typerep a in let rb = of_typerep b in let rc = of_typerep c in X . tuple3 ra rb rc | Typerep . Tuple . T4 ( a , b , c , d ) -> let ra = of_typerep a in let rb = of_typerep b in let rc = of_typerep c in let rd = of_typerep d in X . tuple4 ra rb rc rd | Typerep . Tuple . T5 ( a , b , c , d , e ) -> let ra = of_typerep a in let rb = of_typerep b in let rc = of_typerep c in let rd = of_typerep d in let re = of_typerep e in X . tuple5 ra rb rc rd re ) | Typerep . Record record -> X . record ( Helper . map_record { Helper . map = of_typerep } record ) | Typerep . Variant variant -> X . variant ( Helper . map_variant { Helper . map = of_typerep } variant ) | Typerep . Named ( named , content ) -> let typename = Typerep . Named . typename_of_t named in ( match Memo . find memo_table typename with | Some shared -> X . Named . get_wip_computation shared | None -> ( match find_extended_implementation { generic = of_typerep } named with | Some computation -> computation | None -> ( match content with | None -> let name = Typename . Uid . name ( Typename . uid typename ) in raise_not_implemented name | Some ( lazy content ) -> if X . Named . share content then ( let shared = X . Named . init context typename in Memo . set memo_table typename shared ; let computation = of_typerep content in X . Named . set_final_computation shared computation ) else of_typerep content ) ) ) in let computation = of_typerep rep in ` generic computation ; ; end
module M ( X : sig type ' a t end ) = struct module type S = sig type t include Typerepable . S with type t := t val compute : t X . t end module type S1 = sig type ' a t include Typerepable . S1 with type ' a t := ' a t val compute : ' a X . t -> ' a t X . t end module type S2 = sig type ( ' a , ' b ) t include Typerepable . S2 with type ( ' a , ' b ) t := ( ' a , ' b ) t val compute : ' a X . t -> ' b X . t -> ( ' a , ' b ) t X . t end module type S3 = sig type ( ' a , ' b , ' c ) t include Typerepable . S3 with type ( ' a , ' b , ' c ) t := ( ' a , ' b , ' c ) t val compute : ' a X . t -> ' b X . t -> ' c X . t -> ( ' a , ' b , ' c ) t X . t end module type S4 = sig type ( ' a , ' b , ' c , ' d ) t include Typerepable . S4 with type ( ' a , ' b , ' c , ' d ) t := ( ' a , ' b , ' c , ' d ) t val compute : ' a X . t -> ' b X . t -> ' c X . t -> ' d X . t -> ( ' a , ' b , ' c , ' d ) t X . t end module type S5 = sig type ( ' a , ' b , ' c , ' d , ' e ) t include Typerepable . S5 with type ( ' a , ' b , ' c , ' d , ' e ) t := ( ' a , ' b , ' c , ' d , ' e ) t val compute : ' a X . t -> ' b X . t -> ' c X . t -> ' d X . t -> ' e X . t -> ( ' a , ' b , ' c , ' d , ' e ) t X . t end end
module type S = sig type ' a t include module type of M ( struct type ' a computation = ' a t type ' a t = ' a computation end ) end
module Make ( D : Debugger . S ) ( Cmt_cache : Cmt_cache_intf . S ) = struct let type_and_env_from_dwarf_type0 ~ dwarf_type ~ cmt_cache = let cmt_file_and_ident_name = match Dwarf_name_laundry . split_base_type_die_name dwarf_type with | None -> None | Some { compilation_unit ; ident_name ; ident_stamp ; is_parameter ; } -> let compilation_unit = Compilation_unit . create ( Ident . create_persistent compilation_unit ) ( Linkage_name . create ( Compilenv . make_symbol ~ unitname : compilation_unit None ) ) in match Cmt_cache . load cmt_cache compilation_unit with | None -> None | Some cmt -> Some ( cmt , ident_name , ident_stamp , is_parameter ) in match cmt_file_and_ident_name with | None -> None | Some ( cmt_file , name , stamp , is_parameter ) -> match Cmt_file . type_of_ident cmt_file ~ name ~ stamp with | None -> None | Some ( ty , env ) -> Some ( ty , env , is_parameter ) let type_is_polymorphic env ty = Btype . fold_type_expr ( fun is_poly ty -> is_poly || Btype . is_Tvar ( Ctype . expand_head env ty ) ) false ty let rec type_and_env_from_dwarf_type ~ dwarf_type ~ cmt_cache frame = if Monda_debug . debug then begin Printf . fprintf stdout " Checking DWARF type % s \ n " dwarf_type end ; match type_and_env_from_dwarf_type0 ~ dwarf_type ~ cmt_cache with | None -> if Monda_debug . debug then begin Printf . fprintf stdout " Couldn ' t get OCaml type + env \ n " end ; None | ( Some ( ty , env , is_parameter ) ) as result -> match ty with | Module _ -> result | Core ty -> let ty = Ctype . expand_head env ty in let normal_case ( ) = Some ( Cmt_file . Core ty , env , is_parameter ) in if type_is_polymorphic env ty && not ( D . Frame . inlined frame ) then begin if Monda_debug . debug then begin Printf . fprintf stdout " Type is polymorphic . \ n " end ; match is_parameter with | Local -> if Monda_debug . debug then begin Printf . fprintf stdout " Not a parameter . \ n " end ; normal_case ( ) | Parameter { index ; } -> if Monda_debug . debug then begin Printf . fprintf stdout " Type is polymorphic and that of a parameter . \ n " end ; match D . Frame . caller frame with | No_caller -> if Monda_debug . debug then begin Printf . fprintf stdout " Couldn ' t find caller frame . \ n " end ; normal_case ( ) | Caller ( caller_frame , call_site ) -> if Monda_debug . debug then begin Printf . fprintf stdout " Found caller frame . \ n " end ; match D . Call_site . dwarf_type_of_argument call_site ~ index with | None -> if Monda_debug . debug then begin Printf . fprintf stdout " Couldn ' t find DWARF arg type . \ n " end ; begin match D . Call_site . line_number call_site , D . Call_site . column_number call_site with | None , None | None , Some _ | Some _ , None -> if Monda_debug . debug then begin Printf . fprintf stdout " Couldn ' t find call site location . \ n " end ; normal_case ( ) | Some line , Some column -> match D . Call_site . ocaml_specific_compilation_unit_info call_site with | None -> if Monda_debug . debug then begin Printf . fprintf stdout " Couldn ' t find unit info . \ n " end ; normal_case ( ) | Some unit_info -> let comp_unit = Compilation_unit . create unit_info . unit_name ( Linkage_name . create ( Compilenv . make_symbol ~ unitname ( : Ident . name unit_info . unit_name ) None ) ) in match Cmt_cache . load cmt_cache comp_unit with | None -> if Monda_debug . debug then begin Printf . fprintf stdout " . cmt load failed \ n " end ; normal_case ( ) | Some call_site_cmt -> match Cmt_file . type_of_call_site_argument call_site_cmt ~ line ~ column ~ index with | None -> if Monda_debug . debug then begin Printf . fprintf stdout " type lookup failed ( line % d , column % d ) \ n " line column end ; normal_case ( ) | Some ( ty , env ) -> if Monda_debug . debug then begin Printf . fprintf stdout " type lookup ok ( line % d , column % d ) \ n " line column end ; Some ( ty , env , is_parameter ) end | Some dwarf_type -> type_and_env_from_dwarf_type ~ dwarf_type ~ cmt_cache caller_frame end else begin if Monda_debug . debug then begin Printf . fprintf stdout " Type is not polymorphic . \ n " end ; normal_case ( ) end end
let helpers_error msg = raise ( Type_helpers_error msg )
let michelson_type_to_ex_ty ( typ : Alpha_context . Script . expr ) ( ctxt : Alpha_context . t ) = Script_ir_translator . parse_ty ctxt ~ legacy : false ~ allow_lazy_storage : false ~ allow_operation : false ~ allow_contract : false ~ allow_ticket : false ( Micheline . root typ ) |> Environment . wrap_tzresult |> function | Ok ( ex_ty , _ctxt ) -> ex_ty | Error errs -> let msg = Format . asprintf " Michelson_generation . michelson_type_to_ex_ty ( % a ) " Error_monad . pp_print_trace errs in helpers_error msg
let rec michelson_type_list_to_ex_stack_ty ( stack_ty : Alpha_context . Script . expr list ) ctxt = let open Script_ir_translator in let open Script_typed_ir in match stack_ty with | [ ] -> Ex_stack_ty Bot_t | hd :: tl -> ( let ex_ty = michelson_type_to_ex_ty hd ctxt in match ex_ty with | Ex_ty ty -> ( let ex_stack_ty = michelson_type_list_to_ex_stack_ty tl ctxt in match ex_stack_ty with | Ex_stack_ty tl -> Ex_stack_ty ( Item_t ( ty , tl ) ) ) )
let base_type_to_michelson_type ( typ : Type . Base . t ) = let typ = Mikhailsky . map_var ( fun _ -> Mikhailsky . unit_ty ) typ in Mikhailsky . to_michelson typ
let rec stack_type_to_michelson_type_list ( typ : Type . Stack . t ) = let node = typ . node in match node with | Type . Stack . Stack_var_t _ -> helpers_error " stack_type_to_michelson_type_list : bug found " | Type . Stack . Empty_t -> [ ] | Type . Stack . Item_t ( ty , tl ) -> base_type_to_michelson_type ty :: stack_type_to_michelson_type_list tl
let base_type_to_ex_ty ty = michelson_type_to_ex_ty ( base_type_to_michelson_type ty )
module Key = struct type t = int [ @@ deriving compare , sexp_of ] let hash x = x end
module Allowed_ints = struct type t = | None | All | Hash_set of Hash_set . M ( Key ) . t | From_zero_to of int let _invariant = function | None | All | Hash_set _ -> ( ) | From_zero_to n -> assert ( n >= 0 ) ; ; let int_is_value t i = match t with | None -> false | All -> true | Hash_set hash_set -> Hash_set . mem hash_set i | From_zero_to n -> 0 <= i && i <= n ; ; end
module Immediacy = struct type t = | Always | Sometimes | Never [ @@ deriving compare ] let equal = [ % compare . equal : t ] let to_string = function | Always -> " Always " | Sometimes -> " Sometimes " | Never -> " Never " ; ; end
module T : sig type ' a t val create : ' a Typename . t -> Immediacy . t -> Allowed_ints . t -> ' a t val create_with_name : string -> Immediacy . t -> Allowed_ints . t -> _ t val immediacy : _ t -> Immediacy . t val allowed_ints : _ t -> Allowed_ints . t val typename : _ t -> string module Never_values : sig val int32 : int32 t val int64 : int64 t val nativeint : nativeint t val float : float t val string : string t val bytes : bytes t val array : _ array t val ref_ : _ ref t val tuple2 : ( _ * _ ) t val tuple3 : ( _ * _ * _ ) t val tuple4 : ( _ * _ * _ * _ ) t val tuple5 : ( _ * _ * _ * _ * _ ) t val function_ : ( _ -> _ ) t end val never : ' a Typename . t -> ' a t val option : _ t val list : _ t val magic : _ t -> _ t type t_ = { immediacy : Immediacy . t ; allowed_ints : Allowed_ints . t ; typename : string } type ' a t = t_ let create_with_name typename immediacy allowed_ints = { immediacy ; allowed_ints ; typename } ; ; let create typename immediacy allowed_ints = create_with_name ( Typename . name typename ) immediacy allowed_ints ; ; let immediacy t = t . immediacy let allowed_ints t = t . allowed_ints let typename t = t . typename let magic t = t let never_with_name name = create_with_name name Never Allowed_ints . None let never typename = create typename Never Allowed_ints . None let option = create_with_name " option " Sometimes ( Allowed_ints . From_zero_to 0 ) let list = create_with_name " list " Sometimes ( Allowed_ints . From_zero_to 0 ) module Never_values = struct let int32 = never typename_of_int32 let int64 = never typename_of_int64 let nativeint = never typename_of_nativeint let float = never typename_of_float let string = never typename_of_string let bytes = never typename_of_bytes let array = never_with_name " array " let ref_ = never_with_name " ref " let tuple2 = never_with_name " tuple2 " let tuple3 = never_with_name " tuple3 " let tuple4 = never_with_name " tuple4 " let tuple5 = never_with_name " tuple5 " let function_ = never_with_name " function " end end
let int = create typename_of_int Always Allowed_ints . All
let unit = create typename_of_unit Always ( Allowed_ints . From_zero_to 0 )
let bool = create typename_of_bool Always ( Allowed_ints . From_zero_to 1 )
let char = create typename_of_char Always ( Allowed_ints . From_zero_to 255 )
module Computation_impl = struct type nonrec ' a t = ' a t include Type_generic . Variant_and_record_intf . M ( struct type nonrec ' a t = ' a t end ) include Never_values let ref_ _ = ref_ let array _ = array let tuple2 _ _ = tuple2 let tuple3 _ _ _ = tuple3 let tuple4 _ _ _ _ = tuple4 let tuple5 _ _ _ _ _ = tuple5 let function_ _ _ = function_ let int = int let char = char let bool = bool let unit = unit let option _ = option let list _ = list let lazy_t t = let immediacy = match immediacy t with | Never -> Never | Sometimes | Always -> Sometimes in create_with_name " lazy_t " immediacy ( allowed_ints t ) ; ; let record r = never ( Record . typename_of_t r ) let variant variant = let no_arg_list = List . rev ( Variant . fold variant ~ init [ ] : ~ f ( : fun list tag -> match tag with | Variant . Tag t -> if Tag . arity t = 0 then tag :: list else list ) ) in let no_arg_count = List . length no_arg_list in if no_arg_count = 0 then never ( Variant . typename_of_t variant ) else ( let allowed_ints = if not ( Variant . is_polymorphic variant ) then Allowed_ints . From_zero_to ( no_arg_count - 1 ) else ( let hash_set = Hash_set . create ( module Key ) ~ size ( : no_arg_count * 2 ) in List . iter no_arg_list ~ f ( : function Variant . Tag tag -> ( match Tag . create tag with | Tag . Const _ -> Hash_set . add hash_set ( Tag . ocaml_repr tag ) | Tag . Args _ -> assert false ) ) ; Allowed_ints . Hash_set hash_set ) in let immediacy = if Variant . length variant > no_arg_count then Immediacy . Sometimes else Immediacy . Always in create ( Variant . typename_of_t variant ) immediacy allowed_ints ) ; ; let name = " is_immediate " let required = [ ] module Named = struct module Context = struct type t = unit let create ( ) = ( ) end type nonrec ' a t = ' a t ref let init _ name = ref ( create name Sometimes Allowed_ints . None ) let get_wip_computation comp = ! comp let set_final_computation r t = r := t ; t ; ; let share _ = true end end
module Generic = Type_generic . Make ( Computation_impl )
let of_typerep typerep = let ( ` generic t ) = Generic . of_typerep typerep in t ; ;
module For_all_parameters ( M : sig val immediacy : Immediacy . t end ) = struct let witness typerep1 typerep2 = let t1 = of_typerep typerep1 in let t2 = of_typerep typerep2 in let i1 = immediacy t1 in let i2 = immediacy t2 in if not ( Immediacy . equal i1 i2 ) then failwith ( sprintf " type % s is not independent of its arguments " ( Typename . name ( Typerep . typename_of_t typerep1 ) ) ) else if not ( Immediacy . equal i1 M . immediacy ) then failwith ( sprintf " type % s does not have desired immediacy : wanted % s but got % s " ( Typename . name ( Typerep . typename_of_t typerep1 ) ) ( Immediacy . to_string M . immediacy ) ( Immediacy . to_string i1 ) ) else t1 ; ; let ra = Typerep . Int let rn = Typerep . String module For_all_parameters_S1 ( X : Typerepable . S1 ) = struct let t = witness ( X . typerep_of_t ra ) ( X . typerep_of_t rn ) let witness ( ) = magic t end module For_all_parameters_S2 ( X : Typerepable . S2 ) = struct let t = witness ( X . typerep_of_t ra ra ) ( X . typerep_of_t rn rn ) let witness ( ) = magic t end module For_all_parameters_S3 ( X : Typerepable . S3 ) = struct let t = witness ( X . typerep_of_t ra ra ra ) ( X . typerep_of_t rn rn rn ) let witness ( ) = magic t end module For_all_parameters_S4 ( X : Typerepable . S4 ) = struct let t = witness ( X . typerep_of_t ra ra ra ra ) ( X . typerep_of_t rn rn rn rn ) let witness ( ) = magic t end module For_all_parameters_S5 ( X : Typerepable . S5 ) = struct let t = witness ( X . typerep_of_t ra ra ra ra ra ) ( X . typerep_of_t rn rn rn rn rn ) let witness ( ) = magic t end end
let int_is_value t int = Allowed_ints . int_is_value ( allowed_ints t ) int
let int_as_value ( type a ) ( t : a t ) int = if int_is_value t int then Some ( Obj . magic ( int : int ) : a ) else None ; ;
let int_as_value_exn ( type a ) ( t : a t ) int = if int_is_value t int then ( Obj . magic ( int : int ) : a ) else failwith ( sprintf " Immediate . int_as_value_exn : typename :% S int :% d " ( T . typename t ) int ) ; ;
let value_as_int_exn ( type a ) ( t : a t ) a = if Obj . is_int ( Obj . repr a ) then ( Obj . magic ( a : a ) : int ) else failwith ( sprintf " Immediate . value_as_int_exn : typename :% S " ( T . typename t ) ) ; ;
let value_as_int ( type a ) ( _ : a t ) a = if Obj . is_int ( Obj . repr a ) then Some ( Obj . magic ( a : a ) : int ) else None ; ;
let value_is_int ( type a ) ( _ : a t ) a = Obj . is_int ( Obj . repr a )
module Always = struct type nonrec ' a t = ' a t include For_all_parameters ( struct let immediacy = Always end ) let of_typerep typerep = let t = of_typerep typerep in match immediacy t with | Always -> Some t | Never | Sometimes -> None ; ; let of_typerep_exn here typerep = Option . value_exn ~ here ( of_typerep typerep ) let int_as_value = int_as_value let int_as_value_exn = int_as_value_exn let int_is_value = int_is_value let [ @ inline always ] value_as_int ( type a ) _ a = a |> ( Obj . magic : a -> int ) let int = int let char = char let bool = bool let unit = unit end
module Sometimes = struct type nonrec ' a t = ' a t include For_all_parameters ( struct let immediacy = Sometimes end ) let of_typerep typerep = let t = of_typerep typerep in match immediacy t with | Sometimes -> Some t | Always | Never -> None ; ; let of_typerep_exn here typerep = Option . value_exn ~ here ( of_typerep typerep ) let int_as_value = int_as_value let int_as_value_exn = int_as_value_exn let int_is_value = int_is_value let value_as_int = value_as_int let value_as_int_exn = value_as_int_exn let value_is_int = value_is_int let option = option let list = list end
module Never = struct type nonrec ' a t = ' a t include For_all_parameters ( struct let immediacy = Never end ) let of_typerep typerep = let t = of_typerep typerep in match immediacy t with | Never -> Some t | Always | Sometimes -> None ; ; let of_typerep_exn here typerep = Option . value_exn ~ here ( of_typerep typerep ) include Never_values end
type ' a dest = | Always of ' a Always . t | Sometimes of ' a Sometimes . t | Never of ' a Never . t
let dest t = let module I = Immediacy in match immediacy t with | I . Always -> Always t | I . Sometimes -> Sometimes t | I . Never -> Never t ; ;
( module struct module Typerep_obj = Typerep_lib . Std . Typerep_obj type ' a t = { int_as_value : int -> ' a option ; int_as_value_exn : int -> ' a ; int_is_value : int -> bool ; value_as_int : ' a -> int option ; value_as_int_exn : ' a -> int ; value_is_int : ' a -> bool } let get_conv typerep_of_t = let immediacy = Type_immediacy . of_typerep typerep_of_t in let int_as_value i = Type_immediacy . int_as_value immediacy i in let int_as_value_exn i = Type_immediacy . int_as_value_exn immediacy i in let int_is_value i = Type_immediacy . int_is_value immediacy i in let value_as_int a = Type_immediacy . value_as_int immediacy a in let value_as_int_exn a = Type_immediacy . value_as_int_exn immediacy a in let value_is_int a = Type_immediacy . value_is_int immediacy a in { int_as_value ; int_as_value_exn ; int_is_value ; value_as_int ; value_as_int_exn ; value_is_int } ; ; For [ Convertible ( v , i ) ] , we test the conversion invariants mentioned in 1 ) , i . e . we a ) check that [ v ] is immediate , and that it ' s underlying [ int ] representation is [ i ] b ) check that [ v ] converts to [ i ] , using [ value_is_int ] , and [ value_as_int ( _exn ) ] ? c ) check that [ i ] converts to [ v ] , using [ int_is_value ] , and [ int_as_value ( _exn ) ] ? | Val_does_not_convert of ' a For [ Val_does_not_convert v ] , we test that a ) [ v ] is boxed b ) the conversion functions return the appropriate results as described in 3 ) | Int_does_not_convert of ' a For [ Int_does_not_convert i ] , we test that the conversion functions return the appropriate results as described in II ) | Boxed_value_converts of ( ' a lazy_t * ' a * int ) Since case 2 ) is only relevant if the toplevel type is [ lazy_t ] , we have specialized this case . For [ Boxed_value_converts ( lazy_v , v , i ) ] , we test that a ) [ lazy_v ] is boxed . b ) [ lazy_v ] converts to [ i ] when the conversion functions are called . c ) [ Lazy . force lazy_v == Lazy . force v ] d ) If we test [ Convertible ( v , i ) ] , the test passes . ( We also implicitly have the property that [ Lazy . force lazy_v ] is immediate and internally represented by [ i ] , which follows from b ) , c ) and d ) above . ) The following functions provide tests for the four cases . ) * let is_immediate ( type a ) ( v : a ) : bool = Obj . is_int ( Obj . repr v ) let to_int ( type a ) ( v : a ) : int = if is_immediate v then ( Obj . magic ( v : a ) : int ) else failwith " Can ' t convert a boxed value to an int . " ; ; let test_convertible_single ( type a ) ( conv : a t ) ( ( v , i ) : a * int ) : bool = to_int v = i && conv . value_is_int v && conv . int_is_value i && i = conv . value_as_int_exn v && phys_equal v ( conv . int_as_value_exn i ) && ( match conv . value_as_int v with | Some i ' -> i = i ' | None -> false ) && match conv . int_as_value i with | Some v ' -> phys_equal v v ' | None -> false ; ; let test_convertibles ( type a ) ( conv : a t ) ( test_cases : ( a * int ) list ) : bool = List . for_all test_cases ~ f ( : test_convertible_single conv ) ; ; let test_inconvertible_values ( type a ) ( conv : a t ) ( test_cases : a list ) : bool = List . for_all test_cases ~ f ( : fun v -> ( not ( is_immediate v ) ) && ( not ( conv . value_is_int v ) ) && ( match conv . value_as_int v with | Some _ -> false | None -> true ) && try let _i = conv . value_as_int_exn v in false with | _ -> true ) ; ; let test_inconvertible_ints ( type a ) ( conv : a t ) ( test_cases : int list ) : bool = List . for_all test_cases ~ f ( : fun i -> ( not ( conv . int_is_value i ) ) && ( match conv . int_as_value i with | Some _ -> false | None -> true ) && try let _v = conv . int_as_value_exn i in false with | _ -> true ) ; ; let no_int_but_zero_converts = [ 1 ; 2 ; 3 ; - 1 ; Int . max_value ; Int . min_value ] let no_int_converts = 0 :: no_int_but_zero_converts module type S = sig type t [ @@ deriving typerep ] end let is_never ( type a ) ( module M : S with type t = a ) examples = let conv = get_conv M . typerep_of_t in test_inconvertible_values conv examples && test_inconvertible_ints conv no_int_converts ; ; let % test ( _ [ @ tags " no - js " ] ) = is_never ( module struct type t = int32 [ @@ deriving typerep ] end ) [ Int32 . zero ; Int32 . one ; Int32 . minus_one ; Int32 . max_value ; Int32 . min_value ; Int32 . of_int_exn 328121 ] ; ; let % test _ = is_never ( module struct type t = int64 [ @@ deriving typerep ] end ) [ Int64 . zero ; Int64 . one ; Int64 . minus_one ; Int64 . max_value ; Int64 . min_value ] ; ; let % test ( _ [ @ tags " no - js " ] ) = is_never ( module struct type t = nativeint [ @@ deriving typerep ] end ) [ Nativeint . zero ; Nativeint . one ; Nativeint . minus_one ; Nativeint . max_value ; Nativeint . min_value ] ; ; let % test _ = let module M = struct type t = char [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ ' a ' , 97 ; ' A ' , 65 ; ' 0 ' , 48 ; ' 9 ' , 57 ; ' \ t ' , 9 ; ' \ n ' , 10 ; Char . of_int_exn 0 , 0 ; Char . of_int_exn 127 , 127 ] && test_inconvertible_ints conv [ 256 ; - 1 ; 500 ; Int . max_value ; Int . min_value ] ; ; let % test ( _ [ @ tags " no - js " ] ) = is_never ( module struct type t = float [ @@ deriving typerep ] end ) [ 1 . 1 ; 0 . 0 ; - 3 . 3 ; Float . nan ; Float . infinity ; Float . neg_infinity ] ; ; let % test _ = is_never ( module struct type t = string [ @@ deriving typerep ] end ) [ " " ; " Hello world " ! ] ; ; let % test _ = let module M = struct type t = bool [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ true , 1 ; false , 0 ] && test_inconvertible_ints conv [ 2 ; 3 ; - 1 ; - 2 ; 50 ; Int . max_value ; Int . min_value ] ; ; let % test _ = let module M = struct type t = unit [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ ( ) , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let module M = struct type t = unit option [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ None , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts && test_inconvertible_values conv [ Some ( ) ] ; ; let % test _ = let module M = struct type t = int ref option [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ None , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts && test_inconvertible_values conv [ Some ( ref 0 ) ; Some ( ref 1 ) ] ; ; let % test _ = let module M = struct type t = int ref list [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ [ ] , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts && test_inconvertible_values conv [ [ ref 0 ] ; [ ref 1 ] ] ; ; let % test _ = let module M = struct type t = unit list [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ [ ] , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts && test_inconvertible_values conv [ [ ( ) ] ] ; ; let % test _ = is_never ( module struct type t = int ref array [ @@ deriving typerep ] end ) [ [ ] ; || [ | ref 1 ] | ] ; ; let % test _ = is_never ( module struct type t = unit array [ @@ deriving typerep ] end ) [ [ ] ; || [ | ( ) ] ; | [ | ( ) ; ( ) ] | ] ; ; let % test _ = is_never ( module struct type t = unit ref [ @@ deriving typerep ] end ) [ ref ( ) ] ; ; let % test _ = is_never ( module struct type t = int ref [ @@ deriving typerep ] end ) [ ref 1 ; ref 2 ; ref ( - 1 ) ] ; ; let % test_module _ = ( module struct type ' a t = ' a lazy_t [ @@ deriving typerep ] let % test _ = let conv = get_conv ( typerep_of_t typerep_of_unit ) in test_inconvertible_values conv [ lazy ( ( fun ( ) -> ( ) ) ( ) ) ] && test_convertibles conv [ Lazy . from_val ( ) , 0 ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let conv = get_conv ( typerep_of_t typerep_of_int ) in test_convertibles conv [ lazy 0 , 0 ; lazy ( - 1 ) , - 1 ; Lazy . from_val Int . max_value , Int . max_value ] && test_inconvertible_values conv [ lazy ( 1 + 2 ) ; lazy ( List . length [ ] ) ] ; ; let % test _ = let conv = get_conv ( typerep_of_t ( typerep_of_list typerep_of_int ) ) in let l1 = lazy ( List . filter [ 1 ; 2 ; 3 ; 4 ] ~ f ( : fun _ -> false ) ) in let l2 = lazy ( List . filter [ ] ~ f ( : fun _ -> true ) ) in let l3 = lazy ( List . filter [ 1 ] ~ f ( : fun _ -> true ) ) in let empty = Lazy . from_val [ ] in test_convertibles conv [ empty , 0 ] && test_inconvertible_values conv [ Lazy . from_val [ 1 ] ; l1 ; l2 ; l3 ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let conv = get_conv ( typerep_of_t ( typerep_of_t typerep_of_int ) ) in let l1 = lazy ( lazy ( 1 + 2 ) ) in test_convertibles conv [ Lazy . from_val ( Lazy . from_val 3 ) , 3 ] && test_inconvertible_values conv [ l1 ] ; ; end ) ; ; let % test _ = let module M = struct type t = { foo : unit } [ @@ deriving typerep ] end in is_never ( module M ) [ { M . foo = ( ) } ] ; ; let % test _ = is_never ( module struct type t = unit * unit [ @@ deriving typerep ] end ) [ ( ) , ( ) ] ; ; let % test _ = is_never ( module struct type t = unit * unit * unit [ @@ deriving typerep ] end ) [ ( ) , ( ) , ( ) ] ; ; let % test _ = is_never ( module struct type t = unit * unit * unit * unit [ @@ deriving typerep ] end ) [ ( ) , ( ) , ( ) , ( ) ] ; ; let % test _ = is_never ( module struct type t = unit * unit * unit * unit * unit [ @@ deriving typerep ] end ) [ ( ) , ( ) , ( ) , ( ) , ( ) ] ; ; let % test _ = let module M = struct type t = | Foo | Bar of unit [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ M . Foo , 0 ] && test_inconvertible_values conv [ M . Bar ( ) ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let module M = struct type t = | Foo | Bar | Baz [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ M . Foo , 0 ; M . Bar , 1 ; M . Baz , 2 ] && test_inconvertible_ints conv [ 3 ; 4 ; 5 ; 500 ; 232 ; - 1 ; - 2 ; Int . max_value ; Int . min_value ] ; ; let % test _ = let module M = struct type t = | Foo of unit | Bar of unit | Baz of unit [ @@ deriving typerep ] end in is_never ( module M ) [ M . Foo ( ) ; M . Bar ( ) ; M . Baz ( ) ] ; ; let filter_variants variants list = let variants = List . filter_map variants ~ f ( : fun v -> if Obj . is_int ( Obj . repr v ) then Some ( Obj . magic ( v : [ > ] ) : int ) else None ) in List . filter list ~ f ( : fun int -> List . for_all variants ~ f ( : fun variant -> variant <> int ) ) ; ; let % test _ = let module M = struct type t = [ ` Foo | ` Bar of unit ] [ @@ deriving typerep , enumerate ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ ` Foo , Typerep_obj . repr_of_poly_variant ` Foo ] && test_inconvertible_values conv [ ` Bar ( ) ] && test_inconvertible_ints conv ( filter_variants M . all [ 0 ; 1 ; 2 ; 3 ; - 1 ; - 2 ; 563 ; Int . max_value ; Int . min_value ; Typerep_obj . repr_of_poly_variant ` Bar ] ) ; ; let % test _ = let module M = struct type t = [ ` Foo | ` Bar | ` Baz ] [ @@ deriving typerep , enumerate ] end in let conv = get_conv M . typerep_of_t in test_convertibles conv [ ` Foo , Typerep_obj . repr_of_poly_variant ` Foo ; ` Bar , Typerep_obj . repr_of_poly_variant ` Bar ; ` Baz , Typerep_obj . repr_of_poly_variant ` Baz ] && test_inconvertible_ints conv ( filter_variants M . all [ 0 ; 1 ; 2 ; 3 ; - 1 ; - 2 ; 563 ; Int . max_value ; Int . min_value ] ) ; ; let % test _ = let module M = struct type t = [ ` Foo of unit | ` Bar of unit | ` Baz of unit ] [ @@ deriving typerep ] end in let conv = get_conv M . typerep_of_t in test_inconvertible_values conv [ ` Foo ( ) ; ` Bar ( ) ; ` Baz ( ) ] && test_inconvertible_ints conv ( [ Typerep_obj . repr_of_poly_variant ` Foo ; Typerep_obj . repr_of_poly_variant ` Bar ; Typerep_obj . repr_of_poly_variant ` Baz ] @ no_int_converts ) ; ; let % test _ = let module M = struct type ' a t = | Nil | Cons of ' a * ' a t [ @@ deriving typerep ] end in let conv = get_conv ( M . typerep_of_t typerep_of_unit ) in test_convertibles conv [ M . Nil , 0 ] && test_inconvertible_values conv [ M . Cons ( ( ) , M . Nil ) ; M . Cons ( ( ) , M . Cons ( ( ) , M . Nil ) ) ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let module M = struct type ' a t = | A | B of ' a t lazy_t | C of ' a * ' a t [ @@ deriving typerep ] end in let conv = get_conv ( M . typerep_of_t typerep_of_int ) in test_convertibles conv [ M . A , 0 ] && test_inconvertible_values conv [ M . B ( lazy M . A ) ; M . C ( 1 , M . A ) ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; let % test _ = let module M = struct type ' a t = | A | B of ( ' a t * ' a t ) | C of ' a [ @@ deriving typerep ] end in let conv = get_conv ( M . typerep_of_t typerep_of_unit ) in test_convertibles conv [ M . A , 0 ] && test_inconvertible_values conv [ M . B ( M . A , M . A ) ; M . C ( ) ] && test_inconvertible_ints conv no_int_but_zero_converts ; ; end ) ; ;
( module struct type t = | Always | Sometimes | Never let imm_t = typerep_of_unit let box_t = typerep_of_ref typerep_of_int let is_imm v = Obj . is_int ( Obj . repr v ) let check expected typerep list = if List . length list = 0 then failwith " Must provide at least one test case . " ; let actual = ( Type_immediacy . dest ( Type_immediacy . of_typerep typerep ) , Type_immediacy . Always . of_typerep typerep , Type_immediacy . Sometimes . of_typerep typerep , Type_immediacy . Never . of_typerep typerep ) in let has_imm = List . exists ~ f : is_imm list in let has_boxed = List . exists ~ f ( : fun x -> not ( is_imm x ) ) list in match has_imm , has_boxed , expected , actual with | true , false , Always , ( Type_immediacy . Always _ , Some _ , None , None ) -> true | true , true , Sometimes , ( Type_immediacy . Sometimes _ , None , Some _ , None ) -> true | false , true , Never , ( Type_immediacy . Never _ , None , None , Some _ ) -> true | _ , _ , _ , _ -> false ; ; module T : sig val check_a : ' a Typerep . t -> ' a list -> bool val check_s : ' a Typerep . t -> ' a list -> bool val check_n : ' a Typerep . t -> ' a list -> bool end = struct let check_a typerep list = check Always typerep list let check_s typerep list = check Sometimes typerep list let check_n typerep list = check Never typerep list end include T let % test _ = let module M = struct type t = int [ @@ deriving typerep ] end in check_a M . typerep_of_t [ 0 ; 1 ] ; ; let % test ( _ [ @ tags " no - js " ] ) = let module M = struct type t = int32 [ @@ deriving typerep ] end in check_n M . typerep_of_t [ Int32 . zero ; Int32 . one ; Int32 . minus_one ; Int32 . of_int_exn 32580 ] ; ; let % test _ = let module M = struct type t = int64 [ @@ deriving typerep ] end in check_n M . typerep_of_t [ Int64 . zero ] ; ; let % test ( _ [ @ tags " no - js " ] ) = let module M = struct type t = nativeint [ @@ deriving typerep ] end in check_n M . typerep_of_t [ Nativeint . zero ] ; ; let % test _ = let module M = struct type t = char [ @@ deriving typerep ] end in check_a M . typerep_of_t [ ' a ' ] ; ; let % test ( _ [ @ tags " no - js " ] ) = let module M = struct type t = float [ @@ deriving typerep ] end in check_n M . typerep_of_t [ 1 . 1 ; 0 . 0 ; - 3 . 3 ; Float . nan ; Float . infinity ; Float . neg_infinity ; Float . max_value ; Float . min_value ] ; ; let % test _ = let module M = struct type t = string [ @@ deriving typerep ] end in check_n M . typerep_of_t [ " " ; " Hello world " ! ] ; ; let % test _ = let module M = struct type t = bool [ @@ deriving typerep ] end in check_a M . typerep_of_t [ true ; false ] ; ; let % test _ = let module M = struct type t = unit [ @@ deriving typerep ] end in check_a M . typerep_of_t [ ( ) ] ; ; let % test _ = let module M = struct type ' a t = ' a option [ @@ deriving typerep ] end in check_s ( M . typerep_of_t imm_t ) [ None ; Some ( ) ] && check_s ( M . typerep_of_t box_t ) [ None ; Some ( ref 1 ) ] ; ; let % test _ = let module M = struct type ' a t = ' a list [ @@ deriving typerep ] end in check_s ( M . typerep_of_t imm_t ) [ [ ] ; [ ( ) ] ] && check_s ( M . typerep_of_t box_t ) [ [ ] ; [ ref 1 ] ] ; ; let static_empty_array = [ ] || let % test _ = let module M = struct type ' a t = ' a array [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t ) [ static_empty_array ; [ ] ; || [ | ( ) ; ( ) ] | ] ; ; let % test _ = let module M = struct type ' a t = ' a ref [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t ) [ ref ( ) ] ; ; let % test _ = let module M = struct type ' a t = ' a lazy_t [ @@ deriving typerep ] end in check_s ( M . typerep_of_t typerep_of_int ) [ lazy 1 ; lazy ( 1 + 2 ) ] && check_n ( M . typerep_of_t typerep_of_float ) [ lazy 0 . 0 ; lazy ( 1 . 0 . + - 3 . 3 ) ] ; ; let % test _ = let module M = struct type t = { foo : unit } [ @@ deriving typerep ] end in check_n M . typerep_of_t [ { M . foo = ( ) } ] ; ; let % test _ = let module M = struct type ( ' a , ' b ) t = ' a * ' b [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t imm_t ) [ ( ) , ( ) ] ; ; let % test _ = let module M = struct type ( ' a , ' b , ' c ) t = ' a * ' b * ' c [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t imm_t imm_t ) [ ( ) , ( ) , ( ) ] ; ; let % test _ = let module M = struct type ( ' a , ' b , ' c , ' d ) t = ' a * ' b * ' c * ' d [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t imm_t imm_t imm_t ) [ ( ) , ( ) , ( ) , ( ) ] ; ; let % test _ = let module M = struct type ( ' a , ' b , ' c , ' d , ' e ) t = ' a * ' b * ' c * ' d * ' e [ @@ deriving typerep ] end in check_n ( M . typerep_of_t imm_t imm_t imm_t imm_t imm_t ) [ ( ) , ( ) , ( ) , ( ) , ( ) ] ; ; let % test _ = let module M = struct type t = | Foo | Bar of unit [ @@ deriving typerep ] end in check_s M . typerep_of_t [ M . Foo ; M . Bar ( ) ] ; ; let % test _ = let module M = struct type t = | Foo | Bar | Baz [ @@ deriving typerep ] end in check_a M . typerep_of_t [ M . Foo ; M . Bar ; M . Baz ] ; ; let % test _ = let module M = struct type t = | Foo of unit | Bar of unit | Baz of unit [ @@ deriving typerep ] end in check_n M . typerep_of_t [ M . Foo ( ) ; M . Bar ( ) ; M . Baz ( ) ] ; ; let % test _ = let module M = struct type t = Foo of unit [ @@ deriving typerep ] end in check_n M . typerep_of_t [ M . Foo ( ) ] ; ; let % test _ = let module M = struct type t = [ ` Foo | ` Bar of unit ] [ @@ deriving typerep ] end in check_s M . typerep_of_t [ ` Foo ; ` Bar ( ) ] ; ; let % test _ = let module M = struct type t = [ ` Foo | ` Bar | ` Baz ] [ @@ deriving typerep ] end in check_a M . typerep_of_t [ ` Foo ; ` Bar ; ` Baz ] ; ; let % test _ = let module M = struct type t = [ ` Foo of unit | ` Bar of unit | ` Baz of unit ] [ @@ deriving typerep ] end in check_n M . typerep_of_t [ ` Foo ( ) ; ` Bar ( ) ; ` Baz ( ) ] ; ; let % test _ = let module M = struct type t = [ ` Foo of unit ] [ @@ deriving typerep ] end in check_n M . typerep_of_t [ ` Foo ( ) ] ; ; let % test _ = let module M = struct type ' a t = | Nil | Cons of ' a * ' a t [ @@ deriving typerep ] end in check_s ( M . typerep_of_t typerep_of_int ) [ M . Nil ; M . Cons ( 1 , M . Cons ( 2 , M . Nil ) ) ] ; ; let % test _ = let module M = struct type ' a t = | A | B of ' a t lazy_t | C of ' a * ' a t [ @@ deriving typerep ] end in check_s ( M . typerep_of_t typerep_of_int ) [ M . A ; M . B ( lazy M . A ) ; M . C ( 1 , M . A ) ] ; ; let % test _ = let module M = struct type ' a t = | A | B of ( ' a t * ' a t ) | C of ' a [ @@ deriving typerep ] end in check_s ( M . typerep_of_t typerep_of_int ) [ M . A ; M . B ( M . A , M . C 1 ) ] ; ; let % test _ = let module M = struct type ' a t = | A | B | C [ @@ deriving typerep ] end in let module X = Type_immediacy . Always . For_all_parameters_S1 ( M ) in true ; ; let % test _ = let module M = struct type ' a t = ' a option lazy_t [ @@ deriving typerep ] end in let module X = Type_immediacy . Sometimes . For_all_parameters_S1 ( M ) in true ; ; let % test _ = let module M = struct type ' a t = ' a array lazy_t [ @@ deriving typerep ] end in let module X = Type_immediacy . Never . For_all_parameters_S1 ( M ) in true ; ; let % test _ = let module M = struct type ' a t = ' a lazy_t [ @@ deriving typerep ] end in try let module X = Type_immediacy . Sometimes . For_all_parameters_S1 ( M ) in false with | _ -> ( try let module X = Type_immediacy . Never . For_all_parameters_S1 ( M ) in false with | _ -> ( try let module X = Type_immediacy . Always . For_all_parameters_S1 ( M ) in false with | _ -> true ) ) ; ; end ) ; ;
let hash_string_hex s = let md5_hex = Digest . string s |> Digest . to_hex in assert ( String . length md5_hex = 32 ) ; String . sub md5_hex 0 7
let is_alpha c = match c with | ' A ' . . ' Z ' | ' a ' . . ' z ' -> true | _ -> false
let force_capitalize s = let need_prefix = s = " " || not ( is_alpha s . [ 0 ] ) in if need_prefix then capital_prefix ^ s else String . capitalize_ascii s
let name_of_token ( token : token ) = Punct . to_alphanum token . name
let encode_prec_name name = for i = 0 to String . length name - 1 do match name . [ i ] with | ' A ' . . ' Z ' | ' a ' . . ' z ' | ' 0 ' . . ' 9 ' -> ( ) | c -> failwith ( sprintf " Unsupported character % C in named precedence level % S " c name ) done ; name
let name_of_num_prec n = if n >= 0 then sprintf " p % d " n else sprintf " n % d " ( abs n )
let name_of_prec_value ( p : Tree_sitter_t . prec_value ) = match p with | Num_prec n -> name_of_num_prec n | Named_prec name -> sprintf " x % s " ( encode_prec_name name )
let name_of_opt_prec_value p = match p with | None -> " 0 " | Some p -> " x " ^ name_of_prec_value p
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