···10101111### Other libraries:
12121313+- #10192: Add support for Unix domain sockets on Windows and use them
1414+ to emulate Unix.socketpair (only available on Windows 1803+)
1515+ (Antonin Décimo, review by David Allsopp)
1616+1317### Tools:
14181519### Manual and documentation:
···31353236- #10434: Pun labelled arguments with type constraint in function applications.
3337 (Greta Yorsh, review by Nicolas Chataing and Nicolás Ojeda Bär)
3838+3939+- #10470: Remove unused `cstr_normal` field from the `constructor_description`
4040+ type
4141+ (Nicolas Chataing, review by Gabriel Scherer)
34423543### Build system:
3644···302310 documentation comments
303311 (Florian Angeletti, report by Hendrik Tews, review by Gabriel Scherer)
304312313313+- #10206: Split labels and polymorphic variants tutorials
314314+ Splits the labels and polymorphic variants tutorial into two. Moves the GADTs
315315+ tutorial from the Language Extensions chapter to the tutorials.
316316+ (John Whitington, review by Florian Angeletti and Xavier Leroy)
317317+305318- #10247: Add initial tranche of examples to reference manual.
306319 Adds some eighty examples to the reference manual, principally to the
307320 expressions and patterns sections.
···437450438451- #10327: Add a subdirectories variable and a copy action to ocamltest
439452 (Sébastien Hinderer, review by David Allsopp)
453453+454454+* #10337: Normalize type_expr nodes on access
455455+ One should now use accessors such as get_desc and get_level to access fields
456456+ of type_expr, rather than calling manually Btype.repr (which is now hidden
457457+ in Types.Transient_expr).
458458+ (Jacques Garrigue and Takafumi Saikawa,
459459+ review by Florian Angeletti and Gabriel Radanne)
440460441461- #10358: Use a hash table for the load path.
442462 (Leo White, review by Gabriel Scherer)
+28
configure
···1517015170 test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
15171151711517215172fi
1517315173+1517415174+ ac_fn_c_check_func "$LINENO" "socketpair" "ac_cv_func_socketpair"
1517515175+if test "x$ac_cv_func_socketpair" = xyes; then :
1517615176+ $as_echo "#define HAS_SOCKETPAIR 1" >>confdefs.h
1517715177+1517815178+fi
1517315179 ;; #(
1517415180 *-*-haiku) :
1517515181 cclibs="$cclibs -lnetwork"
···15395154011539615402fi
15397154031540415404+1540515405+## Unix domain sockets support on Windows
1540615406+1540715407+case $host in #(
1540815408+ *-*-mingw32|*-pc-windows) :
1540915409+ for ac_header in afunix.h
1541015410+do :
1541115411+ ac_fn_c_check_header_compile "$LINENO" "afunix.h" "ac_cv_header_afunix_h" "#include <winsock2.h>
1541215412+"
1541315413+if test "x$ac_cv_header_afunix_h" = xyes; then :
1541415414+ cat >>confdefs.h <<_ACEOF
1541515415+#define HAVE_AFUNIX_H 1
1541615416+_ACEOF
1541715417+ $as_echo "#define HAS_AFUNIX_H 1" >>confdefs.h
1541815418+1541915419+fi
1542015420+1542115421+done
1542215422+ ;; #(
1542315423+ *) :
1542415424+ ;;
1542515425+esac
15398154261539915427## IPv6 support
1540015428
···623623 in
624624 begin try
625625 let (v, ty) = Eval.expression !selected_event env expr in
626626- match (Ctype.repr ty).desc with
626626+ match get_desc ty with
627627 | Tarrow _ ->
628628 add_breakpoint_after_pc (Remote_value.closure_code v)
629629 | _ ->
+2-2
debugger/eval.ml
···112112 end
113113 | E_item(arg, n) ->
114114 let (v, ty) = expression event env arg in
115115- begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with
115115+ begin match get_desc (Ctype.expand_head_opt env ty) with
116116 Ttuple ty_list ->
117117 if n < 1 || n > List.length ty_list
118118 then raise(Error(Tuple_index(ty, List.length ty_list, n)))
···142142 end
143143 | E_field(arg, lbl) ->
144144 let (v, ty) = expression event env arg in
145145- begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with
145145+ begin match get_desc (Ctype.expand_head_opt env ty) with
146146 Tconstr(path, _, _) ->
147147 let tydesc = Env.find_type path env in
148148 begin match tydesc.type_kind with
+1-1
driver/main_args.ml
···691691692692let mk_match_context_rows f =
693693 "-match-context-rows", Arg.Int f,
694694- let[@manual.ref "s:comp-options"] chapter, section = 9, 2 in
694694+ let[@manual.ref "s:comp-options"] chapter, section = 11, 2 in
695695 Printf.sprintf
696696 "<n> (advanced, see manual section %d.%d.)" chapter section
697697;;
+4-4
lambda/translmod.ml
···242242 [] -> []
243243 | Sig_value(subid, {val_kind=Val_reg; val_type=ty; val_loc=loc},_) :: rem ->
244244 let init_v =
245245- match Ctype.expand_head env ty with
246246- {desc = Tarrow(_,_,_,_)} ->
245245+ match get_desc (Ctype.expand_head env ty) with
246246+ Tarrow(_,_,_,_) ->
247247 const_int 0 (* camlinternalMod.Function *)
248248- | {desc = Tconstr(p, _, _)} when Path.same p Predef.path_lazy_t ->
248248+ | Tconstr(p, _, _) when Path.same p Predef.path_lazy_t ->
249249 const_int 1 (* camlinternalMod.Lazy *)
250250 | _ ->
251251 let not_a_function =
···1693169316941694let report_error loc = function
16951695 | Circular_dependency cycle ->
16961696- let[@manual.ref "s:recursive-modules"] chapter, section = 8, 2 in
16961696+ let[@manual.ref "s:recursive-modules"] chapter, section = 10, 2 in
16971697 Location.errorf ~loc ~sub:(List.map explanation_submsg cycle)
16981698 "Cannot safely evaluate the definition of the following cycle@ \
16991699 of recursively-defined modules:@ %a.@ \
···9090\entree{"getpwnam", "getpwuid"}{always raise "Not_found"}
9191\entree{"getgrnam", "getgrgid"}{always raise "Not_found"}
9292\entree{type "socket_domain"}{"PF_INET" is fully supported;
9393-"PF_INET6" is fully supported (since 4.01.0); "PF_UNIX" is not supported }
9393+"PF_INET6" is fully supported (since 4.01.0); "PF_UNIX" is supported since 4.14.0, but only works on Windows 10 1803 and later.}
9494\entree{"establish_server"}{not implemented; use threads}
9595\entree{terminal functions ("tc*")}{not implemented}
9696\entree{"setsid"}{not implemented}
+8-299
manual/src/refman/extensions/gadts.etex
···11+Generalized algebraic datatypes, or GADTs, extend usual sum types in
22+two ways: constraints on type parameters may change depending on the
33+value constructor, and some type variables may be existentially
44+quantified. They are described in chapter \ref{c:gadts-tutorial}.
55+16(Introduced in OCaml 4.00)
2738\begin{syntax}
···1015 | [variance] '_'
1116\end{syntax}
12171313-Generalized algebraic datatypes, or GADTs, extend usual sum types in
1414-two ways: constraints on type parameters may change depending on the
1515-value constructor, and some type variables may be existentially
1616-quantified.
1717-Adding constraints is done by giving an explicit return type
1818-(the rightmost @typexpr@ in the above syntax), where type parameters
1919-are instantiated.
2020-This return type must use the same type constructor as the type being
2121-defined, and have the same number of parameters.
2222-Variables are made existential when they appear inside a constructor's
2323-argument, but not in its return type.
2424-2525-Since the use of a return type often eliminates the need to name type
2626-parameters in the left-hand side of a type definition, one can replace
2727-them with anonymous types @"_"@ in that case.
2828-2929-The constraints associated to each constructor can be recovered
3030-through pattern-matching.
3131-Namely, if the type of the scrutinee of a pattern-matching contains
3232-a locally abstract type, this type can be refined according to the
3333-constructor used.
3434-These extra constraints are only valid inside the corresponding branch
3535-of the pattern-matching.
3636-If a constructor has some existential variables, fresh locally
3737-abstract types are generated, and they must not escape the
3838-scope of this branch.
3939-4040-\lparagraph{p:gadts-recfun}{Recursive functions}
4141-4242-Here is a concrete example:
4343-\begin{caml_example*}{verbatim}
4444-type _ term =
4545- | Int : int -> int term
4646- | Add : (int -> int -> int) term
4747- | App : ('b -> 'a) term * 'b term -> 'a term
4848-4949-let rec eval : type a. a term -> a = function
5050- | Int n -> n (* a = int *)
5151- | Add -> (fun x y -> x+y) (* a = int -> int -> int *)
5252- | App(f,x) -> (eval f) (eval x)
5353- (* eval called at types (b->a) and b for fresh b *)
5454-\end{caml_example*}
5555-\begin{caml_example}{verbatim}
5656-let two = eval (App (App (Add, Int 1), Int 1))
5757-\end{caml_example}
5858-It is important to remark that the function "eval" is using the
5959-polymorphic syntax for locally abstract types. When defining a recursive
6060-function that manipulates a GADT, explicit polymorphic recursion should
6161-generally be used. For instance, the following definition fails with a
6262-type error:
6363-\begin{caml_example}{verbatim}[error]
6464-let rec eval (type a) : a term -> a = function
6565- | Int n -> n
6666- | Add -> (fun x y -> x+y)
6767- | App(f,x) -> (eval f) (eval x)
6868-\end{caml_example}
6969-In absence of an explicit polymorphic annotation, a monomorphic type
7070-is inferred for the recursive function. If a recursive call occurs
7171-inside the function definition at a type that involves an existential
7272-GADT type variable, this variable flows to the type of the recursive
7373-function, and thus escapes its scope. In the above example, this happens
7474-in the branch "App(f,x)" when "eval" is called with "f" as an argument.
7575-In this branch, the type of "f" is "($App_ 'b-> a)". The prefix "$" in
7676-"$App_ 'b" denotes an existential type named by the compiler
7777-(see~\ref{p:existential-names}). Since the type of "eval" is
7878-"'a term -> 'a", the call "eval f" makes the existential type "$App_'b"
7979-flow to the type variable "'a" and escape its scope. This triggers the
8080-above error.
8181-8282-\lparagraph{p:gadts-type-inference}{Type inference}
8383-8484-Type inference for GADTs is notoriously hard.
8585-This is due to the fact some types may become ambiguous when escaping
8686-from a branch.
8787-For instance, in the "Int" case above, "n" could have either type "int"
8888-or "a", and they are not equivalent outside of that branch.
8989-As a first approximation, type inference will always work if a
9090-pattern-matching is annotated with types containing no free type
9191-variables (both on the scrutinee and the return type).
9292-This is the case in the above example, thanks to the type annotation
9393-containing only locally abstract types.
9494-9595-In practice, type inference is a bit more clever than that: type
9696-annotations do not need to be immediately on the pattern-matching, and
9797-the types do not have to be always closed.
9898-As a result, it is usually enough to only annotate functions, as in
9999-the example above. Type annotations are
100100-propagated in two ways: for the scrutinee, they follow the flow of
101101-type inference, in a way similar to polymorphic methods; for the
102102-return type, they follow the structure of the program, they are split
103103-on functions, propagated to all branches of a pattern matching,
104104-and go through tuples, records, and sum types.
105105-Moreover, the notion of ambiguity used is stronger: a type is only
106106-seen as ambiguous if it was mixed with incompatible types (equated by
107107-constraints), without type annotations between them.
108108-For instance, the following program types correctly.
109109-\begin{caml_example}{verbatim}
110110-let rec sum : type a. a term -> _ = fun x ->
111111- let y =
112112- match x with
113113- | Int n -> n
114114- | Add -> 0
115115- | App(f,x) -> sum f + sum x
116116- in y + 1
117117-\end{caml_example}
118118-Here the return type "int" is never mixed with "a", so it is seen as
119119-non-ambiguous, and can be inferred.
120120-When using such partial type annotations we strongly suggest
121121-specifying the "-principal" mode, to check that inference is
122122-principal.
1818+Refutation cases. (Introduced in OCaml 4.03)
12319124124-The exhaustiveness check is aware of GADT constraints, and can
125125-automatically infer that some cases cannot happen.
126126-For instance, the following pattern matching is correctly seen as
127127-exhaustive (the "Add" case cannot happen).
128128-\begin{caml_example*}{verbatim}
129129-let get_int : int term -> int = function
130130- | Int n -> n
131131- | App(_,_) -> 0
132132-\end{caml_example*}
133133-134134-135135-\lparagraph{p:gadt-refutation-cases}{Refutation cases} (Introduced in OCaml 4.03)
136136-137137-Usually, the exhaustiveness check only tries to check whether the
138138-cases omitted from the pattern matching are typable or not.
139139-However, you can force it to try harder by adding {\em refutation cases}:
14020\begin{syntax}
14121matching-case:
14222 pattern ['when' expr] '->' expr
14323 | pattern '->' '.'
14424\end{syntax}
145145-In presence of a refutation case, the exhaustiveness check will first
146146-compute the intersection of the pattern with the complement of the
147147-cases preceding it. It then checks whether the resulting patterns can
148148-really match any concrete values by trying to type-check them.
149149-Wild cards in the generated patterns are handled in a special way: if
150150-their type is a variant type with only GADT constructors, then the
151151-pattern is split into the different constructors, in order to check whether
152152-any of them is possible (this splitting is not done for arguments of these
153153-constructors, to avoid non-termination). We also split tuples and
154154-variant types with only one case, since they may contain GADTs inside.
155155-For instance, the following code is deemed exhaustive:
15625157157-\begin{caml_example*}{verbatim}
158158-type _ t =
159159- | Int : int t
160160- | Bool : bool t
161161-162162-let deep : (char t * int) option -> char = function
163163- | None -> 'c'
164164- | _ -> .
165165-\end{caml_example*}
166166-167167-Namely, the inferred remaining case is "Some _", which is split into
168168-"Some (Int, _)" and "Some (Bool, _)", which are both untypable because
169169-"deep" expects a non-existing "char t" as the first element of the tuple.
170170-Note that the refutation case could be omitted here, because it is
171171-automatically added when there is only one case in the pattern
172172-matching.
173173-174174-Another addition is that the redundancy check is now aware of GADTs: a
175175-case will be detected as redundant if it could be replaced by a
176176-refutation case using the same pattern.
177177-178178-\lparagraph{p:gadts-advexamples}{Advanced examples}
179179-The "term" type we have defined above is an {\em indexed} type, where
180180-a type parameter reflects a property of the value contents.
181181-Another use of GADTs is {\em singleton} types, where a GADT value
182182-represents exactly one type. This value can be used as runtime
183183-representation for this type, and a function receiving it can have a
184184-polytypic behavior.
185185-186186-Here is an example of a polymorphic function that takes the
187187-runtime representation of some type "t" and a value of the same type,
188188-then pretty-prints the value as a string:
189189-\begin{caml_example*}{verbatim}
190190-type _ typ =
191191- | Int : int typ
192192- | String : string typ
193193- | Pair : 'a typ * 'b typ -> ('a * 'b) typ
194194-195195-let rec to_string: type t. t typ -> t -> string =
196196- fun t x ->
197197- match t with
198198- | Int -> Int.to_string x
199199- | String -> Printf.sprintf "%S" x
200200- | Pair(t1,t2) ->
201201- let (x1, x2) = x in
202202- Printf.sprintf "(%s,%s)" (to_string t1 x1) (to_string t2 x2)
203203-\end{caml_example*}
204204-205205-Another frequent application of GADTs is equality witnesses.
206206-\begin{caml_example*}{verbatim}
207207-type (_,_) eq = Eq : ('a,'a) eq
208208-209209-let cast : type a b. (a,b) eq -> a -> b = fun Eq x -> x
210210-\end{caml_example*}
211211-Here type "eq" has only one constructor, and by matching on it one
212212-adds a local constraint allowing the conversion between "a" and "b".
213213-By building such equality witnesses, one can make equal types which
214214-are syntactically different.
215215-216216-Here is an example using both singleton types and equality witnesses
217217-to implement dynamic types.
218218-\begin{caml_example*}{verbatim}
219219-let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option =
220220- fun a b ->
221221- match a, b with
222222- | Int, Int -> Some Eq
223223- | String, String -> Some Eq
224224- | Pair(a1,a2), Pair(b1,b2) ->
225225- begin match eq_type a1 b1, eq_type a2 b2 with
226226- | Some Eq, Some Eq -> Some Eq
227227- | _ -> None
228228- end
229229- | _ -> None
230230-231231-type dyn = Dyn : 'a typ * 'a -> dyn
232232-233233-let get_dyn : type a. a typ -> dyn -> a option =
234234- fun a (Dyn(b,x)) ->
235235- match eq_type a b with
236236- | None -> None
237237- | Some Eq -> Some x
238238-\end{caml_example*}
239239-240240-\lparagraph{p:existential-names}{Existential type names in error messages}%
241241-(Updated in OCaml 4.03.0)
242242-243243-The typing of pattern matching in presence of GADT can generate many
244244-existential types. When necessary, error messages refer to these
245245-existential types using compiler-generated names. Currently, the
246246-compiler generates these names according to the following nomenclature:
247247-\begin{itemize}
248248-\item First, types whose name starts with a "$" are existentials.
249249-\item "$Constr_'a" denotes an existential type introduced for the type
250250-variable "'a" of the GADT constructor "Constr":
251251-\begin{caml_example}{verbatim}[error]
252252-type any = Any : 'name -> any
253253-let escape (Any x) = x
254254-\end{caml_example}
255255-\item "$Constr" denotes an existential type introduced for an anonymous %$
256256-type variable in the GADT constructor "Constr":
257257-\begin{caml_example}{verbatim}[error]
258258-type any = Any : _ -> any
259259-let escape (Any x) = x
260260-\end{caml_example}
261261-\item "$'a" if the existential variable was unified with the type %$
262262-variable "'a" during typing:
263263-\begin{caml_example}{verbatim}[error]
264264-type ('arg,'result,'aux) fn =
265265- | Fun: ('a ->'b) -> ('a,'b,unit) fn
266266- | Mem1: ('a ->'b) * 'a * 'b -> ('a, 'b, 'a * 'b) fn
267267- let apply: ('arg,'result, _ ) fn -> 'arg -> 'result = fun f x ->
268268- match f with
269269- | Fun f -> f x
270270- | Mem1 (f,y,fy) -> if x = y then fy else f x
271271-\end{caml_example}
272272-\item "$n" (n a number) is an internally generated existential %$
273273-which could not be named using one of the previous schemes.
274274-\end{itemize}
275275-276276-As shown by the last item, the current behavior is imperfect
277277-and may be improved in future versions.
278278-279279-\lparagraph{p:explicit-existential-name}{Explicit naming of
280280- existentials} (Introduced in OCaml 4.13.0)
281281-282282-As explained above, pattern-matching on a GADT constructor may
283283-introduce existential types. The following syntax allows to name them
284284-explicitly.
2626+Explicit naming of existentials. (Introduced in OCaml 4.13.0)
2852728628\begin{syntax}
28729pattern:
28830 ...
28931 | constr '(' "type" {{typeconstr-name}} ')' '(' pattern ')'
29032;
291291-\end{syntax}
292292-293293-For instance, the following code names the type of the argument of f
294294-and uses this name.
295295-296296-\begin{caml_example*}{verbatim}
297297-type _ closure = Closure : ('a -> 'b) * 'a -> 'b closure
298298-let eval = fun (Closure (type a) (f, x : (a -> _) * _)) -> f (x : a)
299299-\end{caml_example*}
300300-All existential type variables of the constructor must by introduced by
301301-the ("type" ...) construct and bound by a type annotation on the
302302-outside of the constructor argument.
303303-304304-\lparagraph{p:gadt-equation-nonlocal-abstract}{Equations on non-local abstract types} (Introduced in OCaml
305305-4.04)
306306-307307-GADT pattern-matching may also add type equations to non-local
308308-abstract types. The behaviour is the same as with local abstract
309309-types. Reusing the above "eq" type, one can write:
310310-\begin{caml_example*}{verbatim}
311311-module M : sig type t val x : t val e : (t,int) eq end = struct
312312- type t = int
313313- let x = 33
314314- let e = Eq
315315-end
316316-317317-let x : int = let Eq = M.e in M.x
318318-\end{caml_example*}
319319-320320-Of course, not all abstract types can be refined, as this would
321321-contradict the exhaustiveness check. Namely, builtin types (those
322322-defined by the compiler itself, such as "int" or "array"), and
323323-abstract types defined by the local module, are non-instantiable, and
324324-as such cause a type error rather than introduce an equation.
3333+\end{syntax}
···66is assumed, but no prior exposure to functional languages is required. The
77present chapter introduces the core language. Chapter~\ref{c:moduleexamples}
88deals with the module system, chapter~\ref{c:objectexamples} with the
99-object-oriented features, chapter~\ref{c:labl-examples} with extensions to the
1010-core language (labeled arguments and polymorphic variants),
99+object-oriented features, chapter~\ref{c:labl-examples} with labeled
1010+arguments, chapter~\ref{c:poly-variant} with polymorphic variants,
1111chapter~\ref{c:polymorphism} with the limitations of polymorphism, and
1212chapter~\ref{c:advexamples} gives some advanced examples.
1313
+304
manual/src/tutorials/gadtexamples.etex
···11+\chapter{Generalized algebraic datatypes} \label{c:gadts-tutorial}
22+%HEVEA\cutname{gadts-tutorial.html}
33+44+Generalized algebraic datatypes, or GADTs, extend usual sum types in
55+two ways: constraints on type parameters may change depending on the
66+value constructor, and some type variables may be existentially
77+quantified.
88+Adding constraints is done by giving an explicit return type, where type
99+parameters are instantiated:
1010+1111+\begin{caml_example*}{verbatim}
1212+type _ term =
1313+ | Int : int -> int term
1414+ | Add : (int -> int -> int) term
1515+ | App : ('b -> 'a) term * 'b term -> 'a term
1616+\end{caml_example*}
1717+1818+This return type must use the same type constructor as the type being
1919+defined, and have the same number of parameters.
2020+Variables are made existential when they appear inside a constructor's
2121+argument, but not in its return type.
2222+Since the use of a return type often eliminates the need to name type
2323+parameters in the left-hand side of a type definition, one can replace
2424+them with anonymous types "_" in that case.
2525+2626+The constraints associated to each constructor can be recovered
2727+through pattern-matching.
2828+Namely, if the type of the scrutinee of a pattern-matching contains
2929+a locally abstract type, this type can be refined according to the
3030+constructor used.
3131+These extra constraints are only valid inside the corresponding branch
3232+of the pattern-matching.
3333+If a constructor has some existential variables, fresh locally
3434+abstract types are generated, and they must not escape the
3535+scope of this branch.
3636+3737+\section{s:gadts-recfun}{Recursive functions}
3838+3939+We write an "eval" function:
4040+4141+\begin{caml_example*}{verbatim}
4242+let rec eval : type a. a term -> a = function
4343+ | Int n -> n (* a = int *)
4444+ | Add -> (fun x y -> x+y) (* a = int -> int -> int *)
4545+ | App(f,x) -> (eval f) (eval x)
4646+ (* eval called at types (b->a) and b for fresh b *)
4747+\end{caml_example*}
4848+4949+And use it:
5050+5151+\begin{caml_example}{verbatim}
5252+let two = eval (App (App (Add, Int 1), Int 1))
5353+\end{caml_example}
5454+It is important to remark that the function "eval" is using the
5555+polymorphic syntax for locally abstract types. When defining a recursive
5656+function that manipulates a GADT, explicit polymorphic recursion should
5757+generally be used. For instance, the following definition fails with a
5858+type error:
5959+\begin{caml_example}{verbatim}[error]
6060+let rec eval (type a) : a term -> a = function
6161+ | Int n -> n
6262+ | Add -> (fun x y -> x+y)
6363+ | App(f,x) -> (eval f) (eval x)
6464+\end{caml_example}
6565+In absence of an explicit polymorphic annotation, a monomorphic type
6666+is inferred for the recursive function. If a recursive call occurs
6767+inside the function definition at a type that involves an existential
6868+GADT type variable, this variable flows to the type of the recursive
6969+function, and thus escapes its scope. In the above example, this happens
7070+in the branch "App(f,x)" when "eval" is called with "f" as an argument.
7171+In this branch, the type of "f" is "($App_ 'b-> a)". The prefix "$" in
7272+"$App_ 'b" denotes an existential type named by the compiler
7373+(see~\ref{s:existential-names}). Since the type of "eval" is
7474+"'a term -> 'a", the call "eval f" makes the existential type "$App_'b"
7575+flow to the type variable "'a" and escape its scope. This triggers the
7676+above error.
7777+7878+\section{s:gadts-type-inference}{Type inference}
7979+8080+Type inference for GADTs is notoriously hard.
8181+This is due to the fact some types may become ambiguous when escaping
8282+from a branch.
8383+For instance, in the "Int" case above, "n" could have either type "int"
8484+or "a", and they are not equivalent outside of that branch.
8585+As a first approximation, type inference will always work if a
8686+pattern-matching is annotated with types containing no free type
8787+variables (both on the scrutinee and the return type).
8888+This is the case in the above example, thanks to the type annotation
8989+containing only locally abstract types.
9090+9191+In practice, type inference is a bit more clever than that: type
9292+annotations do not need to be immediately on the pattern-matching, and
9393+the types do not have to be always closed.
9494+As a result, it is usually enough to only annotate functions, as in
9595+the example above. Type annotations are
9696+propagated in two ways: for the scrutinee, they follow the flow of
9797+type inference, in a way similar to polymorphic methods; for the
9898+return type, they follow the structure of the program, they are split
9999+on functions, propagated to all branches of a pattern matching,
100100+and go through tuples, records, and sum types.
101101+Moreover, the notion of ambiguity used is stronger: a type is only
102102+seen as ambiguous if it was mixed with incompatible types (equated by
103103+constraints), without type annotations between them.
104104+For instance, the following program types correctly.
105105+\begin{caml_example}{verbatim}
106106+let rec sum : type a. a term -> _ = fun x ->
107107+ let y =
108108+ match x with
109109+ | Int n -> n
110110+ | Add -> 0
111111+ | App(f,x) -> sum f + sum x
112112+ in y + 1
113113+\end{caml_example}
114114+Here the return type "int" is never mixed with "a", so it is seen as
115115+non-ambiguous, and can be inferred.
116116+When using such partial type annotations we strongly suggest
117117+specifying the "-principal" mode, to check that inference is
118118+principal.
119119+120120+The exhaustiveness check is aware of GADT constraints, and can
121121+automatically infer that some cases cannot happen.
122122+For instance, the following pattern matching is correctly seen as
123123+exhaustive (the "Add" case cannot happen).
124124+\begin{caml_example*}{verbatim}
125125+let get_int : int term -> int = function
126126+ | Int n -> n
127127+ | App(_,_) -> 0
128128+\end{caml_example*}
129129+130130+131131+\section{s:gadt-refutation-cases}{Refutation cases}
132132+133133+Usually, the exhaustiveness check only tries to check whether the
134134+cases omitted from the pattern matching are typable or not.
135135+However, you can force it to try harder by adding {\em refutation cases},
136136+written as a full stop.
137137+In the presence of a refutation case, the exhaustiveness check will first
138138+compute the intersection of the pattern with the complement of the
139139+cases preceding it. It then checks whether the resulting patterns can
140140+really match any concrete values by trying to type-check them.
141141+Wild cards in the generated patterns are handled in a special way: if
142142+their type is a variant type with only GADT constructors, then the
143143+pattern is split into the different constructors, in order to check whether
144144+any of them is possible (this splitting is not done for arguments of these
145145+constructors, to avoid non-termination). We also split tuples and
146146+variant types with only one case, since they may contain GADTs inside.
147147+For instance, the following code is deemed exhaustive:
148148+149149+\begin{caml_example*}{verbatim}
150150+type _ t =
151151+ | Int : int t
152152+ | Bool : bool t
153153+154154+let deep : (char t * int) option -> char = function
155155+ | None -> 'c'
156156+ | _ -> .
157157+\end{caml_example*}
158158+159159+Namely, the inferred remaining case is "Some _", which is split into
160160+"Some (Int, _)" and "Some (Bool, _)", which are both untypable because
161161+"deep" expects a non-existing "char t" as the first element of the tuple.
162162+Note that the refutation case could be omitted here, because it is
163163+automatically added when there is only one case in the pattern
164164+matching.
165165+166166+Another addition is that the redundancy check is now aware of GADTs: a
167167+case will be detected as redundant if it could be replaced by a
168168+refutation case using the same pattern.
169169+170170+\section{s:gadts-advexamples}{Advanced examples}
171171+The "term" type we have defined above is an {\em indexed} type, where
172172+a type parameter reflects a property of the value contents.
173173+Another use of GADTs is {\em singleton} types, where a GADT value
174174+represents exactly one type. This value can be used as runtime
175175+representation for this type, and a function receiving it can have a
176176+polytypic behavior.
177177+178178+Here is an example of a polymorphic function that takes the
179179+runtime representation of some type "t" and a value of the same type,
180180+then pretty-prints the value as a string:
181181+\begin{caml_example*}{verbatim}
182182+type _ typ =
183183+ | Int : int typ
184184+ | String : string typ
185185+ | Pair : 'a typ * 'b typ -> ('a * 'b) typ
186186+187187+let rec to_string: type t. t typ -> t -> string =
188188+ fun t x ->
189189+ match t with
190190+ | Int -> Int.to_string x
191191+ | String -> Printf.sprintf "%S" x
192192+ | Pair(t1,t2) ->
193193+ let (x1, x2) = x in
194194+ Printf.sprintf "(%s,%s)" (to_string t1 x1) (to_string t2 x2)
195195+\end{caml_example*}
196196+197197+Another frequent application of GADTs is equality witnesses.
198198+\begin{caml_example*}{verbatim}
199199+type (_,_) eq = Eq : ('a,'a) eq
200200+201201+let cast : type a b. (a,b) eq -> a -> b = fun Eq x -> x
202202+\end{caml_example*}
203203+Here type "eq" has only one constructor, and by matching on it one
204204+adds a local constraint allowing the conversion between "a" and "b".
205205+By building such equality witnesses, one can make equal types which
206206+are syntactically different.
207207+208208+Here is an example using both singleton types and equality witnesses
209209+to implement dynamic types.
210210+\begin{caml_example*}{verbatim}
211211+let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option =
212212+ fun a b ->
213213+ match a, b with
214214+ | Int, Int -> Some Eq
215215+ | String, String -> Some Eq
216216+ | Pair(a1,a2), Pair(b1,b2) ->
217217+ begin match eq_type a1 b1, eq_type a2 b2 with
218218+ | Some Eq, Some Eq -> Some Eq
219219+ | _ -> None
220220+ end
221221+ | _ -> None
222222+223223+type dyn = Dyn : 'a typ * 'a -> dyn
224224+225225+let get_dyn : type a. a typ -> dyn -> a option =
226226+ fun a (Dyn(b,x)) ->
227227+ match eq_type a b with
228228+ | None -> None
229229+ | Some Eq -> Some x
230230+\end{caml_example*}
231231+232232+\section{s:existential-names}{Existential type names in error messages}
233233+234234+The typing of pattern matching in presence of GADT can generate many
235235+existential types. When necessary, error messages refer to these
236236+existential types using compiler-generated names. Currently, the
237237+compiler generates these names according to the following nomenclature:
238238+\begin{itemize}
239239+\item First, types whose name starts with a "$" are existentials.
240240+\item "$Constr_'a" denotes an existential type introduced for the type
241241+variable "'a" of the GADT constructor "Constr":
242242+\begin{caml_example}{verbatim}[error]
243243+type any = Any : 'name -> any
244244+let escape (Any x) = x
245245+\end{caml_example}
246246+\item "$Constr" denotes an existential type introduced for an anonymous %$
247247+type variable in the GADT constructor "Constr":
248248+\begin{caml_example}{verbatim}[error]
249249+type any = Any : _ -> any
250250+let escape (Any x) = x
251251+\end{caml_example}
252252+\item "$'a" if the existential variable was unified with the type %$
253253+variable "'a" during typing:
254254+\begin{caml_example}{verbatim}[error]
255255+type ('arg,'result,'aux) fn =
256256+ | Fun: ('a ->'b) -> ('a,'b,unit) fn
257257+ | Mem1: ('a ->'b) * 'a * 'b -> ('a, 'b, 'a * 'b) fn
258258+ let apply: ('arg,'result, _ ) fn -> 'arg -> 'result = fun f x ->
259259+ match f with
260260+ | Fun f -> f x
261261+ | Mem1 (f,y,fy) -> if x = y then fy else f x
262262+\end{caml_example}
263263+\item "$n" (n a number) is an internally generated existential %$
264264+which could not be named using one of the previous schemes.
265265+\end{itemize}
266266+267267+As shown by the last item, the current behavior is imperfect
268268+and may be improved in future versions.
269269+270270+\section{s:explicit-existential-name}{Explicit naming of existentials}
271271+272272+As explained above, pattern-matching on a GADT constructor may introduce
273273+existential types. Syntax has been introduced which allows them to be named
274274+explicitly. For instance, the following code names the type of the argument of
275275+"f" and uses this name.
276276+277277+\begin{caml_example*}{verbatim}
278278+type _ closure = Closure : ('a -> 'b) * 'a -> 'b closure
279279+let eval = fun (Closure (type a) (f, x : (a -> _) * _)) -> f (x : a)
280280+\end{caml_example*}
281281+All existential type variables of the constructor must by introduced by
282282+the ("type" ...) construct and bound by a type annotation on the
283283+outside of the constructor argument.
284284+285285+\section{s:gadt-equation-nonlocal-abstract}{Equations on non-local abstract types}
286286+287287+GADT pattern-matching may also add type equations to non-local
288288+abstract types. The behaviour is the same as with local abstract
289289+types. Reusing the above "eq" type, one can write:
290290+\begin{caml_example*}{verbatim}
291291+module M : sig type t val x : t val e : (t,int) eq end = struct
292292+ type t = int
293293+ let x = 33
294294+ let e = Eq
295295+end
296296+297297+let x : int = let Eq = M.e in M.x
298298+\end{caml_example*}
299299+300300+Of course, not all abstract types can be refined, as this would
301301+contradict the exhaustiveness check. Namely, builtin types (those
302302+defined by the compiler itself, such as "int" or "array"), and
303303+abstract types defined by the local module, are non-instantiable, and
304304+as such cause a type error rather than introduce an equation.
+5-194
manual/src/tutorials/lablexamples.etex
···11-\chapter{Labels and variants} \label{c:labl-examples}
11+\chapter{Labeled arguments} \label{c:labl-examples}
22%HEVEA\cutname{lablexamples.html}
33{\it (Chapter written by Jacques Garrigue)}
44-55-\bigskip
66-77-\noindent This chapter gives an overview of the new features in
88-OCaml 3: labels, and polymorphic variants.
99-1010-\section{s:labels}{Labels}
114125If you have a look at modules ending in "Labels" in the standard
136library, you will see that function types have annotations you did not
···4235cannot use a reserved keyword (like "in" or "to") as label.
43364437Formal parameters and arguments are matched according to their
4545-respective labels\footnote{This corresponds to the commuting label mode
4646-of Objective Caml 3.00 through 3.02, with some additional flexibility
4747-on total applications. The so-called classic mode ("-nolabels"
4848-options) is now deprecated for normal use.}, the absence of label
3838+respective labels, the absence of label
4939being interpreted as the empty label.
5040%
5141This allows commuting arguments in applications. One can also
···6959hline ~x:3 ~y:2 ~x:5;;
7060\end{caml_example}
71617272-\subsection{ss:optional-arguments}{Optional arguments}
6262+\section{s:optional-arguments}{Optional arguments}
73637464An interesting feature of labeled arguments is that they can be made
7565optional. For optional parameters, the question mark "?" replaces the
···133123test2 ?x:None;;
134124\end{caml_example}
135125136136-\subsection{ss:label-inference}{Labels and type inference}
126126+\section{s:label-inference}{Labels and type inference}
137127138128While they provide an increased comfort for writing function
139129applications, labels and optional arguments have the pitfall that they
···199189parameters shall produce side-effects, these are delayed until the
200190received function is really applied to an argument.
201191202202-\subsection{ss:label-suggestions}{Suggestions for labeling}
192192+\section{s:label-suggestions}{Suggestions for labeling}
203193204194Like for names, choosing labels for functions is not an easy task. A
205195good labeling is a labeling which
···278268\begin{caml_eval}
279269#label false;;
280270\end{caml_eval}
281281-282282-283283-\section{s:polymorphic-variants}{Polymorphic variants}
284284-285285-Variants as presented in section~\ref{s:tut-recvariants} are a
286286-powerful tool to build data structures and algorithms. However they
287287-sometimes lack flexibility when used in modular programming. This is
288288-due to the fact that every constructor is assigned to a unique type
289289-when defined and used. Even if the same name appears in the definition
290290-of multiple types, the constructor itself belongs to only one type.
291291-Therefore, one cannot decide that a given constructor belongs to
292292-multiple types, or consider a value of some type to belong to some
293293-other type with more constructors.
294294-295295-With polymorphic variants, this original assumption is removed. That
296296-is, a variant tag does not belong to any type in particular, the type
297297-system will just check that it is an admissible value according to its
298298-use. You need not define a type before using a variant tag. A variant
299299-type will be inferred independently for each of its uses.
300300-301301-\subsection*{ss:polyvariant:basic-use}{Basic use}
302302-303303-In programs, polymorphic variants work like usual ones. You just have
304304-to prefix their names with a backquote character "`".
305305-\begin{caml_example}{toplevel}
306306-[`On; `Off];;
307307-`Number 1;;
308308-let f = function `On -> 1 | `Off -> 0 | `Number n -> n;;
309309-List.map f [`On; `Off];;
310310-\end{caml_example}
311311-"[>`Off|`On] list" means that to match this list, you should at
312312-least be able to match "`Off" and "`On", without argument.
313313-"[<`On|`Off|`Number of int]" means that "f" may be applied to "`Off",
314314-"`On" (both without argument), or "`Number" $n$ where
315315-$n$ is an integer.
316316-The ">" and "<" inside the variant types show that they may still be
317317-refined, either by defining more tags or by allowing less. As such, they
318318-contain an implicit type variable. Because each of the variant types
319319-appears only once in the whole type, their implicit type variables are
320320-not shown.
321321-322322-The above variant types were polymorphic, allowing further refinement.
323323-When writing type annotations, one will most often describe fixed
324324-variant types, that is types that cannot be refined. This is
325325-also the case for type abbreviations. Such types do not contain "<" or
326326-">", but just an enumeration of the tags and their associated types,
327327-just like in a normal datatype definition.
328328-\begin{caml_example}{toplevel}
329329-type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
330330-let rec map f : 'a vlist -> 'b vlist = function
331331- | `Nil -> `Nil
332332- | `Cons(a, l) -> `Cons(f a, map f l)
333333-;;
334334-\end{caml_example}
335335-336336-\subsection*{ss:polyvariant-advanced}{Advanced use}
337337-338338-Type-checking polymorphic variants is a subtle thing, and some
339339-expressions may result in more complex type information.
340340-341341-\begin{caml_example}{toplevel}
342342-let f = function `A -> `C | `B -> `D | x -> x;;
343343-f `E;;
344344-\end{caml_example}
345345-Here we are seeing two phenomena. First, since this matching is open
346346-(the last case catches any tag), we obtain the type "[> `A | `B]"
347347-rather than "[< `A | `B]" in a closed matching. Then, since "x" is
348348-returned as is, input and return types are identical. The notation "as
349349-'a" denotes such type sharing. If we apply "f" to yet another tag
350350-"`E", it gets added to the list.
351351-352352-\begin{caml_example}{toplevel}
353353-let f1 = function `A x -> x = 1 | `B -> true | `C -> false
354354-let f2 = function `A x -> x = "a" | `B -> true ;;
355355-let f x = f1 x && f2 x;;
356356-\end{caml_example}
357357-Here "f1" and "f2" both accept the variant tags "`A" and "`B", but the
358358-argument of "`A" is "int" for "f1" and "string" for "f2". In "f"'s
359359-type "`C", only accepted by "f1", disappears, but both argument types
360360-appear for "`A" as "int & string". This means that if we
361361-pass the variant tag "`A" to "f", its argument should be {\em both}
362362-"int" and "string". Since there is no such value, "f" cannot be
363363-applied to "`A", and "`B" is the only accepted input.
364364-365365-Even if a value has a fixed variant type, one can still give it a
366366-larger type through coercions. Coercions are normally written with
367367-both the source type and the destination type, but in simple cases the
368368-source type may be omitted.
369369-\begin{caml_example}{toplevel}
370370-type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
371371-let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);;
372372-let open_vlist l = (l : 'a vlist :> [> 'a vlist]);;
373373-fun x -> (x :> [`A|`B|`C]);;
374374-\end{caml_example}
375375-376376-You may also selectively coerce values through pattern matching.
377377-\begin{caml_example}{toplevel}
378378-let split_cases = function
379379- | `Nil | `Cons _ as x -> `A x
380380- | `Snoc _ as x -> `B x
381381-;;
382382-\end{caml_example}
383383-When an or-pattern composed of variant tags is wrapped inside an
384384-alias-pattern, the alias is given a type containing only the tags
385385-enumerated in the or-pattern. This allows for many useful idioms, like
386386-incremental definition of functions.
387387-388388-\begin{caml_example}{toplevel}
389389-let num x = `Num x
390390-let eval1 eval (`Num x) = x
391391-let rec eval x = eval1 eval x ;;
392392-let plus x y = `Plus(x,y)
393393-let eval2 eval = function
394394- | `Plus(x,y) -> eval x + eval y
395395- | `Num _ as x -> eval1 eval x
396396-let rec eval x = eval2 eval x ;;
397397-\end{caml_example}
398398-399399-To make this even more comfortable, you may use type definitions as
400400-abbreviations for or-patterns. That is, if you have defined "type
401401-myvariant = [`Tag1 of int | `Tag2 of bool]", then the pattern "#myvariant" is
402402-equivalent to writing "(`Tag1(_ : int) | `Tag2(_ : bool))".
403403-\begin{caml_eval}
404404-type myvariant = [`Tag1 of int | `Tag2 of bool];;
405405-\end{caml_eval}
406406-407407-Such abbreviations may be used alone,
408408-\begin{caml_example}{toplevel}
409409-let f = function
410410- | #myvariant -> "myvariant"
411411- | `Tag3 -> "Tag3";;
412412-\end{caml_example}
413413-or combined with with aliases.
414414-\begin{caml_example}{toplevel}
415415-let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
416416-let g = function
417417- | #myvariant as x -> g1 x
418418- | `Tag3 -> "Tag3";;
419419-\end{caml_example}
420420-421421-\subsection{ss:polyvariant-weaknesses}{Weaknesses of polymorphic variants}
422422-423423-After seeing the power of polymorphic variants, one may wonder why
424424-they were added to core language variants, rather than replacing them.
425425-426426-The answer is twofold. One first aspect is that while being pretty
427427-efficient, the lack of static type information allows for less
428428-optimizations, and makes polymorphic variants slightly heavier than
429429-core language ones. However noticeable differences would only
430430-appear on huge data structures.
431431-432432-More important is the fact that polymorphic variants, while being
433433-type-safe, result in a weaker type discipline. That is, core language
434434-variants do actually much more than ensuring type-safety, they also
435435-check that you use only declared constructors, that all constructors
436436-present in a data-structure are compatible, and they enforce typing
437437-constraints to their parameters.
438438-439439-For this reason, you must be more careful about making types explicit
440440-when you use polymorphic variants. When you write a library, this is
441441-easy since you can describe exact types in interfaces, but for simple
442442-programs you are probably better off with core language variants.
443443-444444-Beware also that some idioms make trivial errors very hard to find.
445445-For instance, the following code is probably wrong but the compiler
446446-has no way to see it.
447447-\begin{caml_example}{toplevel}
448448-type abc = [`A | `B | `C] ;;
449449-let f = function
450450- | `As -> "A"
451451- | #abc -> "other" ;;
452452-let f : abc -> string = f ;;
453453-\end{caml_example}
454454-You can avoid such risks by annotating the definition itself.
455455-\begin{caml_example}{toplevel}[error]
456456-let f : abc -> string = function
457457- | `As -> "A"
458458- | #abc -> "other" ;;
459459-\end{caml_example}
+179
manual/src/tutorials/polyvariant.etex
···11+\chapter{Polymorphic variants} \label{c:poly-variant}
22+%HEVEA\cutname{polyvariant.html}
33+{\it (Chapter written by Jacques Garrigue)}
44+55+Variants as presented in section~\ref{s:tut-recvariants} are a
66+powerful tool to build data structures and algorithms. However they
77+sometimes lack flexibility when used in modular programming. This is
88+due to the fact that every constructor is assigned to a unique type
99+when defined and used. Even if the same name appears in the definition
1010+of multiple types, the constructor itself belongs to only one type.
1111+Therefore, one cannot decide that a given constructor belongs to
1212+multiple types, or consider a value of some type to belong to some
1313+other type with more constructors.
1414+1515+With polymorphic variants, this original assumption is removed. That
1616+is, a variant tag does not belong to any type in particular, the type
1717+system will just check that it is an admissible value according to its
1818+use. You need not define a type before using a variant tag. A variant
1919+type will be inferred independently for each of its uses.
2020+2121+\section{s:polyvariant:basic-use}{Basic use}
2222+2323+In programs, polymorphic variants work like usual ones. You just have
2424+to prefix their names with a backquote character "`".
2525+\begin{caml_example}{toplevel}
2626+[`On; `Off];;
2727+`Number 1;;
2828+let f = function `On -> 1 | `Off -> 0 | `Number n -> n;;
2929+List.map f [`On; `Off];;
3030+\end{caml_example}
3131+"[>`Off|`On] list" means that to match this list, you should at
3232+least be able to match "`Off" and "`On", without argument.
3333+"[<`On|`Off|`Number of int]" means that "f" may be applied to "`Off",
3434+"`On" (both without argument), or "`Number" $n$ where
3535+$n$ is an integer.
3636+The ">" and "<" inside the variant types show that they may still be
3737+refined, either by defining more tags or by allowing less. As such, they
3838+contain an implicit type variable. Because each of the variant types
3939+appears only once in the whole type, their implicit type variables are
4040+not shown.
4141+4242+The above variant types were polymorphic, allowing further refinement.
4343+When writing type annotations, one will most often describe fixed
4444+variant types, that is types that cannot be refined. This is
4545+also the case for type abbreviations. Such types do not contain "<" or
4646+">", but just an enumeration of the tags and their associated types,
4747+just like in a normal datatype definition.
4848+\begin{caml_example}{toplevel}
4949+type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
5050+let rec map f : 'a vlist -> 'b vlist = function
5151+ | `Nil -> `Nil
5252+ | `Cons(a, l) -> `Cons(f a, map f l)
5353+;;
5454+\end{caml_example}
5555+5656+\section{s:polyvariant-advanced}{Advanced use}
5757+5858+Type-checking polymorphic variants is a subtle thing, and some
5959+expressions may result in more complex type information.
6060+6161+\begin{caml_example}{toplevel}
6262+let f = function `A -> `C | `B -> `D | x -> x;;
6363+f `E;;
6464+\end{caml_example}
6565+Here we are seeing two phenomena. First, since this matching is open
6666+(the last case catches any tag), we obtain the type "[> `A | `B]"
6767+rather than "[< `A | `B]" in a closed matching. Then, since "x" is
6868+returned as is, input and return types are identical. The notation "as
6969+'a" denotes such type sharing. If we apply "f" to yet another tag
7070+"`E", it gets added to the list.
7171+7272+\begin{caml_example}{toplevel}
7373+let f1 = function `A x -> x = 1 | `B -> true | `C -> false
7474+let f2 = function `A x -> x = "a" | `B -> true ;;
7575+let f x = f1 x && f2 x;;
7676+\end{caml_example}
7777+Here "f1" and "f2" both accept the variant tags "`A" and "`B", but the
7878+argument of "`A" is "int" for "f1" and "string" for "f2". In "f"'s
7979+type "`C", only accepted by "f1", disappears, but both argument types
8080+appear for "`A" as "int & string". This means that if we
8181+pass the variant tag "`A" to "f", its argument should be {\em both}
8282+"int" and "string". Since there is no such value, "f" cannot be
8383+applied to "`A", and "`B" is the only accepted input.
8484+8585+Even if a value has a fixed variant type, one can still give it a
8686+larger type through coercions. Coercions are normally written with
8787+both the source type and the destination type, but in simple cases the
8888+source type may be omitted.
8989+\begin{caml_example}{toplevel}
9090+type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
9191+let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);;
9292+let open_vlist l = (l : 'a vlist :> [> 'a vlist]);;
9393+fun x -> (x :> [`A|`B|`C]);;
9494+\end{caml_example}
9595+9696+You may also selectively coerce values through pattern matching.
9797+\begin{caml_example}{toplevel}
9898+let split_cases = function
9999+ | `Nil | `Cons _ as x -> `A x
100100+ | `Snoc _ as x -> `B x
101101+;;
102102+\end{caml_example}
103103+When an or-pattern composed of variant tags is wrapped inside an
104104+alias-pattern, the alias is given a type containing only the tags
105105+enumerated in the or-pattern. This allows for many useful idioms, like
106106+incremental definition of functions.
107107+108108+\begin{caml_example}{toplevel}
109109+let num x = `Num x
110110+let eval1 eval (`Num x) = x
111111+let rec eval x = eval1 eval x ;;
112112+let plus x y = `Plus(x,y)
113113+let eval2 eval = function
114114+ | `Plus(x,y) -> eval x + eval y
115115+ | `Num _ as x -> eval1 eval x
116116+let rec eval x = eval2 eval x ;;
117117+\end{caml_example}
118118+119119+To make this even more comfortable, you may use type definitions as
120120+abbreviations for or-patterns. That is, if you have defined "type
121121+myvariant = [`Tag1 of int | `Tag2 of bool]", then the pattern "#myvariant" is
122122+equivalent to writing "(`Tag1(_ : int) | `Tag2(_ : bool))".
123123+\begin{caml_eval}
124124+type myvariant = [`Tag1 of int | `Tag2 of bool];;
125125+\end{caml_eval}
126126+127127+Such abbreviations may be used alone,
128128+\begin{caml_example}{toplevel}
129129+let f = function
130130+ | #myvariant -> "myvariant"
131131+ | `Tag3 -> "Tag3";;
132132+\end{caml_example}
133133+or combined with with aliases.
134134+\begin{caml_example}{toplevel}
135135+let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
136136+let g = function
137137+ | #myvariant as x -> g1 x
138138+ | `Tag3 -> "Tag3";;
139139+\end{caml_example}
140140+141141+\section{s:polyvariant-weaknesses}{Weaknesses of polymorphic variants}
142142+143143+After seeing the power of polymorphic variants, one may wonder why
144144+they were added to core language variants, rather than replacing them.
145145+146146+The answer is twofold. One first aspect is that while being pretty
147147+efficient, the lack of static type information allows for less
148148+optimizations, and makes polymorphic variants slightly heavier than
149149+core language ones. However noticeable differences would only
150150+appear on huge data structures.
151151+152152+More important is the fact that polymorphic variants, while being
153153+type-safe, result in a weaker type discipline. That is, core language
154154+variants do actually much more than ensuring type-safety, they also
155155+check that you use only declared constructors, that all constructors
156156+present in a data-structure are compatible, and they enforce typing
157157+constraints to their parameters.
158158+159159+For this reason, you must be more careful about making types explicit
160160+when you use polymorphic variants. When you write a library, this is
161161+easy since you can describe exact types in interfaces, but for simple
162162+programs you are probably better off with core language variants.
163163+164164+Beware also that some idioms make trivial errors very hard to find.
165165+For instance, the following code is probably wrong but the compiler
166166+has no way to see it.
167167+\begin{caml_example}{toplevel}
168168+type abc = [`A | `B | `C] ;;
169169+let f = function
170170+ | `As -> "A"
171171+ | #abc -> "other" ;;
172172+let f : abc -> string = f ;;
173173+\end{caml_example}
174174+You can avoid such risks by annotating the definition itself.
175175+\begin{caml_example}{toplevel}[error]
176176+let f : abc -> string = function
177177+ | `As -> "A"
178178+ | #abc -> "other" ;;
179179+\end{caml_example}
+3-3
ocamldoc/odoc_ast.ml
···258258259259 | Typedtree.Tpat_construct (_, cons_desc, _, _) when
260260 (* we give a name to the parameter only if it is unit *)
261261- (match cons_desc.cstr_res.desc with
261261+ (match get_desc cons_desc.cstr_res with
262262 Tconstr (p, _, _) ->
263263 Path.same p Predef.path_unit
264264 | _ ->
···585585 with Not_found -> raise (Failure (Odoc_messages.method_type_not_found current_class_name label))
586586 in
587587 let real_type =
588588- match met_type.Types.desc with
588588+ match get_desc met_type with
589589 Tarrow (_, _, t, _) ->
590590 t
591591 | _ ->
···627627 with Not_found -> raise (Failure (Odoc_messages.method_not_found_in_typedtree complete_name))
628628 in
629629 let real_type =
630630- match exp.exp_type.desc with
630630+ match get_desc exp.exp_type with
631631 Tarrow (_, _, t,_) ->
632632 t
633633 | _ ->
+23-18
ocamldoc/odoc_env.ml
···169169 if List.memq t !deja_vu then () else begin
170170 deja_vu := t :: !deja_vu;
171171 Btype.iter_type_expr iter t;
172172- match t.Types.desc with
173173- | Types.Tconstr (p, [_], _) when Path.same p Predef.path_option ->
172172+ let open Types in
173173+ match get_desc t with
174174+ | Tconstr (p, [_], _) when Path.same p Predef.path_option ->
174175 ()
175175- | Types.Tconstr (p, l, a) ->
176176+ | Tconstr (p, l, a) ->
176177 let new_p =
177178 Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
178178- Btype.set_type_desc t (Types.Tconstr (new_p, l, a))
179179- | Types.Tpackage (p, fl) ->
179179+ set_type_desc t (Tconstr (new_p, l, a))
180180+ | Tpackage (p, fl) ->
180181 let new_p =
181181- Odoc_name.to_path (full_module_type_name env (Odoc_name.from_path p)) in
182182- Btype.set_type_desc t (Types.Tpackage (new_p, fl))
183183- | Types.Tobject (_, ({contents=Some(p,tyl)} as r)) ->
182182+ Odoc_name.to_path
183183+ (full_module_type_name env (Odoc_name.from_path p)) in
184184+ set_type_desc t (Tpackage (new_p, fl))
185185+ | Tobject (_, ({contents=Some(p,tyl)} as r)) ->
184186 let new_p =
185187 Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
186188 r := Some (new_p, tyl)
187187- | Types.Tvariant ({Types.row_name=Some(p, tyl)} as row) ->
189189+ | Tvariant ({row_name=Some(p, tyl)} as row) ->
188190 let new_p =
189191 Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
190190- Btype.set_type_desc t
191191- (Types.Tvariant {row with Types.row_name=Some(new_p, tyl)})
192192+ set_type_desc t (Tvariant {row with row_name=Some(new_p, tyl)})
192193 | _ ->
193194 ()
194195 end
···202203 let open Types in
203204 match t with
204205 Mty_ident p ->
205205- let new_p = Odoc_name.to_path (full_module_type_name env (Odoc_name.from_path p)) in
206206+ let new_p =
207207+ Odoc_name.to_path (full_module_type_name env (Odoc_name.from_path p))
208208+ in
206209 Mty_ident new_p
207210 | Mty_alias _
208211 | Mty_signature _ ->
···215218216219let subst_class_type env t =
217220 let rec iter t =
221221+ let open Types in
218222 match t with
219219- Types.Cty_constr (p,texp_list,ct) ->
220220- let new_p = Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
223223+ Cty_constr (p,texp_list,ct) ->
224224+ let new_p =
225225+ Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
221226 let new_texp_list = List.map (subst_type env) texp_list in
222227 let new_ct = iter ct in
223223- Types.Cty_constr (new_p, new_texp_list, new_ct)
224224- | Types.Cty_signature _ ->
228228+ Cty_constr (new_p, new_texp_list, new_ct)
229229+ | Cty_signature _ ->
225230 (* we don't handle vals and methods *)
226231 t
227227- | Types.Cty_arrow (l, texp, ct) ->
232232+ | Cty_arrow (l, texp, ct) ->
228233 let new_texp = subst_type env texp in
229234 let new_ct = iter ct in
230230- Types.Cty_arrow (l, new_texp, new_ct)
235235+ Cty_arrow (l, new_texp, new_ct)
231236 in
232237 iter t
+22-17
ocamldoc/odoc_misc.ml
···492492let label_name = Btype.label_name
493493494494let remove_option typ =
495495- let rec iter t =
495495+ let open Types in
496496+ let rec trim t =
496497 match t with
497497- | Types.Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty.Types.desc
498498- | Types.Tconstr _
499499- | Types.Tvar _
500500- | Types.Tunivar _
501501- | Types.Tpoly _
502502- | Types.Tarrow _
503503- | Types.Ttuple _
504504- | Types.Tobject _
505505- | Types.Tfield _
506506- | Types.Tnil
507507- | Types.Tvariant _
508508- | Types.Tpackage _ -> t
509509- | Types.Tlink t2 -> iter t2.Types.desc
510510- | Types.Tsubst _ -> assert false
498498+ | Tconstr(path, [ty], _)
499499+ when Path.same path Predef.path_option -> get_desc ty
500500+ | Tconstr _
501501+ | Tvar _
502502+ | Tunivar _
503503+ | Tpoly _
504504+ | Tarrow _
505505+ | Ttuple _
506506+ | Tobject _
507507+ | Tfield _
508508+ | Tnil
509509+ | Tvariant _
510510+ | Tpackage _ -> t
511511+ | Tlink t2 -> trim (get_desc t2)
512512+ | Tsubst _ -> assert false
511513 in
512512- Types.Private_type_expr.create (iter typ.Types.desc)
513513- ~level:typ.Types.level ~scope:typ.Types.scope ~id:typ.Types.id
514514+ Transient_expr.type_expr
515515+ (Transient_expr.create (trim (get_desc typ))
516516+ ~level:(get_level typ)
517517+ ~scope:(get_scope typ)
518518+ ~id:(get_id typ))
+16-12
ocamldoc/odoc_print.ml
···8181 from the signatures. Used when we don't want to print a too long class type.*)
8282let simpl_class_type t =
8383 let rec iter t =
8484+ let open Types in
8485 match t with
8585- Types.Cty_constr _ -> t
8686- | Types.Cty_signature cs ->
8686+ Cty_constr _ -> t
8787+ | Cty_signature cs ->
8788 (* we delete vals and methods in order to not print them when
8889 displaying the type *)
8990 let tself =
9090- let t = cs.Types.csig_self in
9191- let t' = Types.Private_type_expr.create Types.Tnil
9191+ let t = cs.csig_self in
9292+ let t' = Transient_expr.create Tnil
9293 ~level:0 ~scope:Btype.lowest_level ~id:0 in
9393- let desc = Types.Tobject (t', ref None) in
9494- Types.Private_type_expr.create desc
9595- ~level:t.Types.level ~scope:t.Types.scope ~id:t.Types.id
9494+ let desc =
9595+ Tobject (Transient_expr.type_expr t', ref None) in
9696+ Transient_expr.create desc
9797+ ~level:(get_level t)
9898+ ~scope:(get_scope t)
9999+ ~id:(get_id t)
96100 in
9797- Types.Cty_signature { Types.csig_self = tself;
9898- csig_vars = Types.Vars.empty ;
9999- csig_concr = Types.Concr.empty ;
101101+ Cty_signature { csig_self = Transient_expr.type_expr tself;
102102+ csig_vars = Vars.empty ;
103103+ csig_concr = Concr.empty ;
100104 csig_inher = []
101105 }
102102- | Types.Cty_arrow (l, texp, ct) ->
106106+ | Cty_arrow (l, texp, ct) ->
103107 let new_ct = iter ct in
104104- Types.Cty_arrow (l, texp, new_ct)
108108+ Cty_arrow (l, texp, new_ct)
105109 in
106110 iter t
107111
+1-1
ocamldoc/odoc_sig.ml
···341341342342343343 let manifest_structure env name_comment_list type_expr =
344344- match type_expr.desc with
344344+ match get_desc type_expr with
345345 | Tobject (fields, _) ->
346346 let f (field_name, _, type_expr) =
347347 let comment_opt =
+2-2
ocamldoc/odoc_str.ml
···3030 else
3131 ""
3232let rec is_arrow_type t =
3333- match t.Types.desc with
3333+ match Types.get_desc t with
3434 Types.Tarrow _ -> true
3535 | Types.Tlink t2 -> is_arrow_type t2
3636 | Types.Ttuple _
···4343 let buf = Buffer.create 256 in
4444 let fmt = Format.formatter_of_buffer buf in
4545 let rec need_parent t =
4646- match t.Types.desc with
4646+ match Types.get_desc t with
4747 Types.Tarrow _ | Types.Ttuple _ -> true
4848 | Types.Tlink t2 -> need_parent t2
4949 | Types.Tconstr _
+3-3
ocamldoc/odoc_value.ml
···7272 [parameter_list_from_arrows t = [ a ; b ]] if t = a -> b -> c.*)
7373let parameter_list_from_arrows typ =
7474 let rec iter t =
7575- match t.Types.desc with
7575+ match Types.get_desc t with
7676 Types.Tarrow (l, t1, t2, _) ->
7777 (l, t1) :: (iter t2)
7878 | Types.Tlink texp
···102102 Printtyp.mark_loops typ;
103103 let liste_param = parameter_list_from_arrows typ in
104104 let rec iter (label, t) =
105105- match t.Types.desc with
105105+ match Types.get_desc t with
106106 | Types.Ttuple l ->
107107 let open Asttypes in
108108 if label = Nolabel then
···129129(** Return true if the value is a function, i.e. has a functional type.*)
130130let is_function v =
131131 let rec f t =
132132- match t.Types.desc with
132132+ match Types.get_desc t with
133133 Types.Tarrow _ ->
134134 true
135135 | Types.Tlink t ->
-6
otherlibs/unix/socketaddr.c
···5555 socklen_param_type * adr_len /*out*/)
5656{
5757 switch(Tag_val(mladr)) {
5858-#ifndef _WIN32
5958 case 0: /* ADDR_UNIX */
6059 { value path;
6160 mlsize_t len;
···7574 + len;
7675 break;
7776 }
7878-#endif
7977 case 1: /* ADDR_INET */
8078#ifdef HAS_IPV6
8179 if (caml_string_length(Field(mladr, 0)) == 16) {
···114112 socklen_param_type adr_len, int close_on_error)
115113{
116114 value res;
117117-#ifndef _WIN32
118115 if (adr_len < offsetof(struct sockaddr, sa_data)) {
119116 // Only possible for an unnamed AF_UNIX socket, in
120117 // which case sa_family might be uninitialized.
121118 return alloc_unix_sockaddr(caml_alloc_string(0));
122119 }
123123-#endif
124120125121 switch(adr->s_gen.sa_family) {
126126-#ifndef _WIN32
127122 case AF_UNIX:
128123 { /* Based on recommendation in section BUGS of Linux unix(7). See
129124 http://man7.org/linux/man-pages/man7/unix.7.html. */
···147142 );
148143 break;
149144 }
150150-#endif
151145 case AF_INET:
152146 { value a = alloc_inet_addr(&adr->s_inet.sin_addr);
153147 Begin_root (a);
···13991399(** The type of socket domains. Not all platforms support
14001400 IPv6 sockets (type [PF_INET6]).
1401140114021402- On Windows: [PF_UNIX] not implemented. *)
14021402+ On Windows: [PF_UNIX] supported since 4.14.0 on Windows 10 1803
14031403+ and later. *)
1403140414041405type socket_type =
14051406 SOCK_STREAM (** Stream socket *)
+2-1
otherlibs/unix/unixLabels.mli
···14031403(** The type of socket domains. Not all platforms support
14041404 IPv6 sockets (type [PF_INET6]).
1405140514061406- On Windows: [PF_UNIX] not implemented. *)
14061406+ On Windows: [PF_UNIX] supported since 4.14.0 on Windows 10 1803
14071407+ and later. *)
1407140814081409type socket_type = Unix.socket_type =
14091410 SOCK_STREAM (** Stream socket *)
···331331 else
332332 return unix_cloexec_default;
333333}
334334+335335+int win_set_inherit(HANDLE fd, BOOL inherit)
336336+{
337337+ /* According to the MSDN, SetHandleInformation may not work
338338+ for console handles on WinNT4 and earlier versions. */
339339+ if (! SetHandleInformation(fd,
340340+ HANDLE_FLAG_INHERIT,
341341+ inherit ? HANDLE_FLAG_INHERIT : 0)) {
342342+ win32_maperr(GetLastError());
343343+ return -1;
344344+ }
345345+ return 0;
346346+}
+4
otherlibs/win32unix/unixsupport.h
···74747575extern int unix_cloexec_default;
7676extern int unix_cloexec_p(value cloexec);
7777+extern int win_set_inherit(HANDLE fd, BOOL inherit);
7878+/* This is a best effort, not guaranteed to work, so don't fail on error */
7979+#define win_set_cloexec(fd, cloexec) \
8080+ win_set_inherit((fd), ! unix_cloexec_p((cloexec)))
77817882/* Information stored in flags_fd, describing more precisely the socket
7983 * and its status. The whole flags_fd is initialized to 0.
+9
runtime/caml/s.h.in
···78787979/* Define HAS_SOCKETS if you have BSD sockets. */
80808181+#undef HAS_SOCKETPAIR
8282+8383+/* Define HAS_SOCKETPAIR if you have the socketpair function. Only
8484+ relevant on Windows. */
8585+8186#undef HAS_SOCKLEN_T
82878388/* Define HAS_SOCKLEN_T if the type socklen_t is defined in
8489 /usr/include/sys/socket.h. */
9090+9191+#undef HAS_AFUNIX_H
9292+9393+/* Define HAS_AFUNIX_H if you have <afunix.h>. */
85948695#undef HAS_INET_ATON
8796
+12-8
runtime/debugger.c
···7070#define ATOM ATOM_WS
7171#include <winsock2.h>
7272#undef ATOM
7373+/* Code duplication with otherlibs/unix/socketaddr.h is inevitable
7474+ * because pulling winsock2.h creates many naming conflicts. */
7575+#ifdef HAS_AFUNIX_H
7676+#include <afunix.h>
7777+#else
7878+struct sockaddr_un {
7979+ ADDRESS_FAMILY sun_family;
8080+ char sun_path[108];
8181+};
8282+#endif /* HAS_AFUNIX_H */
7383#include <process.h>
7474-#endif
8484+#endif /* _WIN32 */
75857686#include "caml/fail.h"
7787#include "caml/fix_code.h"
···8595static int sock_domain; /* Socket domain for the debugger */
8696static union { /* Socket address for the debugger */
8797 struct sockaddr s_gen;
8888-#ifndef _WIN32
8998 struct sockaddr_un s_unix;
9090-#endif
9199 struct sockaddr_in s_inet;
92100} sock_addr;
93101static int sock_addr_len; /* Length of sock_addr */
···170178{
171179 char * address;
172180 char_os * a;
173173- size_t a_len;
174181 char * port, * p;
175182 struct hostent * host;
176183 value flags;
···207214 if (*p == ':') { *p = 0; port = p+1; break; }
208215 }
209216 if (port == NULL) {
210210-#ifndef _WIN32
217217+ size_t a_len;
211218 /* Unix domain */
212219 sock_domain = PF_UNIX;
213220 sock_addr.s_unix.sun_family = AF_UNIX;
···224231 sock_addr_len =
225232 ((char *)&(sock_addr.s_unix.sun_path) - (char *)&(sock_addr.s_unix))
226233 + a_len;
227227-#else
228228- caml_fatal_error("unix sockets not supported");
229229-#endif
230234 } else {
231235 /* Internet domain */
232236 sock_domain = PF_INET;
···1313 ^^^^^^^^^^^^^^^^^^^^^^
1414Error: Cannot safely evaluate the definition of the following cycle
1515 of recursively-defined modules: B -> E -> D -> C -> B.
1616- There are no safe modules in this cycle (see manual section 8.2).
1616+ There are no safe modules in this cycle (see manual section 10.2).
1717Line 2, characters 10-20:
18182 | and B:sig val x: int end = struct let x = E.y end
1919 ^^^^^^^^^^
···4242 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4343Error: Cannot safely evaluate the definition of the following cycle
4444 of recursively-defined modules: A -> B -> A.
4545- There are no safe modules in this cycle (see manual section 8.2).
4545+ There are no safe modules in this cycle (see manual section 10.2).
4646Line 2, characters 28-29:
47472 | module rec A: sig type t += A end = struct type t += A = B.A end
4848 ^
···70707 | end
7171Error: Cannot safely evaluate the definition of the following cycle
7272 of recursively-defined modules: A -> B -> A.
7373- There are no safe modules in this cycle (see manual section 8.2).
7373+ There are no safe modules in this cycle (see manual section 10.2).
7474Line 2, characters 2-41:
75752 | module F: functor(X:sig end) -> sig end
7676 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
···1001008 | end
101101Error: Cannot safely evaluate the definition of the following cycle
102102 of recursively-defined modules: A -> B -> A.
103103- There are no safe modules in this cycle (see manual section 8.2).
103103+ There are no safe modules in this cycle (see manual section 10.2).
104104Line 3, characters 4-17:
1051053 | module M: X.t
106106 ^^^^^^^^^^^^^
···11+#!/bin/sh
22+33+# Test if the OS runtime has afunix enabled.
44+55+if sc query afunix > /dev/null; then
66+ exit "${TEST_PASS}";
77+fi
88+exit "${TEST_SKIP}"
+32
testsuite/tests/lib-unix/win-socketpair/test.ml
···11+(* TEST
22+33+* libwin32unix
44+ script = "sh ${test_source_directory}/has-afunix.sh"
55+** hassysthreads
66+ include systhreads
77+*** script
88+**** bytecode
99+output = "${test_build_directory}/program-output"
1010+stdout = "${output}"
1111+**** native
1212+output = "${test_build_directory}/program-output"
1313+stdout = "${output}"
1414+1515+ *)
1616+1717+let peer id fd =
1818+ let msg = Bytes.of_string (Printf.sprintf "%d" id) in
1919+ ignore (Unix.write fd msg 0 (Bytes.length msg));
2020+ ignore (Unix.read fd msg 0 (Bytes.length msg));
2121+ let expected = Bytes.of_string (Printf.sprintf "%d" (if id = 0 then 1 else 0)) in
2222+ if msg = expected then
2323+ Printf.printf "Ok\n%!"
2424+ else
2525+ Printf.printf "%d: %s\n%!" id (Bytes.to_string msg);
2626+ flush_all ()
2727+2828+let () =
2929+ let fd0, fd1 = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in
3030+ let t0, t1 = Thread.create (peer 0) fd0, Thread.create (peer 1) fd1 in
3131+ Thread.join t0; Thread.join t1;
3232+ Unix.close fd0; Unix.close fd1
···628628 in M.z
629629;; (* fails because of aliasing... *)
630630[%%expect{|
631631+Lines 2-4, characters 2-10:
632632+2 | ..match x with Int ->
633633+3 | let module M = struct type b = a let z = (y : b) end
634634+4 | in M.z
635635+Warning 18 [not-principal]:
636636+ The return type of this pattern-matching is ambiguous.
637637+ Please add a type annotation, as the choice of `a' is not principal.
638638+val f : 'a t -> 'a -> 'a = <fun>
639639+|}, Principal{|
631640Line 3, characters 46-47:
6326413 | let module M = struct type b = a let z = (y : b) end
633642 ^
+1-2
testsuite/tests/typing-misc/constraints.ml
···77Line 1, characters 0-32:
881 | type 'a t = [`A of 'a t t] as 'a;; (* fails *)
99 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1010-Error: The definition of t contains a cycle:
1111- 'a t t as 'a
1010+Error: The type abbreviation t is cyclic
1211|}, Principal{|
1312Line 1, characters 0-32:
14131 | type 'a t = [`A of 'a t t] as 'a;; (* fails *)
-14
testsuite/tests/typing-objects/Exemples.ml
···589589 but an expression was expected of type
590590 #comparable as 'a = < cmp : 'a -> int; .. >
591591 Type int_comparable = < cmp : int_comparable -> int; x : int >
592592- is not compatible with type
593593- int_comparable3 =
594594- < cmp : int_comparable -> int; setx : int -> unit; x : int >
595595- The first object type has no method setx
596596-|}, Principal{|
597597-Line 1, characters 25-27:
598598-1 | (new sorted_list ())#add c3;;
599599- ^^
600600-Error: This expression has type
601601- int_comparable3 =
602602- < cmp : int_comparable -> int; setx : int -> unit; x : int >
603603- but an expression was expected of type
604604- #comparable as 'a = < cmp : 'a -> int; .. >
605605- Type int_comparable = < cmp : int_comparable -> int; x : int >
606592 is not compatible with type 'a = < cmp : 'a -> int; .. >
607593 The first object type has no method setx
608594|}];; (* Error; strange message with -principal *)
···28282 | | ((Val x, _) | (_, Val x)) when x < 0 -> ()
2929 ^^^^^^^^^^^^^^^^^^^^^^^^^
3030Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
3131-variable x may match different arguments. (See manual section 9.5)
3131+variable x may match different arguments. (See manual section 11.5)
3232val ambiguous_typical_example : expr * expr -> unit = <fun>
3333|}]
3434···95952 | | (`B (x, _, Some y) | `B (x, Some y, _)) when y -> ignore x
9696 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9797Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
9898-variable y may match different arguments. (See manual section 9.5)
9898+variable y may match different arguments. (See manual section 11.5)
9999val ambiguous__y : [> `B of 'a * bool option * bool option ] -> unit = <fun>
100100|}]
101101···1261262 | | (`B (x, _, Some y) | `B (x, Some y, _)) when x < y -> ()
127127 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
128128Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
129129-variable y may match different arguments. (See manual section 9.5)
129129+variable y may match different arguments. (See manual section 11.5)
130130val ambiguous__x_y : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
131131|}]
132132···1391392 | | (`B (x, z, Some y) | `B (x, Some y, z)) when x < y || Some x = z -> ()
140140 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
141141Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
142142-variables y,z may match different arguments. (See manual section 9.5)
142142+variables y,z may match different arguments. (See manual section 11.5)
143143val ambiguous__x_y_z : [> `B of 'a * 'a option * 'a option ] -> unit = <fun>
144144|}]
145145···1701702 | | `A (`B (Some x, _) | `B (_, Some x)) when x -> ()
171171 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
172172Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
173173-variable x may match different arguments. (See manual section 9.5)
173173+variable x may match different arguments. (See manual section 11.5)
174174val ambiguous__in_depth :
175175 [> `A of [> `B of bool option * bool option ] ] -> unit = <fun>
176176|}]
···2012012 | ....`A ((`B (Some x, _) | `B (_, Some x)),
2022023 | (`C (Some y, Some _, _) | `C (Some y, _, Some _))).................
203203Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
204204-variable x may match different arguments. (See manual section 9.5)
204204+variable x may match different arguments. (See manual section 11.5)
205205val ambiguous__first_orpat :
206206 [> `A of
207207 [> `B of 'a option * 'a option ] *
···2192192 | ....`A ((`B (Some x, Some _, _) | `B (Some x, _, Some _)),
2202203 | (`C (Some y, _) | `C (_, Some y))).................
221221Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
222222-variable y may match different arguments. (See manual section 9.5)
222222+variable y may match different arguments. (See manual section 11.5)
223223val ambiguous__second_orpat :
224224 [> `A of
225225 [> `B of 'a option * 'b option * 'c option ] *
···3123122 | ..X (Z x,Y (y,0))
3133133 | | X (Z y,Y (x,_))
314314Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
315315-variables x,y may match different arguments. (See manual section 9.5)
315315+variables x,y may match different arguments. (See manual section 11.5)
316316val ambiguous__amoi : amoi -> int = <fun>
317317|}]
318318···3323322 | ....(module M:S),_,(1,_)
3333333 | | _,(module M:S),(_,1)...................
334334Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
335335-variable M may match different arguments. (See manual section 9.5)
335335+variable M may match different arguments. (See manual section 11.5)
336336val ambiguous__module_variable :
337337 (module S) * (module S) * (int * int) -> bool -> int = <fun>
338338|}]
···3793792 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
380380 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
381381Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
382382-variables x,y may match different arguments. (See manual section 9.5)
382382+variables x,y may match different arguments. (See manual section 11.5)
383383val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
384384 <fun>
385385|}, Principal{|
···4084082 | | A (x as z,(0 as y))|A (0 as y as z,x)|B (x,(y as z)) when g x (y+z) -> 1
409409 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
410410Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
411411-variables x,y may match different arguments. (See manual section 9.5)
411411+variables x,y may match different arguments. (See manual section 11.5)
412412val ambiguous_xy_but_not_ambiguous_z : (int -> int -> bool) -> t2 -> int =
413413 <fun>
414414|}]
···4674673 | | ((Val y, _) | (_, Val y)) when y < 0 -> ()
468468 ^^^^^^^^^^^^^^^^^^^^^^^^^
469469Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
470470-variable y may match different arguments. (See manual section 9.5)
470470+variable y may match different arguments. (See manual section 11.5)
471471val guarded_ambiguity : expr * expr -> unit = <fun>
472472|}]
473473···4964964 | | ((Val x, _) | (_, Val x)) when pred x -> ()
497497 ^^^^^^^^^^^^^^^^^^^^^^^^^
498498Warning 57 [ambiguous-var-in-pattern-guard]: Ambiguous or-pattern variables under guard;
499499-variable x may match different arguments. (See manual section 9.5)
499499+variable x may match different arguments. (See manual section 11.5)
500500val cmp : (a -> bool) -> a alg -> a alg -> unit = <fun>
501501|}]
502502
+6-6
testsuite/tests/warnings/w52.ml
···1010 ^^^^^
1111Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
1212this constructor's arguments. They are only for information
1313-and may change in future versions. (See manual section 9.5)
1313+and may change in future versions. (See manual section 11.5)
1414|}];;
15151616let () = try () with Match_failure ("Any",_,_) -> ();;
···2020 ^^^^^^^^^^^
2121Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
2222this constructor's arguments. They are only for information
2323-and may change in future versions. (See manual section 9.5)
2323+and may change in future versions. (See manual section 11.5)
2424|}];;
25252626let () = try () with Match_failure (_,0,_) -> ();;
···3030 ^^^^^^^
3131Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
3232this constructor's arguments. They are only for information
3333-and may change in future versions. (See manual section 9.5)
3333+and may change in future versions. (See manual section 11.5)
3434|}];;
35353636type t =
···5555 ^^^^^^^^^^
5656Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
5757this constructor's arguments. They are only for information
5858-and may change in future versions. (See manual section 9.5)
5858+and may change in future versions. (See manual section 11.5)
5959val f : t -> unit = <fun>
6060|}];;
6161···6868 ^^
6969Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
7070this constructor's arguments. They are only for information
7171-and may change in future versions. (See manual section 9.5)
7171+and may change in future versions. (See manual section 11.5)
7272val g : t -> unit = <fun>
7373|}];;
7474···9595 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
9696Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of
9797this constructor's arguments. They are only for information
9898-and may change in future versions. (See manual section 9.5)
9898+and may change in future versions. (See manual section 11.5)
9999val j : t -> unit = <fun>
100100|}];;
+3-2
toplevel/byte/topmain.ml
···3939 if Obj.is_block clos
4040 && (Obj.tag clos = Obj.closure_tag || Obj.tag clos = Obj.infix_tag)
4141 && (match
4242- Ctype.(repr (expand_head !Topcommon.toplevel_env desc.val_type))
4343- with {desc=Tarrow _} -> true | _ -> false)
4242+ Types.get_desc
4343+ (Ctype.expand_head !Topcommon.toplevel_env desc.val_type)
4444+ with Tarrow _ -> true | _ -> false)
4445 then begin
4546 match is_traced clos with
4647 | Some opath ->
+2-2
toplevel/byte/trace.ml
···6666(* If a function returns a functional value, wrap it into a trace code *)
67676868let rec instrument_result env name ppf clos_typ =
6969- match (Ctype.repr(Ctype.expand_head env clos_typ)).desc with
6969+ match get_desc (Ctype.expand_head env clos_typ) with
7070 | Tarrow(l, t1, t2, _) ->
7171 let starred_name =
7272 match name with
···109109let _ = Dummy
110110111111let instrument_closure env name ppf clos_typ =
112112- match (Ctype.repr(Ctype.expand_head env clos_typ)).desc with
112112+ match get_desc (Ctype.expand_head env clos_typ) with
113113 | Tarrow(l, t1, t2, _) ->
114114 let trace_res = instrument_result env name ppf t2 in
115115 (fun actual_code closure arg ->
+7-7
toplevel/genprintval.ml
···203203 Oide_ident name
204204 | Pdot(p, _s) ->
205205 if
206206- match (find (Lident (Out_name.print name)) env).desc with
206206+ match get_desc (find (Lident (Out_name.print name)) env) with
207207 | Tconstr(ty_path', _, _) -> Path.same ty_path ty_path'
208208 | _ -> false
209209 | exception Not_found -> false
···215215 let tree_of_constr =
216216 tree_of_qualified
217217 (fun lid env ->
218218- (Env.find_constructor_by_name lid env).cstr_res)
218218+ (Env.find_constructor_by_name lid env).cstr_res)
219219220220 and tree_of_label =
221221 tree_of_qualified
222222 (fun lid env ->
223223- (Env.find_label_by_name lid env).lbl_res)
223223+ (Env.find_label_by_name lid env).lbl_res)
224224225225 (* An abstract type *)
226226···260260 try
261261 find_printer depth env ty obj
262262 with Not_found ->
263263- match (Ctype.repr ty).desc with
263263+ match get_desc ty with
264264 | Tvar _ | Tunivar _ ->
265265 Oval_stuff "<poly>"
266266 | Tarrow _ ->
···397397 let type_params =
398398 match cd_res with
399399 Some t ->
400400- begin match (Ctype.repr t).desc with
400400+ begin match get_desc t with
401401 Tconstr (_,params,_) ->
402402 params
403403 | _ -> assert false end
···559559 if not (EVP.same_value slot (EVP.eval_address addr))
560560 then raise Not_found;
561561 let type_params =
562562- match (Ctype.repr cstr.cstr_res).desc with
562562+ match get_desc cstr.cstr_res with
563563 Tconstr (_,params,_) ->
564564 params
565565 | _ -> assert false
···592592 then printer
593593 else find remainder
594594 | (_name, Generic (path, fn)) :: remainder ->
595595- begin match (Ctype.expand_head env ty).desc with
595595+ begin match get_desc (Ctype.expand_head env ty) with
596596 | Tconstr (p, args, _) when Path.same p path ->
597597 begin try apply_generic_printer path (fn depth) args
598598 with exn -> (fun _obj -> out_exn path exn) end
+6-5
toplevel/topdirs.ml
···175175176176let filter_arrow ty =
177177 let ty = Ctype.expand_head !toplevel_env ty in
178178- match ty.desc with
178178+ match get_desc ty with
179179 | Tarrow (lbl, l, r, _) when not (Btype.is_optional lbl) -> Some (l, r)
180180 | _ -> None
181181···189189let extract_target_type ty = fst (extract_last_arrow ty)
190190let extract_target_parameters ty =
191191 let ty = extract_target_type ty |> Ctype.expand_head !toplevel_env in
192192- match ty.desc with
192192+ match get_desc ty with
193193 | Tconstr (path, (_ :: _ as args), _)
194194- when Ctype.all_distinct_vars !toplevel_env args -> Some (path, args)
194194+ when Ctype.all_distinct_vars !toplevel_env args ->
195195+ Some (path, args)
195196 | _ -> None
196197197198type 'a printer_type_new = Format.formatter -> 'a -> unit
···454455 if is_exception_constructor env desc.cstr_res then
455456 raise Not_found;
456457 let path =
457457- match Ctype.repr desc.cstr_res with
458458- | {desc=Tconstr(path, _, _)} -> path
458458+ match get_desc desc.cstr_res with
459459+ | Tconstr(path, _, _) -> path
459460 | _ -> raise Not_found
460461 in
461462 let type_decl = Env.find_type path env in
+103-230
typing/btype.ml
···22222323(**** Sets, maps and hashtables of types ****)
24242525-module TypeSet = Set.Make(TypeOps)
2626-module TypeMap = Map.Make (TypeOps)
2727-module TypeHash = Hashtbl.Make(TypeOps)
2525+let wrap_repr f ty = f (Transient_expr.repr ty)
2626+let wrap_type_expr f tty = f (Transient_expr.type_expr tty)
2727+2828+module TransientTypeSet = Set.Make(TransientTypeOps)
2929+module TypeSet = struct
3030+ include TransientTypeSet
3131+ let add = wrap_repr add
3232+ let mem = wrap_repr mem
3333+ let singleton = wrap_repr singleton
3434+ let exists p = TransientTypeSet.exists (wrap_type_expr p)
3535+ let elements set =
3636+ List.map Transient_expr.type_expr (TransientTypeSet.elements set)
3737+end
3838+module TransientTypeMap = Map.Make(TransientTypeOps)
3939+module TypeMap = struct
4040+ include TransientTypeMap
4141+ let add ty = wrap_repr add ty
4242+ let find ty = wrap_repr find ty
4343+ let singleton ty = wrap_repr singleton ty
4444+ let fold f = TransientTypeMap.fold (wrap_type_expr f)
4545+end
4646+module TransientTypeHash = Hashtbl.Make(TransientTypeOps)
4747+module TypeHash = struct
4848+ include TransientTypeHash
4949+ let add hash = wrap_repr (add hash)
5050+ let find hash = wrap_repr (find hash)
5151+ let iter f = TransientTypeHash.iter (wrap_type_expr f)
5252+end
5353+module TransientTypePairs =
5454+ Hashtbl.Make (struct
5555+ type t = transient_expr * transient_expr
5656+ let equal (t1, t1') (t2, t2') = (t1 == t2) && (t1' == t2')
5757+ let hash (t, t') = t.id + 93 * t'.id
5858+ end)
5959+module TypePairs = struct
6060+ include TransientTypePairs
6161+ open Transient_expr
6262+ let wrap_repr f (t1, t2) = f (repr t1, repr t2)
6363+ let wrap_type_expr f (tt1, tt2) = f (type_expr tt1, type_expr tt2)
6464+ let add hash = wrap_repr (add hash)
6565+ let find hash = wrap_repr (find hash)
6666+ let mem hash = wrap_repr (mem hash)
6767+ let iter f = TransientTypePairs.iter (wrap_type_expr f)
6868+end
28692970(**** Forward declarations ****)
3071···42834384(**** Some type creators ****)
44854545-let new_id = s_ref (-1)
8686+let newgenty desc = newty2 ~level:generic_level desc
8787+let newgenvar ?name () = newgenty (Tvar name)
8888+let newgenstub ~scope = newty3 ~level:generic_level ~scope (Tvar None)
46894747-let newty2 level desc =
4848- incr new_id;
4949- Private_type_expr.create desc ~level ~scope:lowest_level ~id:!new_id
5050-let newgenty desc = newty2 generic_level desc
5151-let newgenvar ?name () = newgenty (Tvar name)
5290(*
5391let newmarkedvar level =
5492 incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
···59976098(**** Check some types ****)
61996262-let is_Tvar = function {desc=Tvar _} -> true | _ -> false
6363-let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
6464-let is_Tconstr = function {desc=Tconstr _} -> true | _ -> false
100100+let is_Tvar ty = match get_desc ty with Tvar _ -> true | _ -> false
101101+let is_Tunivar ty = match get_desc ty with Tunivar _ -> true | _ -> false
102102+let is_Tconstr ty = match get_desc ty with Tconstr _ -> true | _ -> false
6510366104let dummy_method = "*dummy method*"
671056868-(**** Definitions for backtracking ****)
6969-7070-type change =
7171- Ctype of type_expr * type_desc
7272- | Ccompress of type_expr * type_desc * type_desc
7373- | Clevel of type_expr * int
7474- | Cscope of type_expr * int
7575- | Cname of
7676- (Path.t * type_expr list) option ref * (Path.t * type_expr list) option
7777- | Crow of row_field option ref * row_field option
7878- | Ckind of field_kind option ref * field_kind option
7979- | Ccommu of commutable ref * commutable
8080- | Cuniv of type_expr option ref * type_expr option
8181-8282-type changes =
8383- Change of change * changes ref
8484- | Unchanged
8585- | Invalid
8686-8787-let trail = s_table ref Unchanged
8888-8989-let log_change ch =
9090- let r' = ref Unchanged in
9191- !trail := Change (ch, r');
9292- trail := r'
9393-94106(**** Representative of a type ****)
951079696-let rec field_kind_repr =
9797- function
9898- Fvar {contents = Some kind} -> field_kind_repr kind
9999- | kind -> kind
100100-101101-let rec repr_link compress (t : type_expr) d : type_expr -> type_expr =
102102- function
103103- {desc = Tlink t' as d'} ->
104104- repr_link true t d' t'
105105- | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent ->
106106- repr_link true t d' t'
107107- | t' ->
108108- if compress then begin
109109- log_change (Ccompress (t, t.desc, d)); Private_type_expr.set_desc t d
110110- end;
111111- t'
112112-113113-let repr (t : type_expr) =
114114- match t.desc with
115115- Tlink t' as d ->
116116- repr_link false t d t'
117117- | Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent ->
118118- repr_link false t d t'
119119- | _ -> t
120120-121108let rec commu_repr = function
122109 Clink r when !r <> Cunknown -> commu_repr !r
123110 | c -> c
···139126 | l'::ll -> rev_concat (l'@l) ll
140127141128let rec row_repr_aux ll row =
142142- match (repr row.row_more).desc with
129129+ match get_desc row.row_more with
143130 | Tvariant row' ->
144131 let f = row.row_fields in
145132 row_repr_aux (if f = [] then ll else f::ll) row'
···154141 | (tag',f) :: fields ->
155142 if tag = tag' then row_field_repr f else find fields
156143 | [] ->
157157- match repr row.row_more with
158158- | {desc=Tvariant row'} -> row_field tag row'
144144+ match get_desc row.row_more with
145145+ | Tvariant row' -> row_field tag row'
159146 | _ -> Rabsent
160147 in find row.row_fields
161148162149let rec row_more row =
163163- match repr row.row_more with
164164- | {desc=Tvariant row'} -> row_more row'
165165- | ty -> ty
150150+ match get_desc row.row_more with
151151+ | Tvariant row' -> row_more row'
152152+ | _ -> row.row_more
166153167154let merge_fixed_explanation fixed1 fixed2 =
168155 match fixed1, fixed2 with
···178165 match row.row_fixed with
179166 | Some _ as x -> x
180167 | None ->
181181- let more = repr row.row_more in
182182- match more.desc with
168168+ match get_desc row.row_more with
183169 | Tvar _ | Tnil -> None
184184- | Tunivar _ -> Some (Univar more)
170170+ | Tunivar _ -> Some (Univar row.row_more)
185171 | Tconstr (p,_,_) -> Some (Reified p)
186172 | _ -> assert false
187173···210196 if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
211197212198let proxy ty =
213213- let ty0 = repr ty in
214214- match ty0.desc with
199199+ match get_desc ty with
215200 | Tvariant row when not (static_row row) ->
216201 row_more row
217202 | Tobject (ty, _) ->
218203 let rec proxy_obj ty =
219219- match ty.desc with
220220- Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
204204+ match get_desc ty with
205205+ Tfield (_, _, _, ty) -> proxy_obj ty
221206 | Tvar _ | Tunivar _ | Tconstr _ -> ty
222222- | Tnil -> ty0
207207+ | Tnil -> ty
223208 | _ -> assert false
224209 in proxy_obj ty
225225- | _ -> ty0
210210+ | _ -> ty
226211227212(**** Utilities for fixed row private types ****)
228213229214let row_of_type t =
230230- match (repr t).desc with
215215+ match get_desc t with
231216 Tobject(t,_) ->
232217 let rec get_row t =
233233- let t = repr t in
234234- match t.desc with
218218+ match get_desc t with
235219 Tfield(_,_,_,t) -> get_row t
236220 | _ -> t
237221 in get_row t
···248232 if l < 4 then false else String.sub s (l-4) 4 = "#row"
249233250234let is_constr_row ~allow_ident t =
251251- match t.desc with
235235+ match get_desc t with
252236 Tconstr (Path.Pident id, _, _) when allow_ident ->
253237 is_row_name (Ident.name id)
254238 | Tconstr (Path.Pdot (_, s), _, _) -> is_row_name s
···260244 match decl.type_manifest with
261245 None -> ()
262246 | Some ty ->
263263- let ty = repr ty in
264264- match ty.desc with
247247+ match get_desc ty with
265248 Tvariant row when static_row row ->
266249 let row = {(row_repr row) with
267250 row_name = Some (path, decl.type_params)} in
268268- Private_type_expr.set_desc ty (Tvariant row)
251251+ set_type_desc ty (Tvariant row)
269252 | _ -> ()
270253271254···284267 init
285268 row.row_fields
286269 in
287287- match (repr row.row_more).desc with
270270+ match get_desc row.row_more with
288271 Tvariant row -> fold_row f result row
289272 | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil ->
290273 begin match
···298281let iter_row f row =
299282 fold_row (fun () v -> f v) () row
300283301301-let rec fold_type_expr f init ty =
302302- match ty.desc with
284284+let fold_type_expr f init ty =
285285+ match get_desc ty with
303286 Tvar _ -> init
304287 | Tarrow (_, ty1, ty2, _) ->
305305- let result = f init ty1 in
306306- f result ty2
288288+ let result = f init ty1 in
289289+ f result ty2
307290 | Ttuple l -> List.fold_left f init l
308291 | Tconstr (_, l, _) -> List.fold_left f init l
309309- | Tobject(ty, {contents = Some (_, p)})
310310- ->
311311- let result = f init ty in
312312- List.fold_left f result p
292292+ | Tobject(ty, {contents = Some (_, p)}) ->
293293+ let result = f init ty in
294294+ List.fold_left f result p
313295 | Tobject (ty, _) -> f init ty
314296 | Tvariant row ->
315315- let result = fold_row f init row in
316316- f result (row_more row)
297297+ let result = fold_row f init row in
298298+ f result (row_more row)
317299 | Tfield (_, _, ty1, ty2) ->
318318- let result = f init ty1 in
319319- f result ty2
300300+ let result = f init ty1 in
301301+ f result ty2
320302 | Tnil -> init
321321- | Tlink ty -> fold_type_expr f init ty
303303+ | Tlink _
322304 | Tsubst _ -> assert false
323305 | Tunivar _ -> init
324306 | Tpoly (ty, tyl) ->
···440422 iter_type_expr_kind (it.it_type_expr it) kind
441423 and it_do_type_expr it ty =
442424 iter_type_expr (it.it_type_expr it) ty;
443443- match ty.desc with
425425+ match get_desc ty with
444426 Tconstr (p, _, _)
445427 | Tobject (_, {contents=Some (p, _)})
446428 | Tpackage (p, _) ->
···498480 | Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *)
499481 Tfield (p, field_kind_repr k, f ty1, f ty2)
500482 | Tnil -> Tnil
501501- | Tlink ty -> copy_type_desc f ty.desc
483483+ | Tlink ty -> copy_type_desc f (get_desc ty)
502484 | Tsubst _ -> assert false
503485 | Tunivar _ as ty -> ty (* always keep the name *)
504486 | Tpoly (ty, tyl) ->
···511493module For_copy : sig
512494 type copy_scope
513495514514- val save_desc: copy_scope -> type_expr -> type_desc -> unit
496496+ val redirect_desc: copy_scope -> type_expr -> type_desc -> unit
515497516498 val dup_kind: copy_scope -> field_kind option ref -> unit
517499518500 val with_scope: (copy_scope -> 'a) -> 'a
519501end = struct
520502 type copy_scope = {
521521- mutable saved_desc : (type_expr * type_desc) list;
503503+ mutable saved_desc : (transient_expr * type_desc) list;
522504 (* Save association of generic nodes with their description. *)
523505524506 mutable saved_kinds: field_kind option ref list;
···528510 (* new kind variables *)
529511 }
530512531531- let save_desc copy_scope ty desc =
532532- copy_scope.saved_desc <- (ty, desc) :: copy_scope.saved_desc
513513+ let redirect_desc copy_scope ty desc =
514514+ let ty = Transient_expr.repr ty in
515515+ copy_scope.saved_desc <- (ty, ty.desc) :: copy_scope.saved_desc;
516516+ Transient_expr.set_desc ty desc
533517534518 let dup_kind copy_scope r =
535519 assert (Option.is_none !r);
···542526543527 (* Restore type descriptions. *)
544528 let cleanup { saved_desc; saved_kinds; _ } =
545545- List.iter (fun (ty, desc) -> Private_type_expr.set_desc ty desc) saved_desc;
529529+ List.iter (fun (ty, desc) -> Transient_expr.set_desc ty desc) saved_desc;
546530 List.iter (fun r -> r := None) saved_kinds
547531548532 let with_scope f =
···551535 cleanup scope;
552536 res
553537end
554554-555538556539 (*******************************************)
557540 (* Memorization of abbreviation expansion *)
···625608 List.for_all (fun mem -> check_abbrev_rec !mem) !memo
626609*)
627610611611+(* Re-export backtrack *)
612612+613613+let snapshot = snapshot
614614+let backtrack = backtrack ~cleanup_abbrev
615615+628616 (**********************************)
629617 (* Utilities for labels *)
630618 (**********************************)
···651639652640let extract_label l ls = extract_label_aux [] l ls
653641654654-655642 (**********************************)
656656- (* Utilities for backtracking *)
643643+ (* Utilities for level-marking *)
657644 (**********************************)
658645659659-let undo_change = function
660660- Ctype (ty, desc) -> Private_type_expr.set_desc ty desc
661661- | Ccompress (ty, desc, _) -> Private_type_expr.set_desc ty desc
662662- | Clevel (ty, level) -> Private_type_expr.set_level ty level
663663- | Cscope (ty, scope) -> Private_type_expr.set_scope ty scope
664664- | Cname (r, v) -> r := v
665665- | Crow (r, v) -> r := v
666666- | Ckind (r, v) -> r := v
667667- | Ccommu (r, v) -> r := v
668668- | Cuniv (r, v) -> r := v
669669-670670-type snapshot = changes ref * int
671671-let last_snapshot = s_ref 0
672672-673673-let log_type ty =
674674- if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
675675-let link_type ty ty' =
676676- log_type ty;
677677- let desc = ty.desc in
678678- Private_type_expr.set_desc ty (Tlink ty');
679679- (* Name is a user-supplied name for this unification variable (obtained
680680- * through a type annotation for instance). *)
681681- match desc, ty'.desc with
682682- Tvar name, Tvar name' ->
683683- begin match name, name' with
684684- | Some _, None -> log_type ty'; Private_type_expr.set_desc ty' (Tvar name)
685685- | None, Some _ -> ()
686686- | Some _, Some _ ->
687687- if ty.level < ty'.level then
688688- (log_type ty'; Private_type_expr.set_desc ty' (Tvar name))
689689- | None, None -> ()
690690- end
691691- | _ -> ()
692692- (* ; assert (check_memorized_abbrevs ()) *)
693693- (* ; check_expans [] ty' *)
694694-(* TODO: consider eliminating set_type_desc, replacing it with link types *)
695695-let set_type_desc ty td =
696696- if td != ty.desc then begin
697697- log_type ty;
698698- Private_type_expr.set_desc ty td
699699- end
700700-(* TODO: separate set_level into two specific functions: *)
701701-(* set_lower_level and set_generic_level *)
702702- let set_level ty level =
703703- if level <> ty.level then begin
704704- if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
705705- Private_type_expr.set_level ty level
706706- end
707707-(* TODO: introduce a guard and rename it to set_higher_scope? *)
708708-let set_scope ty scope =
709709- if scope <> ty.scope then begin
710710- if ty.id <= !last_snapshot then log_change (Cscope (ty, ty.scope));
711711- Private_type_expr.set_scope ty scope
712712- end
713713-let set_univar rty ty =
714714- log_change (Cuniv (rty, !rty)); rty := Some ty
715715-let set_name nm v =
716716- log_change (Cname (nm, !nm)); nm := v
717717-let set_row_field e v =
718718- log_change (Crow (e, !e)); e := Some v
719719-let set_kind rk k =
720720- log_change (Ckind (rk, !rk)); rk := Some k
721721-let set_commu rc c =
722722- log_change (Ccommu (rc, !rc)); rc := c
723723-724724-let snapshot () =
725725- let old = !last_snapshot in
726726- last_snapshot := !new_id;
727727- (!trail, old)
728728-729729-let rec rev_log accu = function
730730- Unchanged -> accu
731731- | Invalid -> assert false
732732- | Change (ch, next) ->
733733- let d = !next in
734734- next := Invalid;
735735- rev_log (ch::accu) d
736736-737737-let backtrack (changes, old) =
738738- match !changes with
739739- Unchanged -> last_snapshot := old
740740- | Invalid -> failwith "Btype.backtrack"
741741- | Change _ as change ->
742742- cleanup_abbrev ();
743743- let backlog = rev_log [] change in
744744- List.iter undo_change backlog;
745745- changes := Unchanged;
746746- last_snapshot := old;
747747- trail := changes
748748-749749-let rec rev_compress_log log r =
750750- match !r with
751751- Unchanged | Invalid ->
752752- log
753753- | Change (Ccompress _, next) ->
754754- rev_compress_log (r::log) next
755755- | Change (_, next) ->
756756- rev_compress_log log next
757757-758758-let undo_compress (changes, _old) =
759759- match !changes with
760760- Unchanged
761761- | Invalid -> ()
762762- | Change _ ->
763763- let log = rev_compress_log [] changes in
764764- List.iter
765765- (fun r -> match !r with
766766- Change (Ccompress (ty, desc, d), next) when ty.desc == d ->
767767- Private_type_expr.set_desc ty desc; r := !next
768768- | _ -> ())
769769- log
770770-771771-(* Mark a type. *)
772772-773773-let not_marked_node ty = ty.level >= lowest_level
646646+let not_marked_node ty = get_level ty >= lowest_level
774647 (* type nodes with negative levels are "marked" *)
775648776776-let flip_mark_node ty = Private_type_expr.set_level ty (pivot_level - ty.level)
777777-let logged_mark_node ty = set_level ty (pivot_level - ty.level)
649649+let flip_mark_node ty =
650650+ let ty = Transient_expr.repr ty in
651651+ Transient_expr.set_level ty (pivot_level - ty.level)
652652+let logged_mark_node ty =
653653+ set_level ty (pivot_level - get_level ty)
778654779655let try_mark_node ty = not_marked_node ty && (flip_mark_node ty; true)
780656let try_logged_mark_node ty = not_marked_node ty && (logged_mark_node ty; true)
781657782658let rec mark_type ty =
783783- let ty = repr ty in
784659 if not_marked_node ty then begin
785660 flip_mark_node ty;
786661 iter_type_expr mark_type ty
···791666792667let type_iterators =
793668 let it_type_expr it ty =
794794- let ty = repr ty in
795669 if try_mark_node ty then it.it_do_type_expr it ty
796670 in
797671 {type_iterators with it_type_expr}
···799673800674(* Remove marks from a type. *)
801675let rec unmark_type ty =
802802- let ty = repr ty in
803803- if ty.level < lowest_level then begin
676676+ if get_level ty < lowest_level then begin
804677 (* flip back the marked level *)
805678 flip_mark_node ty;
806679 iter_type_expr unmark_type ty
+50-53
typing/btype.mli
···20202121(**** Sets, maps and hashtables of types ****)
22222323-module TypeSet : Set.S with type elt = type_expr
2424-module TypeMap : Map.S with type key = type_expr
2525-module TypeHash : Hashtbl.S with type key = type_expr
2323+module TypeSet : sig
2424+ include Set.S with type elt = transient_expr
2525+ val add: type_expr -> t -> t
2626+ val mem: type_expr -> t -> bool
2727+ val singleton: type_expr -> t
2828+ val exists: (type_expr -> bool) -> t -> bool
2929+ val elements: t -> type_expr list
3030+end
3131+module TransientTypeMap : Map.S with type key = transient_expr
3232+module TypeMap : sig
3333+ include Map.S with type key = transient_expr
3434+ and type 'a t = 'a TransientTypeMap.t
3535+ val add: type_expr -> 'a -> 'a t -> 'a t
3636+ val find: type_expr -> 'a t -> 'a
3737+ val singleton: type_expr -> 'a -> 'a t
3838+ val fold: (type_expr -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
3939+end
4040+module TypeHash : sig
4141+ include Hashtbl.S with type key = transient_expr
4242+ val add: 'a t -> type_expr -> 'a -> unit
4343+ val find: 'a t -> type_expr -> 'a
4444+ val iter: (type_expr -> 'a -> unit) -> 'a t -> unit
4545+end
4646+module TypePairs : sig
4747+ include Hashtbl.S with type key = transient_expr * transient_expr
4848+ val add: 'a t -> type_expr * type_expr -> 'a -> unit
4949+ val find: 'a t -> type_expr * type_expr -> 'a
5050+ val mem: 'a t -> type_expr * type_expr -> bool
5151+ val iter: (type_expr * type_expr -> 'a -> unit) -> 'a t -> unit
5252+end
26532754(**** Levels ****)
28552956val generic_level: int
30573131-val newty2: int -> type_desc -> type_expr
3232- (* Create a type *)
3358val newgenty: type_desc -> type_expr
3459 (* Create a generic type *)
3560val newgenvar: ?name:string -> unit -> type_expr
3661 (* Return a fresh generic variable *)
6262+val newgenstub: scope:int -> type_expr
6363+ (* Return a fresh generic node, to be instantiated
6464+ by [Transient_expr.set_stub_desc] *)
37653866(* Use Tsubst instead
3967val newmarkedvar: int -> type_expr
···4876val is_Tunivar: type_expr -> bool
4977val is_Tconstr: type_expr -> bool
5078val dummy_method: label
5151-5252-val repr: type_expr -> type_expr
5353- (* Return the canonical representative of a type. *)
5454-5555-val field_kind_repr: field_kind -> field_kind
5656- (* Return the canonical representative of an object field
5757- kind. *)
58795980val commu_repr: commutable -> commutable
6081 (* Return the canonical representative of a commutation lock *)
···113134val fold_row: ('a -> type_expr -> 'a) -> 'a -> row_desc -> 'a
114135val iter_abbrev: (type_expr -> unit) -> abbrev_memo -> unit
115136 (* Iteration on types in an abbreviation list *)
137137+val iter_type_expr_kind: (type_expr -> unit) -> (type_decl_kind -> unit)
138138+139139+val iter_type_expr_cstr_args: (type_expr -> unit) ->
140140+ (constructor_arguments -> unit)
141141+val map_type_expr_cstr_args: (type_expr -> type_expr) ->
142142+ (constructor_arguments -> constructor_arguments)
143143+116144117145type type_iterators =
118146 { it_signature: type_iterators -> signature -> unit;
···154182 While it is possible to circumvent that discipline in various
155183 ways, you should NOT do that. *)
156184157157- val save_desc: copy_scope -> type_expr -> type_desc -> unit
158158- (* Save a type description *)
185185+ val redirect_desc: copy_scope -> type_expr -> type_desc -> unit
186186+ (* Temporarily change a type description *)
159187160188 val dup_kind: copy_scope -> field_kind option ref -> unit
161189 (* Save a None field_kind, and make it point to a fresh Fvar *)
···217245 abbrev_memo ref -> Path.t -> unit
218246 (* Remove an abbreviation from the cache *)
219247248248+(**** Backtracking ****)
249249+250250+val snapshot: unit -> snapshot
251251+val backtrack: snapshot -> unit
252252+ (* Backtrack to a given snapshot. Only possible if you have
253253+ not already backtracked to a previous snapshot.
254254+ Calls [cleanup_abbrev] internally *)
255255+220256(**** Utilities for labels ****)
221257222258val is_optional : arg_label -> bool
···233269 whether (label, value) was at the head of the list,
234270 list without the extracted (label, value) *)
235271236236-(**** Utilities for backtracking ****)
237237-238238-type snapshot
239239- (* A snapshot for backtracking *)
240240-val snapshot: unit -> snapshot
241241- (* Make a snapshot for later backtracking. Costs nothing *)
242242-val backtrack: snapshot -> unit
243243- (* Backtrack to a given snapshot. Only possible if you have
244244- not already backtracked to a previous snapshot.
245245- Calls [cleanup_abbrev] internally *)
246246-val undo_compress: snapshot -> unit
247247- (* Backtrack only path compression. Only meaningful if you have
248248- not already backtracked to a previous snapshot.
249249- Does not call [cleanup_abbrev] *)
250250-251251-(* Functions to use when modifying a type (only Ctype?) *)
252252-val link_type: type_expr -> type_expr -> unit
253253- (* Set the desc field of [t1] to [Tlink t2], logging the old
254254- value if there is an active snapshot *)
255255-val set_type_desc: type_expr -> type_desc -> unit
256256- (* Set directly the desc field, without sharing *)
257257-val set_level: type_expr -> int -> unit
258258-val set_scope: type_expr -> int -> unit
259259-val set_name:
260260- (Path.t * type_expr list) option ref ->
261261- (Path.t * type_expr list) option -> unit
262262-val set_row_field: row_field option ref -> row_field -> unit
263263-val set_univar: type_expr option ref -> type_expr -> unit
264264-val set_kind: field_kind option ref -> field_kind -> unit
265265-val set_commu: commutable ref -> commutable -> unit
266266- (* Set references, logging the old value *)
267267-268272(**** Forward declarations ****)
269273val print_raw: (Format.formatter -> type_expr -> unit) ref
270270-271271-val iter_type_expr_kind: (type_expr -> unit) -> (type_decl_kind -> unit)
272272-273273-val iter_type_expr_cstr_args: (type_expr -> unit) ->
274274- (constructor_arguments -> unit)
275275-val map_type_expr_cstr_args: (type_expr -> type_expr) ->
276276- (constructor_arguments -> constructor_arguments)
+473-523
typing/ctype.ml
···231231232232(* Re-export generic type creators *)
233233234234-let newty2 = Btype.newty2
235235-let newty desc = newty2 !current_level desc
234234+let newty desc = newty2 ~level:!current_level desc
236235237237-let newvar ?name () = newty2 !current_level (Tvar name)
238238-let newvar2 ?name level = newty2 level (Tvar name)
239239-let new_global_var ?name () = newty2 !global_level (Tvar name)
236236+let newvar ?name () = newty2 ~level:!current_level (Tvar name)
237237+let newvar2 ?name level = newty2 ~level:level (Tvar name)
238238+let new_global_var ?name () = newty2 ~level:!global_level (Tvar name)
239239+let newstub ~scope = newty3 ~level:!current_level ~scope (Tvar None)
240240241241let newobj fields = newty (Tobject (fields, ref None))
242242243243let newconstr path tyl = newty (Tconstr (path, tyl, ref Mnil))
244244245245let none = newty (Ttuple []) (* Clearly ill-formed type *)
246246-247247-(**** Representative of a type ****)
248248-249249-(* Re-export repr *)
250250-let repr = repr
251251-252252-(**** Type maps ****)
253253-254254-module TypePairs =
255255- Hashtbl.Make (struct
256256- type t = type_expr * type_expr
257257- let equal (t1, t1') (t2, t2') = (t1 == t2) && (t1' == t2')
258258- let hash (t, t') = t.id + 93 * t'.id
259259- end)
260260-261246262247(**** unification mode ****)
263248···317302(**** Object field manipulation. ****)
318303319304let object_fields ty =
320320- match (repr ty).desc with
305305+ match get_desc ty with
321306 Tobject (fields, _) -> fields
322307 | _ -> assert false
323308324309let flatten_fields ty =
325310 let rec flatten l ty =
326326- let ty = repr ty in
327327- match ty.desc with
311311+ match get_desc ty with
328312 Tfield(s, k, ty1, ty2) ->
329313 flatten ((s, k, ty1)::l) ty2
330314 | _ ->
···335319336320let build_fields level =
337321 List.fold_right
338338- (fun (s, k, ty1) ty2 -> newty2 level (Tfield(s, k, ty1, ty2)))
322322+ (fun (s, k, ty1) ty2 -> newty2 ~level (Tfield(s, k, ty1, ty2)))
339323340324let associate_fields fields1 fields2 =
341325 let rec associate p s s' =
···354338 associate [] [] [] (fields1, fields2)
355339356340let rec has_dummy_method ty =
357357- match repr ty with
358358- {desc = Tfield (m, _, _, ty2)} ->
341341+ match get_desc ty with
342342+ Tfield (m, _, _, ty2) ->
359343 m = dummy_method || has_dummy_method ty2
360344 | _ -> false
361345···367351368352(* +++ The abbreviation should eventually be expanded *)
369353let rec object_row ty =
370370- let ty = repr ty in
371371- match ty.desc with
354354+ match get_desc ty with
372355 Tobject (t, _) -> object_row t
373356 | Tfield(_, _, _, t) -> object_row t
374357 | _ -> ty
375358376359let opened_object ty =
377377- match (object_row ty).desc with
360360+ match get_desc (object_row ty) with
378361 | Tvar _ | Tunivar _ | Tconstr _ -> true
379362 | _ -> false
380363381364let concrete_object ty =
382382- match (object_row ty).desc with
365365+ match get_desc (object_row ty) with
383366 | Tvar _ -> false
384367 | _ -> true
385368···387370388371let close_object ty =
389372 let rec close ty =
390390- let ty = repr ty in
391391- match ty.desc with
373373+ match get_desc ty with
392374 Tvar _ ->
393393- link_type ty (newty2 ty.level Tnil); true
375375+ link_type ty (newty2 ~level:(get_level ty) Tnil); true
394376 | Tfield(lab, _, _, _) when lab = dummy_method ->
395377 false
396378 | Tfield(_, _, _, ty') -> close ty'
397379 | _ -> assert false
398380 in
399399- match (repr ty).desc with
381381+ match get_desc ty with
400382 Tobject (ty, _) -> close ty
401383 | _ -> assert false
402384···404386405387let row_variable ty =
406388 let rec find ty =
407407- let ty = repr ty in
408408- match ty.desc with
389389+ match get_desc ty with
409390 Tfield (_, _, _, ty) -> find ty
410391 | Tvar _ -> ty
411392 | _ -> assert false
412393 in
413413- match (repr ty).desc with
394394+ match get_desc ty with
414395 Tobject (fi, _) -> find fi
415396 | _ -> assert false
416397···418399(* +++ Bientot obsolete *)
419400420401let set_object_name id rv params ty =
421421- match (repr ty).desc with
402402+ match get_desc ty with
422403 Tobject (_fi, nm) ->
423404 set_name nm (Some (Path.Pident id, rv::params))
424405 | _ ->
425406 assert false
426407427408let remove_object_name ty =
428428- match (repr ty).desc with
409409+ match get_desc ty with
429410 Tobject (_, nm) -> set_name nm None
430411 | Tconstr (_, _, _) -> ()
431412 | _ -> fatal_error "Ctype.remove_object_name"
···433414(**** Hiding of private methods ****)
434415435416let hide_private_methods ty =
436436- match (repr ty).desc with
417417+ match get_desc ty with
437418 Tobject (fi, nm) ->
438419 nm := None;
439420 let (fl, _) = flatten_fields fi in
···459440 | Cty_arrow (_, _, cty) -> signature_of_class_type cty
460441461442let self_type cty =
462462- repr (signature_of_class_type cty).csig_self
443443+ (signature_of_class_type cty).csig_self
463444464445let rec class_type_arity =
465446 function
···530511 and only returns a [variable list].
531512 *)
532513let rec free_vars_rec real ty =
533533- let ty = repr ty in
534514 if try_mark_node ty then
535535- match ty.desc, !really_closed with
515515+ match get_desc ty, !really_closed with
536516 Tvar _, _ ->
537517 free_variables := (ty, real) :: !free_variables
538518 | Tconstr (path, tl, _), Some env ->
539519 begin try
540520 let (_, body, _) = Env.find_type_expansion path env in
541541- if (repr body).level <> generic_level then
521521+ if get_level body <> generic_level then
542522 free_variables := (ty, real) :: !free_variables
543523 with Not_found -> ()
544524 end;
···636616exception CCFailure of closed_class_failure
637617638618let closed_class params sign =
639639- let ty = object_fields (repr sign.csig_self) in
619619+ let ty = object_fields sign.csig_self in
640620 let (fields, rest) = flatten_fields ty in
641621 List.iter mark_type params;
642622 mark_type rest;
···644624 (fun (lab, _, ty) -> if lab = dummy_method then mark_type ty)
645625 fields;
646626 try
647647- ignore (try_mark_node (repr sign.csig_self));
627627+ ignore (try_mark_node sign.csig_self);
648628 List.iter
649629 (fun (lab, kind, ty) ->
650630 if field_kind_repr kind = Fpresent then
651631 try closed_type ty with Non_closed (ty0, real) ->
652632 raise (CCFailure (CC_Method (ty0, real, lab, ty))))
653633 fields;
654654- mark_type_params (repr sign.csig_self);
634634+ mark_type_params sign.csig_self;
655635 List.iter unmark_type params;
656636 unmark_class_signature sign;
657637 None
658638 with CCFailure reason ->
659659- mark_type_params (repr sign.csig_self);
639639+ mark_type_params sign.csig_self;
660640 List.iter unmark_type params;
661641 unmark_class_signature sign;
662642 Some reason
···688668 preserved. Does it worth duplicating this code ?
689669*)
690670let rec generalize ty =
691691- let ty = repr ty in
692692- if (ty.level > !current_level) && (ty.level <> generic_level) then begin
671671+ let level = get_level ty in
672672+ if (level > !current_level) && (level <> generic_level) then begin
693673 set_level ty generic_level;
694674 (* recur into abbrev for the speed *)
695695- begin match ty.desc with
675675+ begin match get_desc ty with
696676 Tconstr (_, _, abbrev) ->
697677 iter_abbrev generalize !abbrev
698678 | _ -> ()
···707687(* Generalize the structure and lower the variables *)
708688709689let rec generalize_structure ty =
710710- let ty = repr ty in
711711- if ty.level <> generic_level then begin
712712- if is_Tvar ty && ty.level > !current_level then
690690+ let level = get_level ty in
691691+ if level <> generic_level then begin
692692+ if is_Tvar ty && level > !current_level then
713693 set_level ty !current_level
714694 else if
715715- ty.level > !current_level &&
716716- match ty.desc with
695695+ level > !current_level &&
696696+ match get_desc ty with
717697 Tconstr (p, _, abbrev) ->
718698 not (is_object_type p) && (abbrev := Mnil; true)
719699 | _ -> true
···730710(* Generalize the spine of a function, if the level >= !current_level *)
731711732712let rec generalize_spine ty =
733733- let ty = repr ty in
734734- if ty.level < !current_level || ty.level = generic_level then () else
735735- match ty.desc with
713713+ let level = get_level ty in
714714+ if level < !current_level || level = generic_level then () else
715715+ match get_desc ty with
736716 Tarrow (_, ty1, ty2, _) ->
737717 set_level ty generic_level;
738718 generalize_spine ty1;
···777757 | _ -> p
778758779759let rec check_scope_escape env level ty =
780780- let ty = repr ty in
781781- let orig_level = ty.level in
760760+ let orig_level = get_level ty in
782761 if try_logged_mark_node ty then begin
783783- if level < ty.scope then
762762+ if level < get_scope ty then
784763 raise_scope_escape_exn ty;
785785- begin match ty.desc with
764764+ begin match get_desc ty with
786765 | Tconstr (p, _, _) when level < Path.scope p ->
787766 begin match !forward_try_expand_safe env ty with
788767 | ty' ->
···794773 let p' = normalize_package_path env p in
795774 if Path.same p p' then raise_escape_exn (Module_type p);
796775 check_scope_escape env level
797797- (Btype.newty2 orig_level (Tpackage (p', fl)))
776776+ (newty2 ~level:orig_level (Tpackage (p', fl)))
798777 | _ ->
799799- iter_type_expr (check_scope_escape env level) ty
778778+ iter_type_expr (check_scope_escape env level) ty
800779 end;
801780 end
802781···808787 raise (Escape { e with context = Some ty })
809788810789let rec update_scope scope ty =
811811- let ty = repr ty in
812812- if ty.scope < scope then begin
813813- if ty.level < scope then raise_scope_escape_exn ty;
790790+ if get_scope ty < scope then begin
791791+ if get_level ty < scope then raise_scope_escape_exn ty;
814792 set_scope ty scope;
815793 (* Only recurse in principal mode as this is not necessary for soundness *)
816794 if !Clflags.principal then iter_type_expr (update_scope scope) ty
···830808*)
831809832810let rec update_level env level expand ty =
833833- let ty = repr ty in
834834- if ty.level > level then begin
835835- if level < ty.scope then raise_scope_escape_exn ty;
836836- match ty.desc with
811811+ if get_level ty > level then begin
812812+ if level < get_scope ty then raise_scope_escape_exn ty;
813813+ match get_desc ty with
837814 Tconstr(p, _tl, _abbrev) when level < Path.scope p ->
838815 (* Try first to replace an abbreviation by its expansion. *)
839816 begin try
840840- link_type ty (!forward_try_expand_safe env ty);
841841- update_level env level expand ty
817817+ let ty' = !forward_try_expand_safe env ty in
818818+ link_type ty ty';
819819+ update_level env level expand ty'
842820 with Cannot_expand ->
843821 raise_escape_exn (Constructor p)
844822 end
···849827 let needs_expand =
850828 expand ||
851829 List.exists2
852852- (fun var ty -> var = Variance.null && (repr ty).level > level)
830830+ (fun var ty -> var = Variance.null && get_level ty > level)
853831 variance tl
854832 in
855833 begin try
856834 if not needs_expand then raise Cannot_expand;
857857- link_type ty (!forward_try_expand_safe env ty);
858858- update_level env level expand ty
835835+ let ty' = !forward_try_expand_safe env ty in
836836+ link_type ty ty';
837837+ update_level env level expand ty'
859838 with Cannot_expand ->
860839 set_level ty level;
861840 iter_type_expr (update_level env level expand) ty
···865844 if Path.same p p' then raise_escape_exn (Module_type p);
866845 set_type_desc ty (Tpackage (p', fl));
867846 update_level env level expand ty
868868- | Tobject(_, ({contents=Some(p, _tl)} as nm))
847847+ | Tobject (_, ({contents=Some(p, _tl)} as nm))
869848 when level < Path.scope p ->
870849 set_name nm None;
871850 update_level env level expand ty
···878857 end;
879858 set_level ty level;
880859 iter_type_expr (update_level env level expand) ty
881881- | Tfield(lab, _, ty1, _)
882882- when lab = dummy_method && (repr ty1).level > level ->
860860+ | Tfield (lab, _, ty1, _)
861861+ when lab = dummy_method && get_level ty1 > level ->
883862 raise_escape_exn Self
884863 | _ ->
885864 set_level ty level;
···890869(* First try without expanding, then expand everything,
891870 to avoid combinatorial blow-up *)
892871let update_level env level ty =
893893- let ty = repr ty in
894894- if ty.level > level then begin
872872+ if get_level ty > level then begin
895873 let snap = snapshot () in
896874 try
897875 update_level env level false ty
···908886(* Lower level of type variables inside contravariant branches *)
909887910888let rec lower_contravariant env var_level visited contra ty =
911911- let ty = repr ty in
912889 let must_visit =
913913- ty.level > var_level &&
914914- match Hashtbl.find visited ty.id with
890890+ get_level ty > var_level &&
891891+ match Hashtbl.find visited (get_id ty) with
915892 | done_contra -> contra && not done_contra
916893 | exception Not_found -> true
917894 in
918895 if must_visit then begin
919919- Hashtbl.add visited ty.id contra;
896896+ Hashtbl.add visited (get_id ty) contra;
920897 let lower_rec = lower_contravariant env var_level visited in
921921- match ty.desc with
898898+ match get_desc ty with
922899 Tvar _ -> if contra then set_level ty var_level
923900 | Tconstr (_, [], _) -> ()
924901 | Tconstr (path, tyl, _abbrev) ->
···983960984961(* Only generalize the type ty0 in ty *)
985962let limited_generalize ty0 ty =
986986- let ty0 = repr ty0 in
987987-988963 let graph = Hashtbl.create 17 in
989964 let idx = ref lowest_level in
990965 let roots = ref [] in
991966992967 let rec inverse pty ty =
993993- let ty = repr ty in
994994- if (ty.level > !current_level) || (ty.level = generic_level) then begin
968968+ let level = get_level ty in
969969+ if (level > !current_level) || (level = generic_level) then begin
995970 decr idx;
996971 Hashtbl.add graph !idx (ty, ref pty);
997997- if (ty.level = generic_level) || (ty == ty0) then
972972+ if (level = generic_level) || eq_type ty ty0 then
998973 roots := ty :: !roots;
999974 set_level ty !idx;
1000975 iter_type_expr (inverse [ty]) ty
10011001- end else if ty.level < lowest_level then begin
10021002- let (_, parents) = Hashtbl.find graph ty.level in
976976+ end else if level < lowest_level then begin
977977+ let (_, parents) = Hashtbl.find graph level in
1003978 parents := pty @ !parents
1004979 end
10059801006981 and generalize_parents ty =
10071007- let idx = ty.level in
982982+ let idx = get_level ty in
1008983 if idx <> generic_level then begin
1009984 set_level ty generic_level;
1010985 List.iter generalize_parents !(snd (Hashtbl.find graph idx));
1011986 (* Special case for rows: must generalize the row variable *)
10121012- match ty.desc with
987987+ match get_desc ty with
1013988 Tvariant row ->
1014989 let more = row_more row in
10151015- let lv = more.level in
990990+ let lv = get_level more in
1016991 if (lv < lowest_level || lv > !current_level)
1017992 && lv <> generic_level then set_level more generic_level
1018993 | _ -> ()
···1020995 in
10219961022997 inverse [] ty;
10231023- if ty0.level < lowest_level then
998998+ if get_level ty0 < lowest_level then
1024999 iter_type_expr (inverse []) ty0;
10251000 List.iter generalize_parents !roots;
10261001 Hashtbl.iter
10271002 (fun _ (ty, _) ->
10281028- if ty.level <> generic_level then set_level ty !current_level)
10031003+ if get_level ty <> generic_level then set_level ty !current_level)
10291004 graph
1030100510311006···10371012 mutable inv_parents : inv_type_expr list }
1038101310391014let rec inv_type hash pty ty =
10401040- let ty = repr ty in
10411015 try
10421016 let inv = TypeHash.find hash ty in
10431017 inv.inv_parents <- pty @ inv.inv_parents
···10511025 inv_type inverted [] ty;
10521026 let node_univars = TypeHash.create 17 in
10531027 let rec add_univar univ inv =
10541054- match inv.inv_type.desc with
10551055- Tpoly (_ty, tl) when List.memq univ (List.map repr tl) -> ()
10281028+ match get_desc inv.inv_type with
10291029+ Tpoly (_ty, tl) when List.memq (get_id univ) (List.map get_id tl) -> ()
10561030 | _ ->
10571031 try
10581032 let univs = TypeHash.find node_univars inv.inv_type in
···1072104610731047let fully_generic ty =
10741048 let rec aux ty =
10751075- let ty = repr ty in
10761049 if not_marked_node ty then
10771077- if ty.level = generic_level then
10501050+ if get_level ty = generic_level then
10781051 (flip_mark_node ty; iter_type_expr aux ty)
10791052 else raise Exit
10801053 in
···11161089 before we call type_pat *)
11171090let rec copy ?partial ?keep_names scope ty =
11181091 let copy = copy ?partial ?keep_names scope in
11191119- let ty = repr ty in
11201120- match ty.desc with
10921092+ match get_desc ty with
11211093 Tsubst (ty, _) -> ty
11221122- | _ ->
11231123- if ty.level <> generic_level && partial = None then ty else
10941094+ | desc ->
10951095+ let level = get_level ty in
10961096+ if level <> generic_level && partial = None then ty else
11241097 (* We only forget types that are non generic and do not contain
11251098 free univars *)
11261099 let forget =
11271127- if ty.level = generic_level then generic_level else
11001100+ if level = generic_level then generic_level else
11281101 match partial with
11291102 None -> assert false
11301103 | Some (free_univars, keep) ->
11311104 if TypeSet.is_empty (free_univars ty) then
11321132- if keep then ty.level else !current_level
11051105+ if keep then level else !current_level
11331106 else generic_level
11341107 in
11351135- if forget <> generic_level then newty2 forget (Tvar None) else
11361136- let desc = ty.desc in
11371137- For_copy.save_desc scope ty desc;
11381138- let t = newvar() in (* Stub *)
11391139- set_scope t ty.scope;
11401140- Private_type_expr.set_desc ty (Tsubst (t, None));
11411141- Private_type_expr.set_desc t
11421142- begin match desc with
11081108+ if forget <> generic_level then newty2 ~level:forget (Tvar None) else
11091109+ let t = newstub ~scope:(get_scope ty) in
11101110+ For_copy.redirect_desc scope ty (Tsubst (t, None));
11111111+ let desc' =
11121112+ match desc with
11431113 | Tconstr (p, tl, _) ->
11441114 let abbrevs = proper_abbrevs p tl !abbreviations in
11451115 begin match find_repr p !abbrevs with
11461146- Some ty when repr ty != t ->
11161116+ Some ty when not (eq_type ty t) ->
11471117 Tlink ty
11481118 | _ ->
11491119 (*
···11621132 end
11631133 | Tvariant row0 ->
11641134 let row = row_repr row0 in
11651165- let more = repr row.row_more in
11351135+ let more = row.row_more in
11361136+ let mored = get_desc more in
11661137 (* We must substitute in a subtle way *)
11671138 (* Tsubst takes a tuple containing the row var and the variant *)
11681168- begin match more.desc with
11391139+ begin match mored with
11691140 Tsubst (_, Some ty2) ->
11701141 (* This variant type has been already copied *)
11711171- Private_type_expr.set_desc ty (Tsubst (ty2, None));
11721172- (* avoid Tlink in the new type *)
11421142+ (* Change the stub to avoid Tlink in the new type *)
11431143+ For_copy.redirect_desc scope ty (Tsubst (ty2, None));
11731144 Tlink ty2
11741145 | _ ->
11751146 (* If the row variable is not generic, we must keep it *)
11761176- let keep = more.level <> generic_level && partial = None in
11471147+ let keep = get_level more <> generic_level && partial = None in
11771148 let more' =
11781178- match more.desc with
11491149+ match mored with
11791150 Tsubst (ty, None) -> ty
11801151 (* TODO: is this case possible?
11811152 possibly an interaction with (copy more) below? *)
11821153 | Tconstr _ | Tnil ->
11831183- For_copy.save_desc scope more more.desc;
11841154 copy more
11851155 | Tvar _ | Tunivar _ ->
11861186- For_copy.save_desc scope more more.desc;
11871187- if keep then more else newty more.desc
11561156+ if keep then more else newty mored
11881157 | _ -> assert false
11891158 in
11901159 let row =
11911191- match repr more' with (* PR#6163 *)
11921192- {desc=Tconstr (x,_,_)} when not (is_fixed row) ->
11601160+ match get_desc more' with (* PR#6163 *)
11611161+ Tconstr (x,_,_) when not (is_fixed row) ->
11931162 {row with row_fixed = Some (Reified x)}
11941163 | _ -> row
11951164 in
···11981167 match partial with
11991168 Some (free_univars, false) ->
12001169 let more' =
12011201- if more.id <> more'.id then
11701170+ if not (eq_type more more') then
12021171 more' (* we've already made a copy *)
12031172 else
12041173 newvar ()
···12191188 | _ -> (more', row)
12201189 in
12211190 (* Register new type first for recursion *)
12221222- Private_type_expr.set_desc
12231223- more (Tsubst (more', Some t));
11911191+ For_copy.redirect_desc scope more
11921192+ (Tsubst(more', Some t));
12241193 (* Return a new copy *)
12251194 Tvariant (copy_row copy true row keep more')
12261195 end
···12351204 | Tobject (ty1, _) when partial <> None ->
12361205 Tobject (copy ty1, ref None)
12371206 | _ -> copy_type_desc ?keep_names copy desc
12381238- end;
12071207+ in
12081208+ Transient_expr.set_stub_desc t desc';
12391209 t
1240121012411211(**** Variants of instantiations ****)
···12961266 type_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
12971267 }
1298126812991299-let existential_name cstr ty = match repr ty with
13001300- | {desc = Tvar (Some name)} -> "$" ^ cstr.cstr_name ^ "_'" ^ name
12691269+let existential_name cstr ty =
12701270+ match get_desc ty with
12711271+ | Tvar (Some name) -> "$" ^ cstr.cstr_name ^ "_'" ^ name
13011272 | _ -> "$" ^ cstr.cstr_name
1302127313031274let instance_constructor ?in_pattern cstr =
···14081379 | a :: l1 -> a :: diff_list l1 l2
1409138014101381let conflicts free bound =
14111411- let bound = List.map repr bound in
14121412- TypeSet.exists (fun t -> List.memq (repr t) bound) free
13821382+ let bound = List.map get_id bound in
13831383+ TypeSet.exists (fun t -> List.memq (get_id t) bound) free
1413138414141385let delayed_copy = ref []
14151386 (* copying to do later *)
1416138714171388(* Copy without sharing until there are no free univars left *)
14181389(* all free univars must be included in [visited] *)
14191419-let rec copy_sep cleanup_scope fixed free bound visited ty =
14201420- let ty = repr ty in
13901390+let rec copy_sep ~cleanup_scope ~fixed ~free ~bound ~may_share
13911391+ (visited : (int * (type_expr * type_expr list)) list) (ty : type_expr) =
14211392 let univars = free ty in
14221422- if TypeSet.is_empty univars then
14231423- if ty.level <> generic_level then ty else
14241424- let t = newvar () in
13931393+ if is_Tvar ty || may_share && TypeSet.is_empty univars then
13941394+ if get_level ty <> generic_level then ty else
13951395+ let t = newstub ~scope:(get_scope ty) in
14251396 delayed_copy :=
14261426- lazy (Private_type_expr.set_desc t (Tlink (copy cleanup_scope ty)))
13971397+ lazy (Transient_expr.set_stub_desc t (Tlink (copy cleanup_scope ty)))
14271398 :: !delayed_copy;
14281399 t
14291400 else try
14301430- let t, bound_t = List.assq ty visited in
14011401+ let t, bound_t = List.assq (get_id ty) visited in
14311402 let dl = if is_Tunivar ty then [] else diff_list bound bound_t in
14321403 if dl <> [] && conflicts univars dl then raise Not_found;
14331404 t
14341405 with Not_found -> begin
14351435- let t = newvar() in (* Stub *)
14061406+ let t = newstub ~scope:(get_scope ty) in
14071407+ let desc = get_desc ty in
14361408 let visited =
14371437- match ty.desc with
14091409+ match desc with
14381410 Tarrow _ | Ttuple _ | Tvariant _ | Tconstr _ | Tobject _ | Tpackage _ ->
14391439- (ty,(t,bound)) :: visited
14111411+ (get_id ty, (t, bound)) :: visited
14401412 | Tvar _ | Tfield _ | Tnil | Tpoly _ | Tunivar _ ->
14411413 visited
14421414 | Tlink _ | Tsubst _ ->
14431415 assert false
14441416 in
14451445- let copy_rec = copy_sep cleanup_scope fixed free bound visited in
14461446- Private_type_expr.set_desc t
14471447- begin match ty.desc with
14171417+ let copy_rec = copy_sep ~cleanup_scope ~fixed ~free ~bound visited in
14181418+ let desc' =
14191419+ match desc with
14481420 | Tvariant row0 ->
14491421 let row = row_repr row0 in
14501450- let more = repr row.row_more in
14221422+ let more = row.row_more in
14511423 (* We shall really check the level on the row variable *)
14521452- let keep = is_Tvar more && more.level <> generic_level in
14531453- let more' = copy_rec more in
14241424+ let keep = is_Tvar more && get_level more <> generic_level in
14251425+ let more' = copy_rec ~may_share:false more in
14541426 let fixed' = fixed && (is_Tvar more || is_Tunivar more) in
14551455- let row = copy_row copy_rec fixed' row keep more' in
14271427+ let row =
14281428+ copy_row (copy_rec ~may_share:true) fixed' row keep more' in
14561429 Tvariant row
14571430 | Tpoly (t1, tl) ->
14581458- let tl = List.map repr tl in
14591459- let tl' = List.map (fun t -> newty t.desc) tl in
14311431+ let tl' = List.map (fun t -> newty (get_desc t)) tl in
14601432 let bound = tl @ bound in
14611433 let visited =
14621462- List.map2 (fun ty t -> ty,(t,bound)) tl tl' @ visited in
14631463- Tpoly (copy_sep cleanup_scope fixed free bound visited t1, tl')
14641464- | _ -> copy_type_desc copy_rec ty.desc
14651465- end;
14341434+ List.map2 (fun ty t -> get_id ty, (t, bound)) tl tl' @ visited in
14351435+ let body =
14361436+ copy_sep ~cleanup_scope ~fixed ~free ~bound ~may_share:true
14371437+ visited t1 in
14381438+ Tpoly (body, tl')
14391439+ | Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *)
14401440+ Tfield (p, field_kind_repr k, copy_rec ~may_share:true ty1,
14411441+ copy_rec ~may_share:false ty2)
14421442+ | _ -> copy_type_desc (copy_rec ~may_share:true) desc
14431443+ in
14441444+ Transient_expr.set_stub_desc t desc';
14661445 t
14671446 end
1468144714691448let instance_poly' cleanup_scope ~keep_names fixed univars sch =
14701449 (* In order to compute univars below, [sch] should not contain [Tsubst] *)
14711471- let univars = List.map repr univars in
14721450 let copy_var ty =
14731473- match ty.desc with
14511451+ match get_desc ty with
14741452 Tunivar name -> if keep_names then newty (Tvar name) else newvar ()
14751453 | _ -> assert false
14761454 in
14771455 let vars = List.map copy_var univars in
14781478- let pairs = List.map2 (fun u v -> u, (v, [])) univars vars in
14561456+ let pairs = List.map2 (fun u v -> get_id u, (v, [])) univars vars in
14791457 delayed_copy := [];
14801480- let ty = copy_sep cleanup_scope fixed (compute_univars sch) [] pairs sch in
14581458+ let ty =
14591459+ copy_sep ~cleanup_scope ~fixed ~free:(compute_univars sch) ~bound:[]
14601460+ ~may_share:true pairs sch in
14811461 List.iter Lazy.force !delayed_copy;
14821462 delayed_copy := [];
14831463 vars, ty
···14901470let instance_label fixed lbl =
14911471 For_copy.with_scope (fun scope ->
14921472 let vars, ty_arg =
14931493- match repr lbl.lbl_arg with
14941494- {desc = Tpoly (ty, tl)} ->
14731473+ match get_desc lbl.lbl_arg with
14741474+ Tpoly (ty, tl) ->
14951475 instance_poly' scope ~keep_names:false fixed tl ty
14961476 | _ ->
14971477 [], copy scope lbl.lbl_arg
···15071487let unify_var' = (* Forward declaration *)
15081488 ref (fun _env _ty1 _ty2 -> assert false)
1509148915101510-let subst env level priv abbrev ty params args body =
14901490+let subst env level priv abbrev oty params args body =
15111491 if List.length params <> List.length args then raise Cannot_subst;
15121492 let old_level = !current_level in
15131493 current_level := level;
15141494 let body0 = newvar () in (* Stub *)
15151495 let undo_abbrev =
15161516- match ty with
14961496+ match oty with
15171497 | None -> fun () -> () (* No abbreviation added *)
15181518- | Some ({desc = Tconstr (path, tl, _)} as ty) ->
15191519- let abbrev = proper_abbrevs path tl abbrev in
15201520- memorize_abbrev abbrev priv path ty body0;
15211521- fun () -> forget_abbrev abbrev path
15221522- | _ ->
15231523- assert false
14981498+ | Some ty ->
14991499+ match get_desc ty with
15001500+ Tconstr (path, tl, _) ->
15011501+ let abbrev = proper_abbrevs path tl abbrev in
15021502+ memorize_abbrev abbrev priv path ty body0;
15031503+ fun () -> forget_abbrev abbrev path
15041504+ | _ -> assert false
15241505 in
15251506 abbreviations := abbrev;
15261507 let (params', body') = instance_parameterized_type params body in
···15891570*)
15901571let expand_abbrev_gen kind find_type_expansion env ty =
15911572 check_abbrev_env env;
15921592- match ty with
15931593- {desc = Tconstr (path, args, abbrev); level = level; scope} ->
15731573+ match get_desc ty with
15741574+ Tconstr (path, args, abbrev) ->
15751575+ let level = get_level ty in
15761576+ let scope = get_scope ty in
15941577 let lookup_abbrev = proper_abbrevs path args abbrev in
15951578 begin match find_expans kind path !lookup_abbrev with
15961579 Some ty' ->
···16131596 typing error *)
16141597 ()
16151598 end;
16161616- let ty' = repr ty' in
16171617- (* assert (ty != ty'); *) (* PR#7324 *)
16181599 ty'
16191600 | None ->
16201601 match find_type_expansion path env with
···16221603 (* another way to expand is to normalize the path itself *)
16231604 let path' = Env.normalize_type_path None env path in
16241605 if Path.same path path' then raise Cannot_expand
16251625- else newty2 level (Tconstr (path', args, abbrev))
16061606+ else newty2 ~level (Tconstr (path', args, abbrev))
16261607 | (params, body, lv) ->
16271608 (* prerr_endline
16281609 ("add a "^string_of_kind kind^" expansion for "^Path.name path);*)
···16341615 (* For gadts, remember type as non exportable *)
16351616 (* The ambiguous level registered for ty' should be the highest *)
16361617 (* if !trace_gadt_instances then begin *)
16371637- let scope = Int.max lv ty.scope in
16181618+ let scope = Int.max lv (get_scope ty) in
16381619 update_scope scope ty;
16391620 update_scope scope ty';
16401621 ty'
···16491630(* Expand once the head of a type *)
16501631let expand_head_once env ty =
16511632 try
16521652- expand_abbrev env (repr ty)
16331633+ expand_abbrev env ty
16531634 with Cannot_expand | Escape _ -> assert false
1654163516551636(* Check whether a type can be expanded *)
···16681649 Raise Cannot_expand if the type cannot be expanded.
16691650 May raise Escape, if a recursion was hidden in the type. *)
16701651let try_expand_once env ty =
16711671- let ty = repr ty in
16721672- match ty.desc with
16731673- Tconstr _ -> repr (expand_abbrev env ty)
16521652+ match get_desc ty with
16531653+ Tconstr _ -> expand_abbrev env ty
16741654 | _ -> raise Cannot_expand
1675165516761656(* This one only raises Cannot_expand *)
···16811661 Btype.backtrack snap; cleanup_abbrev (); raise Cannot_expand
1682166216831663(* Fully expand the head of a type. *)
16841684-let rec try_expand_head try_once env ty =
16641664+let rec try_expand_head
16651665+ (try_once : Env.t -> type_expr -> type_expr) env ty =
16851666 let ty' = try_once env ty in
16861667 try try_expand_head try_once env ty'
16871668 with Cannot_expand -> ty'
···16911672 try
16921673 try_expand_head try_expand_once env ty
16931674 with
16941694- | Cannot_expand -> repr ty
16751675+ | Cannot_expand -> ty
16951676 | Escape e -> raise_for Unify (Escape e)
1696167716971678(* Safe version of expand_head, never fails *)
16981679let expand_head env ty =
16991699- try try_expand_head try_expand_safe env ty with Cannot_expand -> repr ty
16801680+ try try_expand_head try_expand_safe env ty
16811681+ with Cannot_expand -> ty
1700168217011683let _ = forward_try_expand_safe := try_expand_safe
17021684···17121694 | May_have_typedecl
1713169517141696let rec extract_concrete_typedecl env ty =
17151715- let ty = repr ty in
17161716- match ty.desc with
17171717- | Tconstr (p, _, _) ->
16971697+ match get_desc ty with
16981698+ Tconstr (p, _, _) ->
17181699 let decl = Env.find_type p env in
17191700 if decl.type_kind <> Type_abstract then Typedecl(p, p, decl)
17201701 else begin
···17501731 false
1751173217521733let try_expand_once_opt env ty =
17531753- let ty = repr ty in
17541754- match ty.desc with
17551755- Tconstr _ -> repr (expand_abbrev_opt env ty)
17341734+ match get_desc ty with
17351735+ Tconstr _ -> expand_abbrev_opt env ty
17561736 | _ -> raise Cannot_expand
1757173717581738let try_expand_safe_opt env ty =
···17621742 Btype.backtrack snap; raise Cannot_expand
1763174317641744let expand_head_opt env ty =
17651765- try try_expand_head try_expand_safe_opt env ty with Cannot_expand -> repr ty
17451745+ try try_expand_head try_expand_safe_opt env ty with Cannot_expand -> ty
1766174617671747(* Recursively expand the head of a type.
17681748 Also expand #-types.
···17721752let full_expand ~may_forget_scope env ty =
17731753 let ty =
17741754 if may_forget_scope then
17751775- let ty = repr ty in
17761755 try expand_head_unif env ty with Unify_trace _ ->
17771756 (* #10277: forget scopes when printing trace *)
17781757 begin_def ();
17791779- init_def ty.level;
17581758+ init_def (get_level ty);
17801759 let ty =
17811760 (* The same as [expand_head], except in the failing case we return the
17821761 *original* type, not [correct_levels ty].*)
17831762 try try_expand_head try_expand_safe env (correct_levels ty) with
17841784- | Cannot_expand -> repr ty
17631763+ | Cannot_expand -> ty
17851764 in
17861765 end_def ();
17871766 ty
17881767 else expand_head env ty
17891768 in
17901790- let ty = repr ty in
17911791- match ty.desc with
17921792- Tobject (fi, {contents = Some (_, v::_)}) when is_Tvar (repr v) ->
17931793- newty2 ty.level (Tobject (fi, ref None))
17691769+ match get_desc ty with
17701770+ Tobject (fi, {contents = Some (_, v::_)}) when is_Tvar v ->
17711771+ newty2 ~level:(get_level ty) (Tobject (fi, ref None))
17941772 | _ ->
17951773 ty
17961774···18021780let generic_abbrev env path =
18031781 try
18041782 let (_, body, _) = Env.find_type_expansion path env in
18051805- (repr body).level = generic_level
17831783+ get_level body = generic_level
18061784 with
18071785 Not_found ->
18081786 false
···18131791 {type_kind = Type_abstract;
18141792 type_private = Private;
18151793 type_manifest = Some body} ->
18161816- (repr body).level = generic_level
17941794+ get_level body = generic_level
18171795 | _ -> false
18181796 with Not_found -> false
18191797···1831180918321810exception Occur
1833181118341834-let rec occur_rec env allow_recursive visited ty0 = function
18351835- | {desc=Tlink ty} ->
18361836- occur_rec env allow_recursive visited ty0 ty
18371837- | ty ->
18381838- if ty == ty0 then raise Occur;
18391839- match ty.desc with
18121812+let rec occur_rec env allow_recursive visited ty0 ty =
18131813+ if eq_type ty ty0 then raise Occur;
18141814+ match get_desc ty with
18401815 Tconstr(p, _tl, _abbrev) ->
18411816 if allow_recursive && is_contractive env p then () else
18421817 begin try
···1893186818941869let rec local_non_recursive_abbrev ~allow_rec strict visited env p ty =
18951870 (*Format.eprintf "@[Check %s =@ %a@]@." (Path.name p) !Btype.print_raw ty;*)
18961896- let ty = repr ty in
18971897- if not (List.memq ty visited) then begin
18981898- match ty.desc with
18711871+ if not (List.memq (get_id ty) visited) then begin
18721872+ match get_desc ty with
18991873 Tconstr(p', args, _abbrev) ->
19001874 if Path.same p p' then raise Occur;
19011875 if allow_rec && not strict && is_contractive env p' then () else
19021902- let visited = ty :: visited in
18761876+ let visited = get_id ty :: visited in
19031877 begin try
19041878 (* try expanding, since [p] could be hidden *)
19051879 local_non_recursive_abbrev ~allow_rec strict visited env p
···19111885 in
19121886 List.iter2
19131887 (fun tv ty ->
19141914- let strict = strict || not (is_Tvar (repr tv)) in
18881888+ let strict = strict || not (is_Tvar tv) in
19151889 local_non_recursive_abbrev ~allow_rec strict visited env p ty)
19161890 params args
19171891 end
···19191893 ()
19201894 | _ ->
19211895 if strict || not allow_rec then (* PR#7374 *)
19221922- let visited = ty :: visited in
18961896+ let visited = get_id ty :: visited in
19231897 iter_type_expr
19241898 (local_non_recursive_abbrev ~allow_rec true visited env p) ty
19251899 end
···19451919 (cl1, cl2) :: rem ->
19461920 let find_univ t cl =
19471921 try
19481948- let (_, r) = List.find (fun (t',_) -> t == repr t') cl in
19221922+ let (_, r) = List.find (fun (t',_) -> eq_type t t') cl in
19491923 Some r
19501924 with Not_found -> None
19511925 in
19521926 begin match find_univ t1 cl1, find_univ t2 cl2 with
19531953- Some {contents=Some t'2}, Some _ when t2 == repr t'2 ->
19271927+ Some {contents=Some t'2}, Some _ when eq_type t2 t'2 ->
19541928 ()
19551929 | Some({contents=None} as r1), Some({contents=None} as r2) ->
19561930 set_univar r1 t2; set_univar r2 t1
···19731947let occur_univar ?(inj_only=false) env ty =
19741948 let visited = ref TypeMap.empty in
19751949 let rec occur_rec bound ty =
19761976- let ty = repr ty in
19771950 if not_marked_node ty then
19781951 if TypeSet.is_empty bound then
19791952 (flip_mark_node ty; occur_desc bound ty)
···19871960 visited := TypeMap.add ty bound !visited;
19881961 occur_desc bound ty
19891962 and occur_desc bound ty =
19901990- match ty.desc with
19631963+ match get_desc ty with
19911964 Tunivar _ ->
19921965 if not (TypeSet.mem ty bound) then
19931966 raise_escape_exn (Univ ty)
19941967 | Tpoly (ty, tyl) ->
19951995- let bound = List.fold_right TypeSet.add (List.map repr tyl) bound in
19681968+ let bound = List.fold_right TypeSet.add tyl bound in
19961969 occur_rec bound ty
19971970 | Tconstr (_, [], _) -> ()
19981971 | Tconstr (p, tl, _) ->
···2032200520332006(* Grouping univars by families according to their binders *)
20342007let add_univars =
20352035- List.fold_left (fun s (t,_) -> TypeSet.add (repr t) s)
20082008+ List.fold_left (fun s (t,_) -> TypeSet.add t s)
2036200920372010let get_univar_family univar_pairs univars =
20382011 if univars = [] then TypeSet.empty else
20392012 let insert s = function
20402013 cl1, (_::_ as cl2) ->
20412041- if List.exists (fun (t1,_) -> TypeSet.mem (repr t1) s) cl1 then
20142014+ if List.exists (fun (t1,_) -> TypeSet.mem t1 s) cl1 then
20422015 add_univars s cl2
20432016 else s
20442017 | _ -> s
···20512024 let family = get_univar_family univar_pairs vl in
20522025 let visited = ref TypeSet.empty in
20532026 let rec occur t =
20542054- let t = repr t in
20552027 if TypeSet.mem t !visited then () else begin
20562028 visited := TypeSet.add t !visited;
20572057- match t.desc with
20292029+ match get_desc t with
20582030 Tpoly (t, tl) ->
20592059- if List.exists (fun t -> TypeSet.mem (repr t) family) tl then ()
20312031+ if List.exists (fun t -> TypeSet.mem t family) tl then ()
20602032 else occur t
20612033 | Tunivar _ -> if TypeSet.mem t family then raise_escape_exn (Univ t)
20622034 | Tconstr (_, [], _) -> ()
···20832055 List.fold_left (fun s (cl,_) -> add_univars s cl)
20842056 TypeSet.empty old_univars
20852057 in
20862086- let tl1 = List.map repr tl1 and tl2 = List.map repr tl2 in
20872058 if List.exists (fun t -> TypeSet.mem t known_univars) tl1 then
20882059 univars_escape env old_univars tl1 (newty(Tpoly(t2,tl2)));
20892060 if List.exists (fun t -> TypeSet.mem t known_univars) tl2 then
···2105207621062077let polyfy env ty vars =
21072078 let subst_univar scope ty =
21082108- let ty = repr ty in
21092109- match ty.desc with
21102110- | Tvar name when ty.level = generic_level ->
21112111- For_copy.save_desc scope ty ty.desc;
20792079+ match get_desc ty with
20802080+ | Tvar name when get_level ty = generic_level ->
21122081 let t = newty (Tunivar name) in
21132113- Private_type_expr.set_desc ty (Tsubst (t, None));
20822082+ For_copy.redirect_desc scope ty (Tsubst (t, None));
21142083 Some t
21152084 | _ -> None
21162085 in
···21202089 For_copy.with_scope (fun scope ->
21212090 let vars' = List.filter_map (subst_univar scope) vars in
21222091 let ty = copy scope ty in
21232123- let ty = newty2 ty.level (Tpoly(repr ty, vars')) in
20922092+ let ty = newty2 ~level:(get_level ty) (Tpoly(ty, vars')) in
21242093 let complete = List.length vars = List.length vars' in
21252094 ty, complete
21262095 )
···2139210821402109let rec has_cached_expansion p abbrev =
21412110 match abbrev with
21422142- Mnil -> false
21432143- | Mcons(_, p', _, _, rem) -> Path.same p p' || has_cached_expansion p rem
21442144- | Mlink rem -> has_cached_expansion p !rem
21112111+ Mnil -> false
21122112+ | Mcons(_, p', _, _, rem) -> Path.same p p' || has_cached_expansion p rem
21132113+ | Mlink rem -> has_cached_expansion p !rem
2145211421462115(**** Transform error trace ****)
21472116(* +++ Move it to some other place ? *)
···21492118 but still might be nice. *)
2150211921512120let expand_type env ty =
21522152- { ty = repr ty;
21212121+ { ty = ty;
21532122 expanded = full_expand ~may_forget_scope:true env ty }
2154212321552124let expand_any_trace map env trace =
···21902159(* Return whether [t0] occurs in [ty]. Objects are also traversed. *)
21912160let deep_occur t0 ty =
21922161 let rec occur_rec ty =
21932193- let ty = repr ty in
21942194- if ty.level >= t0.level && try_mark_node ty then begin
21952195- if ty == t0 then raise Occur;
21622162+ if get_level ty >= get_level t0 && try_mark_node ty then begin
21632163+ if eq_type ty t0 then raise Occur;
21962164 iter_type_expr occur_rec ty
21972165 end
21982166 in
···22212189 Env.enter_type (get_new_abstract_name name) decl !env
22222190 ~scope:fresh_constr_scope in
22232191 let path = Path.Pident id in
22242224- let t = newty2 lev (Tconstr (path,[],ref Mnil)) in
21922192+ let t = newty2 ~level:lev (Tconstr (path,[],ref Mnil)) in
22252193 env := new_env;
22262194 path, t
22272195 in
22282196 let visited = ref TypeSet.empty in
22292197 let rec iterator ty =
22302230- let ty = repr ty in
22312198 if TypeSet.mem ty !visited then () else begin
22322199 visited := TypeSet.add ty !visited;
22332233- match ty.desc with
22002200+ match get_desc ty with
22342201 Tvar o ->
22352235- let path, t = create_fresh_constr ty.level o in
22022202+ let level = get_level ty in
22032203+ let path, t = create_fresh_constr level o in
22362204 link_type ty t;
22372237- if ty.level < fresh_constr_scope then
22052205+ if level < fresh_constr_scope then
22382206 raise_for Unify (Escape (escape (Constructor path)))
22392207 | Tvariant r ->
22402208 let r = row_repr r in
22412209 if not (static_row r) then begin
22422210 if is_fixed r then iterator (row_more r) else
22432211 let m = r.row_more in
22442244- match m.desc with
22122212+ match get_desc m with
22452213 Tvar o ->
22462246- let path, t = create_fresh_constr m.level o in
22142214+ let level = get_level m in
22152215+ let path, t = create_fresh_constr level o in
22472216 let row =
22482217 let row_fixed = Some (Reified path) in
22492218 {r with row_fields=[]; row_fixed; row_more = t} in
22502250- link_type m (newty2 m.level (Tvariant row));
22512251- if m.level < fresh_constr_scope then
22192219+ link_type m (newty2 ~level (Tvariant row));
22202220+ if level < fresh_constr_scope then
22522221 raise_for Unify (Escape (escape (Constructor path)))
22532222 | _ -> assert false
22542223 end;
···2293226222942263(* Check for datatypes carefully; see PR#6348 *)
22952264let rec expands_to_datatype env ty =
22962296- let ty = repr ty in
22972297- match ty.desc with
22652265+ match get_desc ty with
22982266 Tconstr (p, _, _) ->
22992267 begin try
23002268 is_datatype (Env.find_type p env) ||
···23172285 *)
2318228623192287let rec mcomp type_pairs env t1 t2 =
23202320- if t1 == t2 then () else
23212321- let t1 = repr t1 in
23222322- let t2 = repr t2 in
23232323- if t1 == t2 then () else
23242324- match (t1.desc, t2.desc) with
22882288+ if eq_type t1 t2 then () else
22892289+ match (get_desc t1, get_desc t2) with
23252290 | (Tvar _, _)
23262291 | (_, Tvar _) ->
23272292 ()
···23312296 let t1' = expand_head_opt env t1 in
23322297 let t2' = expand_head_opt env t2 in
23332298 (* Expansion may have changed the representative of the types... *)
23342334- let t1' = repr t1' and t2' = repr t2' in
23352335- if t1' == t2' then () else
22992299+ if eq_type t1' t2' then () else
23362300 begin try TypePairs.find type_pairs (t1', t2')
23372301 with Not_found ->
23382302 TypePairs.add type_pairs (t1', t2') ();
23392339- match (t1'.desc, t2'.desc) with
23032303+ match (get_desc t1', get_desc t2') with
23402304 | (Tvar _, _)
23412305 | (_, Tvar _) ->
23422306 ()
···23992363 let has_present =
24002364 List.exists (fun (_, k, _) -> field_kind_repr k = Fpresent) in
24012365 mcomp type_pairs env rest1 rest2;
24022402- if has_present miss1 && (object_row ty2).desc = Tnil
24032403- || has_present miss2 && (object_row ty1).desc = Tnil then raise Incompatible;
23662366+ if has_present miss1 && get_desc (object_row ty2) = Tnil
23672367+ || has_present miss2 && get_desc (object_row ty1) = Tnil
23682368+ then raise Incompatible;
24042369 List.iter
24052370 (function (_n, k1, t1, k2, t2) ->
24062371 mcomp_kind k1 k2;
···25242489let find_lowest_level ty =
25252490 let lowest = ref generic_level in
25262491 let rec find ty =
25272527- let ty = repr ty in
25282492 if not_marked_node ty then begin
25292529- if ty.level < !lowest then lowest := ty.level;
24932493+ let level = get_level ty in
24942494+ if level < !lowest then lowest := level;
25302495 flip_mark_node ty;
25312496 iter_type_expr find ty
25322497 end
···25542519let unify_eq_set = TypePairs.create 11
2555252025562521let order_type_pair t1 t2 =
25572557- if t1.id <= t2.id then (t1, t2) else (t2, t1)
25222522+ if get_id t1 <= get_id t2 then (t1, t2) else (t2, t1)
2558252325592524let add_type_equality t1 t2 =
25602525 TypePairs.add unify_eq_set (order_type_pair t1 t2) ()
···26432608let rigid_variants = ref false
2644260926452610let unify_eq t1 t2 =
26462646- t1 == t2 ||
26112611+ eq_type t1 t2 ||
26472612 match !umode with
26482613 | Expression -> false
26492614 | Pattern ->
···26572622 | () ->
26582623 begin
26592624 try
26602660- update_level env t1.level t2;
26612661- update_scope t1.scope t2
26252625+ update_level env (get_level t1) t2;
26262626+ update_scope (get_scope t1) t2;
26622627 with Escape e ->
26632628 raise_for Unify (Escape e)
26642629 end;
···26712636let record_equation t1 t2 =
26722637 match !equations_generation with
26732638 | Forbidden -> assert false
26742674- | Allowed { equated_types } -> TypePairs.add equated_types (t1, t2) ()
26392639+ | Allowed { equated_types } ->
26402640+ TypePairs.add equated_types (t1, t2) ()
2675264126762642(* Called from unify3 *)
26772643let unify3_var env t1' t2 t2' =
···2712267827132679let rec unify (env:Env.t ref) t1 t2 =
27142680 (* First step: special cases (optimizations) *)
27152715- if t1 == t2 then () else
27162716- let t1 = repr t1 in
27172717- let t2 = repr t2 in
27182681 if unify_eq t1 t2 then () else
27192682 let reset_tracing = check_trace_gadt_instances !env in
2720268327212684 try
27222685 type_changed := true;
27232723- begin match (t1.desc, t2.desc) with
26862686+ begin match (get_desc t1, get_desc t2) with
27242687 (Tvar _, Tconstr _) when deep_occur t1 t2 ->
27252688 unify2 env t1 t2
27262689 | (Tconstr _, Tvar _) when deep_occur t2 t1 ->
···27312694 if unify1_var !env t2 t1 then () else unify2 env t1 t2
27322695 | (Tunivar _, Tunivar _) ->
27332696 unify_univar_for Unify t1 t2 !univar_pairs;
27342734- update_level_for Unify !env t1.level t2;
27352735- update_scope_for Unify t1.scope t2;
26972697+ update_level_for Unify !env (get_level t1) t2;
26982698+ update_scope_for Unify (get_scope t1) t2;
27362699 link_type t1 t2
27372700 | (Tconstr (p1, [], a1), Tconstr (p2, [], a2))
27382701 when Path.same p1 p2 (* && actual_mode !env = Old *)
···27412704 when any of the types has a cached expansion. *)
27422705 && not (has_cached_expansion p1 !a1
27432706 || has_cached_expansion p2 !a2) ->
27442744- update_level_for Unify !env t1.level t2;
27452745- update_scope_for Unify t1.scope t2;
27072707+ update_level_for Unify !env (get_level t1) t2;
27082708+ update_scope_for Unify (get_scope t1) t2;
27462709 link_type t1 t2
27472710 | (Tconstr (p1, [], _), Tconstr (p2, [], _))
27482711 when Env.has_local_constraints !env
···27712734 ignore (expand_head_unif !env t2);
27722735 let t1' = expand_head_unif !env t1 in
27732736 let t2' = expand_head_unif !env t2 in
27742774- let lv = Int.min t1'.level t2'.level in
27752775- let scope = Int.max t1'.scope t2'.scope in
27372737+ let lv = Int.min (get_level t1') (get_level t2') in
27382738+ let scope = Int.max (get_scope t1') (get_scope t2') in
27762739 update_level_for Unify !env lv t2;
27772740 update_level_for Unify !env lv t1;
27782741 update_scope_for Unify scope t2;
27792742 update_scope_for Unify scope t1;
27802743 if unify_eq t1' t2' then () else
2781274427822782- let t1 = repr t1 and t2 = repr t2 in
27832745 let t1, t2 =
27842746 if !Clflags.principal
27852747 && (find_lowest_level t1' < lv || find_lowest_level t2' < lv) then
27862748 (* Expand abbreviations hiding a lower level *)
27872749 (* Should also do it for parameterized types, after unification... *)
27882788- (match t1.desc with Tconstr (_, [], _) -> t1' | _ -> t1),
27892789- (match t2.desc with Tconstr (_, [], _) -> t2' | _ -> t2)
27502750+ (match get_desc t1 with Tconstr (_, [], _) -> t1' | _ -> t1),
27512751+ (match get_desc t2 with Tconstr (_, [], _) -> t2' | _ -> t2)
27902752 else (t1, t2)
27912753 in
27922754 if unify_eq t1 t1' || not (unify_eq t2 t2') then
···27982760and unify3 env t1 t1' t2 t2' =
27992761 (* Third step: truly unification *)
28002762 (* Assumes either [t1 == t1'] or [t2 != t2'] *)
28012801- let d1 = t1'.desc and d2 = t2'.desc in
28022802- let create_recursion = (t2 != t2') && (deep_occur t1' t2) in
27632763+ let tt1' = Transient_expr.repr t1' in
27642764+ let d1 = tt1'.desc and d2 = get_desc t2' in
27652765+ let create_recursion =
27662766+ (not (eq_type t2 t2')) && (deep_occur t1' t2) in
2803276728042768 begin match (d1, d2) with (* handle vars and univars specially *)
28052769 (Tunivar _, Tunivar _) ->
···28962860 unify_fields env fi1 fi2;
28972861 (* Type [t2'] may have been instantiated by [unify_fields] *)
28982862 (* XXX One should do some kind of unification... *)
28992899- begin match (repr t2').desc with
28632863+ begin match get_desc t2' with
29002864 Tobject (_, {contents = Some (_, va::_)}) when
29012901- (match (repr va).desc with
28652865+ (match get_desc va with
29022866 Tvar _|Tunivar _|Tnil -> true | _ -> false) -> ()
29032867 | Tobject (_, nm2) -> set_name nm2 !nm1
29042868 | _ -> ()
···29232887 Fvar r when f <> dummy_method ->
29242888 set_kind r Fabsent;
29252889 if d2 = Tnil then unify env rem t2'
29262926- else unify env (newty2 rem.level Tnil) rem
28902890+ else unify env (newgenty Tnil) rem
29272891 | _ ->
29282892 if f = dummy_method then
29292893 raise_for Unify (Obj Self_cannot_be_closed)
···29412905 | (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
29422906 begin try
29432907 unify_package !env (unify_list env)
29442944- t1.level p1 fl1 t2.level p2 fl2
29082908+ (get_level t1) p1 fl1 (get_level t2) p2 fl2
29452909 with Not_found ->
29462910 if !umode = Expression then raise_unexplained_for Unify;
29472911 List.iter (fun (_n, ty) -> reify env ty) (fl1 @ fl2);
···29562920 (* XXX Commentaires + changer "create_recursion"
29572921 ||| Comments + change "create_recursion" *)
29582922 if create_recursion then
29592959- match t2.desc with
29232923+ match get_desc t2 with
29602924 Tconstr (p, tl, abbrev) ->
29612925 forget_abbrev abbrev p;
29622926 let t2'' = expand_head_unif !env t2 in
29632927 if not (closed_parameterized_type tl t2'') then
29642964- link_type (repr t2) (repr t2')
29282928+ link_type t2 t2'
29652929 | _ ->
29662930 () (* t2 has already been expanded by update_level *)
29672931 with Unify_trace trace ->
29682968- Private_type_expr.set_desc t1' d1;
29322932+ Transient_expr.set_desc tt1' d1;
29692933 raise_trace_for Unify trace
29702934 end
29712935···29772941(* Build a fresh row variable for unification *)
29782942and make_rowvar level use1 rest1 use2 rest2 =
29792943 let set_name ty name =
29802980- match ty.desc with
29442944+ match get_desc ty with
29812945 Tvar None -> set_type_desc ty (Tvar name)
29822946 | _ -> ()
29832947 in
29842948 let name =
29852985- match rest1.desc, rest2.desc with
29492949+ match get_desc rest1, get_desc rest2 with
29862950 Tvar (Some _ as name1), Tvar (Some _ as name2) ->
29872987- if rest1.level <= rest2.level then name1 else name2
29512951+ if get_level rest1 <= get_level rest2 then name1 else name2
29882952 | Tvar (Some _ as name), _ ->
29892953 if use2 then set_name rest2 name; name
29902954 | _, Tvar (Some _ as name) ->
···29922956 | _ -> None
29932957 in
29942958 if use1 then rest1 else
29952995- if use2 then rest2 else newvar2 ?name level
29592959+ if use2 then rest2 else newty2 ~level (Tvar name)
2996296029972961and unify_fields env ty1 ty2 = (* Optimization *)
29982962 let (fields1, rest1) = flatten_fields ty1
29992963 and (fields2, rest2) = flatten_fields ty2 in
30002964 let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
30013001- let l1 = (repr ty1).level and l2 = (repr ty2).level in
29652965+ let l1 = get_level ty1 and l2 = get_level ty2 in
30022966 let va = make_rowvar (Int.min l1 l2) (miss2=[]) rest1 (miss1=[]) rest2 in
30033003- let d1 = rest1.desc and d2 = rest2.desc in
29672967+ let tr1 = Transient_expr.repr rest1 and tr2 = Transient_expr.repr rest2 in
29682968+ let d1 = tr1.desc and d2 = tr2.desc in
30042969 try
30052970 unify env (build_fields l1 miss1 va) rest2;
30062971 unify env rest1 (build_fields l2 miss2 va);
···30092974 unify_kind k1 k2;
30102975 try
30112976 if !trace_gadt_instances then begin
30123012- update_level_for Unify !env va.level t1;
30133013- update_scope_for Unify va.scope t1
29772977+ update_level_for Unify !env (get_level va) t1;
29782978+ update_scope_for Unify (get_scope va) t1
30142979 end;
30152980 unify env t1 t2
30162981 with Unify_trace trace ->
···30192984 )
30202985 pairs
30212986 with exn ->
30223022- set_type_desc rest1 d1;
30233023- set_type_desc rest2 d2;
29872987+ Transient_expr.set_desc tr1 d1;
29882988+ Transient_expr.set_desc tr2 d2;
30242989 raise exn
3025299030262991and unify_kind k1 k2 =
···30493014 end;
30503015 let fixed1 = fixed_explanation row1 and fixed2 = fixed_explanation row2 in
30513016 let more = match fixed1, fixed2 with
30523052- | Some _, Some _ -> if rm2.level < rm1.level then rm2 else rm1
30173017+ | Some _, Some _ -> if get_level rm2 < get_level rm1 then rm2 else rm1
30533018 | Some _, None -> rm1
30543019 | None, Some _ -> rm2
30553055- | None, None -> newty2 (Int.min rm1.level rm2.level) (Tvar None)
30203020+ | None, None ->
30213021+ newty2 ~level:(Int.min (get_level rm1) (get_level rm2)) (Tvar None)
30563022 in
30573023 let fixed = merge_fixed_explanation fixed1 fixed2
30583024 and closed = row1.row_closed || row2.row_closed in
···31053071 let rm = row_more row in
31063072 (*if !trace_gadt_instances && rm.desc = Tnil then () else*)
31073073 if !trace_gadt_instances then
31083108- update_level_for Unify !env rm.level (newgenty (Tvariant row));
30743074+ update_level_for Unify !env (get_level rm) (newgenty (Tvariant row));
31093075 if row_fixed row then
31103110- if more == rm then () else
30763076+ if eq_type more rm then () else
31113077 if is_Tvar rm then link_type rm more else unify env rm more
31123078 else
31133079 let ty = newgenty (Tvariant {row0 with row_fields = rest}) in
31143114- update_level_for Unify !env rm.level ty;
31153115- update_scope_for Unify rm.scope ty;
30803080+ update_level_for Unify !env (get_level rm) ty;
30813081+ update_scope_for Unify (get_scope rm) ty;
31163082 link_type rm ty
31173083 in
31183118- let md1 = rm1.desc and md2 = rm2.desc in
30843084+ let tm1 = Transient_expr.repr rm1 and tm2 = Transient_expr.repr rm2 in
30853085+ let md1 = tm1.desc and md2 = tm2.desc in
31193086 begin try
31203087 set_more row2 r1;
31213088 set_more row1 r2;
···31283095 pairs;
31293096 if static_row row1 then begin
31303097 let rm = row_more row1 in
31313131- if is_Tvar rm then link_type rm (newty2 rm.level Tnil)
30983098+ if is_Tvar rm then link_type rm (newty2 ~level:(get_level rm) Tnil)
31323099 end
31333100 with exn ->
31343134- set_type_desc rm1 md1; set_type_desc rm2 md2; raise exn
31013101+ Transient_expr.set_desc tm1 md1;
31023102+ Transient_expr.set_desc tm2 md2;
31033103+ raise exn
31353104 end
3136310531373106and unify_row_field env fixed1 fixed2 rm1 rm2 l f1 f2 =
···31693138 !e1 <> None || !e2 <> None
31703139 end in
31713140 if redo then unify_row_field env fixed1 fixed2 rm1 rm2 l f1 f2 else
31723172- let tl1 = List.map repr tl1 and tl2 = List.map repr tl2 in
31733173- let rec remq tl = function [] -> []
31743174- | ty :: tl' ->
31753175- if List.memq ty tl then remq tl tl' else ty :: remq tl tl'
31763176- in
31413141+ let remq tl =
31423142+ List.filter (fun ty -> not (List.exists (eq_type ty) tl)) in
31773143 let tl1' = remq tl2 tl1 and tl2' = remq tl1 tl2 in
31783144 (* PR#6744 *)
31793145 let (tlu1,tl1') = List.partition (has_free_univars !env) tl1'
···31873153 occur_univar_for Unify !env tu
31883154 end;
31893155 (* Is this handling of levels really principal? *)
31903190- List.iter (fun ty ->
31913191- let rm = repr rm2 in
31923192- update_level_for Unify !env rm.level ty;
31933193- update_scope_for Unify rm.scope ty;
31943194- ) tl1';
31953195- List.iter (fun ty ->
31963196- let rm = repr rm1 in
31973197- update_level_for Unify !env rm.level ty;
31983198- update_scope_for Unify rm.scope ty;
31993199- ) tl2';
31563156+ let update_levels rm =
31573157+ List.iter
31583158+ (fun ty ->
31593159+ update_level_for Unify !env (get_level rm) ty;
31603160+ update_scope_for Unify (get_scope rm) ty)
31613161+ in
31623162+ update_levels rm2 tl1';
31633163+ update_levels rm1 tl2';
32003164 let e = ref None in
32013165 let f1' = Reither(c1 || c2, tl2', m1 || m2, e)
32023166 and f2' = Reither(c1 || c2, tl1', m1 || m2, e) in
···32093173 | Reither(false, tl, _, e1), Rpresent(Some t2) ->
32103174 if_not_fixed first (fun () ->
32113175 set_row_field e1 f2;
32123212- let rm = repr rm1 in
32133213- update_level_for Unify !env rm.level t2;
32143214- update_scope_for Unify rm.scope t2;
31763176+ update_level_for Unify !env (get_level rm1) t2;
31773177+ update_scope_for Unify (get_scope rm1) t2;
32153178 (try List.iter (fun t1 -> unify env t1 t2) tl
32163179 with exn -> e1 := None; raise exn)
32173180 )
32183181 | Rpresent(Some t1), Reither(false, tl, _, e2) ->
32193182 if_not_fixed second (fun () ->
32203183 set_row_field e2 f1;
32213221- let rm = repr rm2 in
32223222- update_level_for Unify !env rm.level t1;
32233223- update_scope_for Unify rm.scope t1;
31843184+ update_level_for Unify !env (get_level rm2) t1;
31853185+ update_scope_for Unify (get_scope rm2) t1;
32243186 (try List.iter (unify env t1) tl
32253187 with exn -> e2 := None; raise exn)
32263188 )
···32583220 raise e
3259322132603222let unify_var env t1 t2 =
32613261- let t1 = repr t1 and t2 = repr t2 in
32623262- if t1 == t2 then () else
32633263- match t1.desc, t2.desc with
32233223+ if eq_type t1 t2 then () else
32243224+ match get_desc t1, get_desc t2 with
32643225 Tvar _, Tconstr _ when deep_occur t1 t2 ->
32653226 unify (ref env) t1 t2
32663227 | Tvar _, _ ->
32673228 let reset_tracing = check_trace_gadt_instances env in
32683229 begin try
32693230 occur_for Unify env t1 t2;
32703270- update_level_for Unify env t1.level t2;
32713271- update_scope_for Unify t1.scope t2;
32313231+ update_level_for Unify env (get_level t1) t2;
32323232+ update_scope_for Unify (get_scope t1) t2;
32723233 link_type t1 t2;
32733234 reset_trace_gadt_instances reset_tracing;
32743235 with Unify_trace trace ->
···33203281let filter_arrow env t l =
33213282 let function_type level =
33223283 let t1 = newvar2 level and t2 = newvar2 level in
33233323- let t' = newty2 level (Tarrow (l, t1, t2, Cok)) in
32843284+ let t' = newty2 ~level (Tarrow (l, t1, t2, Cok)) in
33243285 t', t1, t2
33253286 in
33263287 let t =
33273288 try expand_head_trace env t
33283289 with Unify_trace trace ->
33293329- let t', _, _ = function_type t.level in
32903290+ let t', _, _ = function_type (get_level t) in
33303291 raise (Filter_arrow_failed
33313292 (Unification_error
33323293 (expand_to_unification_error
33333294 env
33343295 (Diff { got = t'; expected = t } :: trace))))
33353296 in
33363336- match t.desc with
32973297+ match get_desc t with
33373298 | Tvar _ ->
33383338- let t', t1, t2 = function_type t.level in
32993299+ let t', t1, t2 = function_type (get_level t) in
33393300 link_type t t';
33403301 (t1, t2)
33413302 | Tarrow(l', t1, t2, _) ->
···33583319let rec filter_method_field env name priv ty =
33593320 let method_type level =
33603321 let ty1 = newvar2 level and ty2 = newvar2 level in
33613361- let ty' = newty2 level (Tfield (name,
33223322+ let ty' = newty2 ~level (Tfield (name,
33623323 begin match priv with
33633324 Private -> Fvar (ref None)
33643325 | Public -> Fpresent
···33703331 let ty =
33713332 try expand_head_trace env ty
33723333 with Unify_trace trace ->
33733373- let ty', _ = method_type ty.level in
33343334+ let ty', _ = method_type (get_level ty) in
33743335 raise (Filter_method_failed
33753336 (Unification_error
33763337 (expand_to_unification_error
33773338 env
33783339 (Diff { got = ty; expected = ty' } :: trace))))
33793340 in
33803380- match ty.desc with
33413341+ match get_desc ty with
33813342 | Tvar _ ->
33823382- let ty', ty1 = method_type ty.level in
33433343+ let ty', ty1 = method_type (get_level ty) in
33833344 link_type ty ty';
33843345 ty1
33853346 | Tfield(n, kind, ty1, ty2) ->
···34063367 let ty =
34073368 try expand_head_trace env ty
34083369 with Unify_trace trace ->
34093409- let ty', _ = object_type ~level:ty.level ~scope:ty.scope in
33703370+ let ty', _ = object_type ~level:(get_level ty) ~scope:(get_scope ty) in
34103371 raise (Filter_method_failed
34113372 (Unification_error
34123373 (expand_to_unification_error
34133374 env
34143375 (Diff { got = ty; expected = ty' } :: trace))))
34153376 in
34163416- match ty.desc with
33773377+ match get_desc ty with
34173378 | Tvar _ ->
34183418- let ty', ty_meth = object_type ~level:ty.level ~scope:ty.scope in
33793379+ let ty', ty_meth =
33803380+ object_type ~level:(get_level ty) ~scope:(get_scope ty) in
34193381 link_type ty ty';
34203382 ty_meth
34213383 | Tobject(f, _) ->
···34463408*)
34473409let moregen_occur env level ty =
34483410 let rec occur ty =
34493449- let ty = repr ty in
34503450- if ty.level <= level then () else
34513451- if is_Tvar ty && ty.level >= generic_level - 1 then raise Occur else
34113411+ let lv = get_level ty in
34123412+ if lv <= level then () else
34133413+ if is_Tvar ty && lv >= generic_level - 1 then raise Occur else
34523414 if try_mark_node ty then iter_type_expr occur ty
34533415 in
34543416 begin try
···34613423 update_level_for Moregen env level ty
3462342434633425let may_instantiate inst_nongen t1 =
34643464- if inst_nongen then t1.level <> generic_level - 1
34653465- else t1.level = generic_level
34263426+ let level = get_level t1 in
34273427+ if inst_nongen then level <> generic_level - 1
34283428+ else level = generic_level
3466342934673430let rec moregen inst_nongen type_pairs env t1 t2 =
34683468- if t1 == t2 then () else
34693469- let t1 = repr t1 in
34703470- let t2 = repr t2 in
34713471- if t1 == t2 then () else
34313431+ if eq_type t1 t2 then () else
34323432+34723433 try
34733473- match (t1.desc, t2.desc) with
34743474- | (Tvar _, _) when may_instantiate inst_nongen t1 ->
34753475- moregen_occur env t1.level t2;
34763476- update_scope_for Moregen t1.scope t2;
34343434+ match (get_desc t1, get_desc t2) with
34353435+ (Tvar _, _) when may_instantiate inst_nongen t1 ->
34363436+ moregen_occur env (get_level t1) t2;
34373437+ update_scope_for Moregen (get_scope t1) t2;
34773438 occur_for Moregen env t1 t2;
34783439 link_type t1 t2
34793440 | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
···34823443 let t1' = expand_head env t1 in
34833444 let t2' = expand_head env t2 in
34843445 (* Expansion may have changed the representative of the types... *)
34853485- let t1' = repr t1' and t2' = repr t2' in
34863486- if t1' == t2' then () else
34463446+ if eq_type t1' t2' then () else
34873447 begin try
34883448 TypePairs.find type_pairs (t1', t2')
34893449 with Not_found ->
34903450 TypePairs.add type_pairs (t1', t2') ();
34913491- match (t1'.desc, t2'.desc) with
34513451+ match (get_desc t1', get_desc t2') with
34923452 (Tvar _, _) when may_instantiate inst_nongen t1' ->
34933493- moregen_occur env t1'.level t2;
34943494- update_scope_for Moregen t1'.scope t2;
34533453+ moregen_occur env (get_level t1') t2;
34543454+ update_scope_for Moregen (get_scope t1') t2;
34953455 link_type t1' t2
34963456 | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
34973457 || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
···35053465 | (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
35063466 begin try
35073467 unify_package env (moregen_list inst_nongen type_pairs env)
35083508- t1'.level p1 fl1 t2'.level p2 fl2
34683468+ (get_level t1') p1 fl1 (get_level t2') p2 fl2
35093469 with Not_found -> raise_unexplained_for Moregen
35103470 end
35113471 | (Tnil, Tconstr _ ) -> raise_for Moregen (Obj (Abstract_row Second))
···35153475 | (Tobject (fi1, _nm1), Tobject (fi2, _nm2)) ->
35163476 moregen_fields inst_nongen type_pairs env fi1 fi2
35173477 | (Tfield _, Tfield _) -> (* Actually unused *)
35183518- moregen_fields inst_nongen type_pairs env t1' t2'
34783478+ moregen_fields inst_nongen type_pairs env
34793479+ t1' t2'
35193480 | (Tnil, Tnil) ->
35203481 ()
35213482 | (Tpoly (t1, []), Tpoly (t2, [])) ->
···35473508 | [] -> ()
35483509 end;
35493510 moregen inst_nongen type_pairs env rest1
35503550- (build_fields (repr ty2).level miss2 rest2);
35513551-35113511+ (build_fields (get_level ty2) miss2 rest2);
35523512 List.iter
35533513 (fun (name, k1, t1, k2, t2) ->
35543514 (* The below call should never throw [Public_method_to_private_method] *)
···3571353135723532and moregen_row inst_nongen type_pairs env row1 row2 =
35733533 let row1 = row_repr row1 and row2 = row_repr row2 in
35743574- let rm1 = repr row1.row_more and rm2 = repr row2.row_more in
35753575- if rm1 == rm2 then () else
35343534+ let rm1 = row1.row_more and rm2 = row2.row_more in
35353535+ if eq_type rm1 rm2 then () else
35763536 let may_inst =
35773577- is_Tvar rm1 && may_instantiate inst_nongen rm1 || rm1.desc = Tnil in
35373537+ is_Tvar rm1 && may_instantiate inst_nongen rm1 || get_desc rm1 = Tnil in
35783538 let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
35793539 let r1, r2 =
35803540 if row2.row_closed then
···35903550 | _, _ :: _ -> raise_for Moregen (Variant (No_tags (First, r2)))
35913551 | _, [] -> ()
35923552 end;
35933593- let md1 = rm1.desc (* This lets us undo a following [link_type] *) in
35943594- begin match rm1.desc, rm2.desc with
35533553+ let md1 = get_desc rm1 (* This lets us undo a following [link_type] *) in
35543554+ begin match md1, get_desc rm2 with
35953555 Tunivar _, Tunivar _ ->
35963556 unify_univar_for Moregen rm1 rm2 !univar_pairs
35973557 | Tunivar _, _ | _, Tunivar _ ->
···36013561 let ext =
36023562 newgenty (Tvariant {row2 with row_fields = r2; row_name = None})
36033563 in
36043604- moregen_occur env rm1.level ext;
36053605- update_scope_for Moregen rm1.scope ext;
35643564+ moregen_occur env (get_level rm1) ext;
35653565+ update_scope_for Moregen (get_scope rm1) ext;
36063566 (* This [link_type] has to be undone if the rest of the function fails *)
36073567 link_type rm1 ext
36083568 | Tconstr _, Tconstr _ ->
···37363696(* Simpler, no? *)
3737369737383698let rec rigidify_rec vars ty =
37393739- let ty = repr ty in
37403699 if try_mark_node ty then
37413741- begin match ty.desc with
37003700+ begin match get_desc ty with
37423701 | Tvar _ ->
37433743- if not (List.memq ty !vars) then vars := ty :: !vars
37023702+ if not (TypeSet.mem ty !vars) then vars := TypeSet.add ty !vars
37443703 | Tvariant row ->
37453704 let row = row_repr row in
37463746- let more = repr row.row_more in
37053705+ let more = row.row_more in
37473706 if is_Tvar more && not (row_fixed row) then begin
37483748- let more' = newty2 more.level more.desc in
37073707+ let more' = newty2 ~level:(get_level more) (get_desc more) in
37493708 let row' =
37503709 {row with row_fixed=Some Rigid; row_fields=[]; row_more=more'}
37513751- in link_type more (newty2 ty.level (Tvariant row'))
37103710+ in link_type more (newty2 ~level:(get_level ty) (Tvariant row'))
37523711 end;
37533712 iter_row (rigidify_rec vars) row;
37543713 (* only consider the row variable if the variant is not static *)
37553755- if not (static_row row) then rigidify_rec vars (row_more row)
37143714+ if not (static_row row) then
37153715+ rigidify_rec vars (row_more row)
37563716 | _ ->
37573717 iter_type_expr (rigidify_rec vars) ty
37583718 end
3759371937603720let rigidify ty =
37613761- let vars = ref [] in
37213721+ let vars = ref TypeSet.empty in
37623722 rigidify_rec vars ty;
37633723 unmark_type ty;
37643764- !vars
37243724+ TypeSet.elements !vars
3765372537663726let all_distinct_vars env vars =
37673767- let tyl = ref [] in
37273727+ let tys = ref TypeSet.empty in
37683728 List.for_all
37693729 (fun ty ->
37703730 let ty = expand_head env ty in
37713771- if List.memq ty !tyl then false else
37723772- (tyl := ty :: !tyl; is_Tvar ty))
37313731+ if TypeSet.mem ty !tys then false else
37323732+ (tys := TypeSet.add ty !tys; is_Tvar ty))
37733733 vars
3774373437753735let matches ~expand_error_trace env ty ty' =
···38073767 let ty' = expand_head env ty in
38083768 rigid_variants := old; ty'
3809376938103810-let normalize_subst subst =
37703770+let eqtype_subst type_pairs subst t1 t2 =
38113771 if List.exists
38123812- (function {desc=Tlink _}, _ | _, {desc=Tlink _} -> true | _ -> false)
37723772+ (fun (t,t') ->
37733773+ let found1 = eq_type t1 t in
37743774+ let found2 = eq_type t2 t' in
37753775+ if found1 && found2 then true else
37763776+ if found1 || found2 then raise_unexplained_for Equality else false)
38133777 !subst
38143814- then subst := List.map (fun (t1,t2) -> repr t1, repr t2) !subst
37783778+ then ()
37793779+ else begin
37803780+ subst := (t1, t2) :: !subst;
37813781+ TypePairs.add type_pairs (t1, t2) ()
37823782+ end
3815378338163784let rec eqtype rename type_pairs subst env t1 t2 =
38173817- if t1 == t2 then () else
38183818- let t1 = repr t1 in
38193819- let t2 = repr t2 in
38203820- if t1 == t2 then () else
37853785+ if eq_type t1 t2 then () else
3821378638223787 try
38233823- match (t1.desc, t2.desc) with
38243824- | (Tvar _, Tvar _) when rename ->
38253825- begin try
38263826- normalize_subst subst;
38273827- if List.assq t1 !subst != t2 then raise_unexplained_for Equality
38283828- with Not_found ->
38293829- if List.exists (fun (_, t) -> t == t2) !subst then
38303830- raise_unexplained_for Equality;
38313831- subst := (t1, t2) :: !subst
38323832- end
37883788+ match (get_desc t1, get_desc t2) with
37893789+ (Tvar _, Tvar _) when rename ->
37903790+ eqtype_subst type_pairs subst t1 t2
38333791 | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
38343792 ()
38353793 | _ ->
38363794 let t1' = expand_head_rigid env t1 in
38373795 let t2' = expand_head_rigid env t2 in
38383796 (* Expansion may have changed the representative of the types... *)
38393839- let t1' = repr t1' and t2' = repr t2' in
38403840- if t1' == t2' then () else
37973797+ if eq_type t1' t2' then () else
38413798 begin try
38423799 TypePairs.find type_pairs (t1', t2')
38433800 with Not_found ->
38443801 TypePairs.add type_pairs (t1', t2') ();
38453845- match (t1'.desc, t2'.desc) with
38463846- | (Tvar _, Tvar _) when rename ->
38473847- begin try
38483848- normalize_subst subst;
38493849- if List.assq t1' !subst != t2' then
38503850- raise_unexplained_for Equality
38513851- with Not_found ->
38523852- if List.exists (fun (_, t) -> t == t2') !subst then
38533853- raise_unexplained_for Equality;
38543854- subst := (t1', t2') :: !subst
38553855- end
38023802+ match (get_desc t1', get_desc t2') with
38033803+ (Tvar _, Tvar _) when rename ->
38043804+ eqtype_subst type_pairs subst t1' t2'
38563805 | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
38573806 || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
38583807 eqtype rename type_pairs subst env t1 t2;
···38653814 | (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
38663815 begin try
38673816 unify_package env (eqtype_list rename type_pairs subst env)
38683868- t1'.level p1 fl1 t2'.level p2 fl2
38173817+ (get_level t1') p1 fl1 (get_level t2') p2 fl2
38693818 with Not_found -> raise_unexplained_for Equality
38703819 end
38713820 | (Tnil, Tconstr _ ) ->
···38773826 | (Tobject (fi1, _nm1), Tobject (fi2, _nm2)) ->
38783827 eqtype_fields rename type_pairs subst env fi1 fi2
38793828 | (Tfield _, Tfield _) -> (* Actually unused *)
38803880- eqtype_fields rename type_pairs subst env t1' t2'
38293829+ eqtype_fields rename type_pairs subst env
38303830+ t1' t2'
38813831 | (Tnil, Tnil) ->
38823832 ()
38833833 | (Tpoly (t1, []), Tpoly (t2, [])) ->
···39033853 let (fields2, rest2) = flatten_fields ty2 in
39043854 (* First check if same row => already equal *)
39053855 let same_row =
39063906- rest1 == rest2 || TypePairs.mem type_pairs (rest1,rest2) ||
39073907- (rename && List.mem (rest1, rest2) !subst)
38563856+ eq_type rest1 rest2 || TypePairs.mem type_pairs (rest1,rest2)
39083857 in
39093858 if same_row then () else
39103859 (* Try expansion, needed when called from Includecore.type_manifest *)
39113911- match expand_head_rigid env rest2 with
39123912- {desc=Tobject(ty2,_)} -> eqtype_fields rename type_pairs subst env ty1 ty2
38603860+ match get_desc (expand_head_rigid env rest2) with
38613861+ Tobject(ty2,_) -> eqtype_fields rename type_pairs subst env ty1 ty2
39133862 | _ ->
39143863 let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
39153864 eqtype rename type_pairs subst env rest1 rest2;
···3939388839403889and eqtype_row rename type_pairs subst env row1 row2 =
39413890 (* Try expansion, needed when called from Includecore.type_manifest *)
39423942- match expand_head_rigid env (row_more row2) with
39433943- {desc=Tvariant row2} -> eqtype_row rename type_pairs subst env row1 row2
38913891+ match get_desc (expand_head_rigid env (row_more row2)) with
38923892+ Tvariant row2 -> eqtype_row rename type_pairs subst env row1 row2
39443893 | _ ->
39453894 let row1 = row_repr row1 and row2 = row_repr row2 in
39463895 let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
···40363985 let subst = ref [] in
40373986 try eqtype_list rename (TypePairs.create 11) subst env tyl1 tyl2
40383987 with Equality_trace trace ->
40394039- normalize_subst subst;
40403988 raise (Equality (expand_to_equality_error env trace !subst))
4041398940423990let is_equal env rename tyl1 tyl2 =
···40914039 end;
40924040 moregen_clty false type_pairs env cty1' cty2'
40934041 | Cty_signature sign1, Cty_signature sign2 ->
40944094- let ty1 = object_fields (repr sign1.csig_self) in
40954095- let ty2 = object_fields (repr sign2.csig_self) in
40424042+ let ty1 = object_fields sign1.csig_self in
40434043+ let ty2 = object_fields sign2.csig_self in
40964044 let (fields1, _rest1) = flatten_fields ty1
40974045 and (fields2, _rest2) = flatten_fields ty2 in
40984046 let (pairs, _miss1, _miss2) = associate_fields fields1 fields2 in
···41374085 let res =
41384086 let sign1 = signature_of_class_type patt in
41394087 let sign2 = signature_of_class_type subj in
41404140- let t1 = repr sign1.csig_self in
41414141- let t2 = repr sign2.csig_self in
40884088+ let t1 = sign1.csig_self in
40894089+ let t2 = sign2.csig_self in
41424090 TypePairs.add type_pairs (t1, t2) ();
41434091 let (fields1, rest1) = flatten_fields (object_fields t1)
41444092 and (fields2, rest2) = flatten_fields (object_fields t2) in
···4232418042334181let equal_clsig trace type_pairs subst env sign1 sign2 =
42344182 try
42354235- let ty1 = object_fields (repr sign1.csig_self) in
42364236- let ty2 = object_fields (repr sign2.csig_self) in
41834183+ let ty1 = object_fields sign1.csig_self in
41844184+ let ty2 = object_fields sign2.csig_self in
42374185 let (fields1, _rest1) = flatten_fields ty1
42384186 and (fields2, _rest2) = flatten_fields ty2 in
42394187 let (pairs, _miss1, _miss2) = associate_fields fields1 fields2 in
···42414189 (fun (lab, _k1, t1, _k2, t2) ->
42424190 begin try eqtype true type_pairs subst env t1 t2 with
42434191 Equality_trace trace ->
42444244- normalize_subst subst;
42454192 raise (Failure
42464193 [CM_Meth_type_mismatch
42474194 (lab,
···42554202 let (_, _, ty') = Vars.find lab sign1.csig_vars in
42564203 try eqtype true type_pairs subst env ty' ty
42574204 with Equality_trace trace ->
42584258- normalize_subst subst;
42594205 raise (Failure
42604206 [CM_Val_type_mismatch
42614207 (lab,
···42734219 let subst = ref [] in
42744220 let sign1 = signature_of_class_type patt_type in
42754221 let sign2 = signature_of_class_type subj_type in
42764276- let t1 = repr sign1.csig_self in
42774277- let t2 = repr sign2.csig_self in
42224222+ let t1 = sign1.csig_self in
42234223+ let t2 = sign2.csig_self in
42784224 TypePairs.add type_pairs (t1, t2) ();
42794225 let (fields1, rest1) = flatten_fields (object_fields t1)
42804226 and (fields2, rest2) = flatten_fields (object_fields t2) in
···43514297 raise (Failure [CM_Parameter_arity_mismatch (lp, ls)]);
43524298 List.iter2 (fun p s ->
43534299 try eqtype true type_pairs subst env p s with Equality_trace trace ->
43544354- normalize_subst subst;
43554300 raise (Failure
43564301 [CM_Type_parameter_mismatch
43574302 (env, expand_to_equality_error env trace !subst)]))
···44114356 let cl_abbr = Env.find_hash_type p env in
44124357 match cl_abbr.type_manifest with
44134358 Some ty ->
44144414- begin match (repr ty).desc with
43594359+ begin match get_desc ty with
44154360 Tobject(_,{contents=Some(p',_)}) when Path.same p p' -> cl_abbr, ty
44164361 | _ -> raise Not_found
44174362 end
···44204365let has_constr_row' env t =
44214366 has_constr_row (expand_abbrev env t)
4422436744234423-let rec build_subtype env visited loops posi level t =
44244424- let t = repr t in
44254425- match t.desc with
43684368+let rec build_subtype env (visited : transient_expr list)
43694369+ (loops : (int * type_expr) list) posi level t =
43704370+ match get_desc t with
44264371 Tvar _ ->
44274372 if posi then
44284373 try
44294429- let t' = List.assq t loops in
43744374+ let t' = List.assq (get_id t) loops in
44304375 warn := true;
44314376 (t', Equiv)
44324377 with Not_found ->
···44344379 else
44354380 (t, Unchanged)
44364381 | Tarrow(l, t1, t2, _) ->
44374437- if memq_warn t visited then (t, Unchanged) else
44384438- let visited = t :: visited in
43824382+ let tt = Transient_expr.repr t in
43834383+ if memq_warn tt visited then (t, Unchanged) else
43844384+ let visited = tt :: visited in
44394385 let (t1', c1) = build_subtype env visited loops (not posi) level t1 in
44404386 let (t2', c2) = build_subtype env visited loops posi level t2 in
44414387 let c = max_change c1 c2 in
44424388 if c > Unchanged then (newty (Tarrow(l, t1', t2', Cok)), c)
44434389 else (t, Unchanged)
44444390 | Ttuple tlist ->
44454445- if memq_warn t visited then (t, Unchanged) else
44464446- let visited = t :: visited in
43914391+ let tt = Transient_expr.repr t in
43924392+ if memq_warn tt visited then (t, Unchanged) else
43934393+ let visited = tt :: visited in
44474394 let tlist' =
44484395 List.map (build_subtype env visited loops posi level) tlist
44494396 in
···44534400 | Tconstr(p, tl, abbrev)
44544401 when level > 0 && generic_abbrev env p && safe_abbrev env t
44554402 && not (has_constr_row' env t) ->
44564456- let t' = repr (expand_abbrev env t) in
44034403+ let t' = expand_abbrev env t in
44574404 let level' = pred_expand level in
44584458- begin try match t'.desc with
44054405+ begin try match get_desc t' with
44594406 Tobject _ when posi && not (opened_object t') ->
44604407 let cl_abbr, body = find_cltype_for_path env p in
44614408 let ty =
···44634410 subst env !current_level Public abbrev None
44644411 cl_abbr.type_params tl body
44654412 with Cannot_subst -> assert false in
44664466- let ty = repr ty in
44674413 let ty1, tl1 =
44684468- match ty.desc with
44144414+ match get_desc ty with
44694415 Tobject(ty1,{contents=Some(p',tl1)}) when Path.same p p' ->
44704416 ty1, tl1
44714417 | _ -> raise Not_found
···44764422 if List.exists (deep_occur ty) tl1 then raise Not_found;
44774423 set_type_desc ty (Tvar None);
44784424 let t'' = newvar () in
44794479- let loops = (ty, t'') :: loops in
44254425+ let loops = (get_id ty, t'') :: loops in
44804426 (* May discard [visited] as level is going down *)
44814427 let (ty1', c) =
44824482- build_subtype env [t'] loops posi (pred_enlarge level') ty1 in
44284428+ build_subtype env [Transient_expr.repr t']
44294429+ loops posi (pred_enlarge level') ty1 in
44834430 assert (is_Tvar t'');
44844431 let nm =
44854432 if c > Equiv || deep_occur ty ty1' then None else Some(p,tl1) in
44864433 set_type_desc t'' (Tobject (ty1', ref nm));
44874434 (try unify_var env ty t with Unify _ -> assert false);
44884488- (t'', Changed)
44354435+ ( t'', Changed)
44894436 | _ -> raise Not_found
44904437 with Not_found ->
44914491- let (t'',c) = build_subtype env visited loops posi level' t' in
44384438+ let (t'',c) =
44394439+ build_subtype env visited loops posi level' t' in
44924440 if c > Unchanged then (t'',c)
44934441 else (t, Unchanged)
44944442 end
44954443 | Tconstr(p, tl, _abbrev) ->
44964444 (* Must check recursion on constructors, since we do not always
44974445 expand them *)
44984498- if memq_warn t visited then (t, Unchanged) else
44994499- let visited = t :: visited in
44464446+ let tt = Transient_expr.repr t in
44474447+ if memq_warn tt visited then (t, Unchanged) else
44484448+ let visited = tt :: visited in
45004449 begin try
45014450 let decl = Env.find_type p env in
45024451 if level = 0 && generic_abbrev env p && safe_abbrev env t
···45224471 end
45234472 | Tvariant row ->
45244473 let row = row_repr row in
45254525- if memq_warn t visited || not (static_row row) then (t, Unchanged) else
44744474+ let tt = Transient_expr.repr t in
44754475+ if memq_warn tt visited || not (static_row row) then (t, Unchanged) else
45264476 let level' = pred_enlarge level in
45274477 let visited =
45284528- t :: if level' < level then [] else filter_visited visited in
44784478+ tt :: if level' < level then [] else filter_visited visited in
45294479 let fields = filter_row_fields false row.row_fields in
45304480 let fields =
45314481 List.map
···45534503 in
45544504 (newty (Tvariant row), Changed)
45554505 | Tobject (t1, _) ->
45564556- if memq_warn t visited || opened_object t1 then (t, Unchanged) else
45064506+ let tt = Transient_expr.repr t in
45074507+ if memq_warn tt visited || opened_object t1 then (t, Unchanged) else
45574508 let level' = pred_enlarge level in
45584509 let visited =
45594559- t :: if level' < level then [] else filter_visited visited in
45104510+ tt :: if level' < level then [] else filter_visited visited in
45604511 let (t1', c) = build_subtype env visited loops posi level' t1 in
45614512 if c > Unchanged then (newty (Tobject (t1', ref None)), c)
45624513 else (t, Unchanged)
···46134564 ~unification_trace))
4614456546154566let rec subtype_rec env trace t1 t2 cstrs =
46164616- let t1 = repr t1 in
46174617- let t2 = repr t2 in
46184618- if t1 == t2 then cstrs else
45674567+ if eq_type t1 t2 then cstrs else
4619456846204569 begin try
46214570 TypePairs.find subtypes (t1, t2);
46224571 cstrs
46234572 with Not_found ->
46244573 TypePairs.add subtypes (t1, t2) ();
46254625- match (t1.desc, t2.desc) with
45744574+ match (get_desc t1, get_desc t2) with
46264575 (Tvar _, _) | (_, Tvar _) ->
46274576 (trace, t1, t2, !univar_pairs)::cstrs
46284577 | (Tarrow(l1, t1, u1, _), Tarrow(l2, t2, u2, _)) when l1 = l2
···46574606 let (co, cn) = Variance.get_upper v in
46584607 if co then
46594608 if cn then
46604660- (trace, newty2 t1.level (Ttuple[t1]),
46614661- newty2 t2.level (Ttuple[t2]), !univar_pairs) :: cstrs
46094609+ (trace, newty2 ~level:(get_level t1) (Ttuple[t1]),
46104610+ newty2 ~level:(get_level t2) (Ttuple[t2]), !univar_pairs)
46114611+ :: cstrs
46624612 else
46634613 subtype_rec
46644614 env
···47094659 end
47104660 | (Tpackage (p1, fl1), Tpackage (p2, fl2)) ->
47114661 begin try
47124712- let ntl1 = complete_type_list env fl2 t1.level (Mty_ident p1) fl1
47134713- and ntl2 = complete_type_list env fl1 t2.level (Mty_ident p2) fl2
46624662+ let ntl1 =
46634663+ complete_type_list env fl2 (get_level t1) (Mty_ident p1) fl1
46644664+ and ntl2 =
46654665+ complete_type_list env fl1 (get_level t2) (Mty_ident p2) fl2
47144666 ~allow_absent:true in
47154667 let cstrs' =
47164668 List.map
···47524704 let (fields2, rest2) = flatten_fields ty2 in
47534705 let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
47544706 let cstrs =
47554755- if rest2.desc = Tnil then cstrs else
47074707+ if get_desc rest2 = Tnil then cstrs else
47564708 if miss1 = [] then
47574709 subtype_rec
47584710 env
···47604712 rest1 rest2
47614713 cstrs
47624714 else
47634763- (trace, build_fields (repr ty1).level miss1 rest1, rest2,
47154715+ (trace, build_fields (get_level ty1) miss1 rest1, rest2,
47644716 !univar_pairs) :: cstrs
47654717 in
47664718 let cstrs =
47674719 if miss2 = [] then cstrs else
47684768- (trace, rest1, build_fields (repr ty2).level miss2 (newvar ()),
47204720+ (trace, rest1, build_fields (get_level ty2) miss2 (newvar ()),
47694721 !univar_pairs) :: cstrs
47704722 in
47714723 List.fold_left
···47844736 merge_row_fields row1.row_fields row2.row_fields in
47854737 let r1 = if row2.row_closed then filter_row_fields false r1 else r1 in
47864738 let r2 = if row1.row_closed then filter_row_fields false r2 else r2 in
47874787- let more1 = repr row1.row_more
47884788- and more2 = repr row2.row_more in
47894789- match more1.desc, more2.desc with
47394739+ let more1 = row1.row_more
47404740+ and more2 = row2.row_more in
47414741+ match get_desc more1, get_desc more2 with
47904742 Tconstr(p1,_,_), Tconstr(p2,_,_) when Path.same p1 p2 ->
47914743 subtype_rec
47924744 env
···4865481748664818(* Utility for printing. The resulting type is not used in computation. *)
48674819let rec unalias_object ty =
48684868- let ty = repr ty in
48694869- match ty.desc with
48204820+ let level = get_level ty in
48214821+ match get_desc ty with
48704822 Tfield (s, k, t1, t2) ->
48714871- newty2 ty.level (Tfield (s, k, t1, unalias_object t2))
48724872- | Tvar _ | Tnil ->
48734873- newty2 ty.level ty.desc
48234823+ newty2 ~level (Tfield (s, k, t1, unalias_object t2))
48244824+ | Tvar _ | Tnil as desc ->
48254825+ newty2 ~level desc
48744826 | Tunivar _ ->
48754827 ty
48764828 | Tconstr _ ->
48774877- newvar2 ty.level
48294829+ newvar2 level
48784830 | _ ->
48794831 assert false
4880483248814833let unalias ty =
48824882- let ty = repr ty in
48834883- match ty.desc with
48344834+ let level = get_level ty in
48354835+ match get_desc ty with
48844836 Tvar _ | Tunivar _ ->
48854837 ty
48864838 | Tvariant row ->
48874839 let row = row_repr row in
48884840 let more = row.row_more in
48894889- newty2 ty.level
48904890- (Tvariant {row with row_more = newty2 more.level more.desc})
48414841+ newty2 ~level
48424842+ (Tvariant {row with
48434843+ row_more = newty2 ~level:(get_level more) (get_desc more)})
48914844 | Tobject (ty, nm) ->
48924892- newty2 ty.level (Tobject (unalias_object ty, nm))
48934893- | _ ->
48944894- newty2 ty.level ty.desc
48454845+ newty2 ~level (Tobject (unalias_object ty, nm))
48464846+ | desc ->
48474847+ newty2 ~level desc
4895484848964849(* Return the arity (as for curried functions) of the given type. *)
48974850let rec arity ty =
48984898- match (repr ty).desc with
48514851+ match get_desc ty with
48994852 Tarrow(_, _t1, t2, _) -> 1 + arity t2
49004853 | _ -> 0
49014854···49044857let visited = ref TypeSet.empty
4905485849064859let rec closed_schema_rec env ty =
49074907- let ty = repr ty in
49084860 if TypeSet.mem ty !visited then () else begin
49094861 visited := TypeSet.add ty !visited;
49104910- match ty.desc with
49114911- Tvar _ when ty.level <> generic_level ->
48624862+ match get_desc ty with
48634863+ Tvar _ when get_level ty <> generic_level ->
49124864 raise Non_closed0
49134865 | Tconstr _ ->
49144866 let old = !visited in
49154867 begin try iter_type_expr (closed_schema_rec env) ty
49164868 with Non_closed0 -> try
49174869 visited := old;
49184918- closed_schema_rec env (try_expand_head try_expand_safe env ty)
48704870+ closed_schema_rec env
48714871+ (try_expand_head try_expand_safe env ty)
49194872 with Cannot_expand ->
49204873 raise Non_closed0
49214874 end
···49454898(* Normalize a type before printing, saving... *)
49464899(* Cannot use mark_type because deep_occur uses it too *)
49474900let rec normalize_type_rec visited ty =
49484948- let ty = repr ty in
49494901 if not (TypeSet.mem ty !visited) then begin
49504902 visited := TypeSet.add ty !visited;
49514903 let tm = row_of_type ty in
49524904 begin if not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm then
49534953- match tm.desc with (* PR#7348 *)
49054905+ match get_desc tm with (* PR#7348 *)
49544906 Tconstr (Path.Pdot(m,i), tl, _abbrev) ->
49554907 let i' = String.sub i 0 (String.length i - 4) in
49564908 set_type_desc ty (Tconstr(Path.Pdot(m,i'), tl, ref Mnil))
49574909 | _ -> assert false
49584958- else match ty.desc with
49104910+ else match get_desc ty with
49594911 | Tvariant row ->
49604912 let row = row_repr row in
49614913 let fields = List.map
···49884940 if deep_occur ty (newgenty (Ttuple l)) then
49894941 (* The abbreviation may be hiding something, so remove it *)
49904942 set_name nm None
49914991- else let v' = repr v in
49924992- begin match v'.desc with
49934993- | Tvar _ | Tunivar _ ->
49944994- if v' != v then set_name nm (Some (n, v' :: l))
49954995- | Tnil ->
49964996- set_type_desc ty (Tconstr (n, l, ref Mnil))
49974997- | _ -> set_name nm None
49434943+ else
49444944+ begin match get_desc v with
49454945+ | Tvar _ | Tunivar _ -> ()
49464946+ | Tnil -> set_type_desc ty (Tconstr (n, l, ref Mnil))
49474947+ | _ -> set_name nm None
49984948 end
49994949 | _ ->
50004950 fatal_error "Ctype.normalize_type_rec"
50014951 end;
50025002- let fi = repr fi in
50035003- if fi.level < lowest_level then () else
49524952+ let level = get_level fi in
49534953+ if level < lowest_level then () else
50044954 let fields, row = flatten_fields fi in
50055005- let fi' = build_fields fi.level fields row in
50065006- set_type_desc fi fi'.desc
49554955+ let fi' = build_fields level fields row in
49564956+ set_type_desc fi (get_desc fi')
50074957 | _ -> ()
50084958 end;
50094959 iter_type_expr (normalize_type_rec visited) ty
···50354985 if expand_private then try_expand_safe_opt env t
50364986 else try_expand_safe env t
50374987 in
50385038- match ty.desc with
49884988+ match get_desc ty with
50394989 Tvar _ | Tunivar _ -> ty
50405040- | Tlink ty -> nondep_type_rec env ids ty
50414990 | _ -> try TypeHash.find nondep_hash ty
50424991 with Not_found ->
50435043- let ty' = newgenvar () in (* Stub *)
49924992+ let ty' = newgenstub ~scope:(get_scope ty) in
50444993 TypeHash.add nondep_hash ty ty';
50455045- set_type_desc ty'
50465046- begin match ty.desc with
50475047- | Tconstr(p, tl, _abbrev) ->
49944994+ let desc =
49954995+ match get_desc ty with
49964996+ | Tconstr(p, tl, _abbrev) as desc ->
50484997 begin try
50494998 (* First, try keeping the same type constructor p *)
50504999 match Path.find_free_opt ids p with
···50555004 with (Nondep_cannot_erase _) as exn ->
50565005 (* If that doesn't work, try expanding abbrevs *)
50575006 try Tlink (nondep_type_rec ~expand_private env ids
50585058- (try_expand env (newty2 ty.level ty.desc)))
50075007+ (try_expand env (newty2 ~level:(get_level ty) desc)))
50595008 (*
50605009 The [Tlink] is important. The expanded type may be a
50615010 variable, or may not be completely copied yet
···50815030 else Some (p, List.map (nondep_type_rec env ids) tl)))
50825031 | Tvariant row ->
50835032 let row = row_repr row in
50845084- let more = repr row.row_more in
50335033+ let more = row.row_more in
50855034 (* We must keep sharing according to the row variable *)
50865035 begin try
50875036 let ty2 = TypeHash.find nondep_variants more in
···51035052 Tvariant {row with row_name = None}
51045053 | _ -> Tvariant row
51055054 end
51065106- | _ -> copy_type_desc (nondep_type_rec env ids) ty.desc
51075107- end;
50555055+ | desc -> copy_type_desc (nondep_type_rec env ids) desc
50565056+ in
50575057+ Transient_expr.set_stub_desc ty' desc;
51085058 ty'
5109505951105060let nondep_type env id ty =
···51735123 newgenty (Tconstr(ext.ext_type_path, ext.ext_type_params, ref Mnil))
51745124 in
51755125 let ty' = nondep_type_rec env ids ty in
51765176- match (repr ty').desc with
51265126+ match get_desc ty' with
51775127 Tconstr(p, tl, _) -> p, tl
51785128 | _ -> raise (Nondep_cannot_erase id)
51795129 end
···5260521052615211(* collapse conjunctive types in class parameters *)
52625212let rec collapse_conj env visited ty =
52635263- let ty = repr ty in
52645264- if List.memq ty visited then () else
52655265- let visited = ty :: visited in
52665266- match ty.desc with
52135213+ let id = get_id ty in
52145214+ if List.memq id visited then () else
52155215+ let visited = id :: visited in
52165216+ match get_desc ty with
52675217 Tvariant row ->
52685218 let row = row_repr row in
52695219 List.iter
···52855235let same_constr env t1 t2 =
52865236 let t1 = expand_head env t1 in
52875237 let t2 = expand_head env t2 in
52885288- match t1.desc, t2.desc with
52385238+ match get_desc t1, get_desc t2 with
52895239 | Tconstr (p1, _, _), Tconstr (p2, _, _) -> Path.same p1 p2
52905240 | _ -> false
52915241···53015251 !Clflags.native_code && Sys.word_size = 64
5302525253035253let immediacy env typ =
53045304- match (repr typ).desc with
52545254+ match get_desc typ with
53055255 | Tconstr(p, _args, _abbrev) ->
53065256 begin try
53075257 let type_decl = Env.find_type p env in
+1-6
typing/ctype.mli
···1818open Asttypes
1919open Types
20202121-module TypePairs : Hashtbl.S with type key = type_expr * type_expr
2222-2321exception Unify of Errortrace.unification_error
2422exception Equality of Errortrace.equality_error
2523exception Moregen of Errortrace.moregen_error
···6765val newconstr: Path.t -> type_expr list -> type_expr
6866val none: type_expr
6967 (* A dummy type expression *)
7070-7171-val repr: type_expr -> type_expr
7272- (* Return the canonical representative of a type. *)
73687469val object_fields: type_expr -> type_expr
7570val flatten_fields:
···225220 (* Unify the two types given. Raise [Unify] if not possible. *)
226221val unify_gadt:
227222 equations_level:int -> allow_recursive:bool ->
228228- Env.t ref -> type_expr -> type_expr -> unit TypePairs.t
223223+ Env.t ref -> type_expr -> type_expr -> unit Btype.TypePairs.t
229224 (* Unify the two types given and update the environment with the
230225 local constraints. Raise [Unify] if not possible.
231226 Returns the pairs of types that have been equated. *)
+9-12
typing/datarepr.ml
···2424let free_vars ?(param=false) ty =
2525 let ret = ref TypeSet.empty in
2626 let rec loop ty =
2727- let ty = repr ty in
2827 if try_mark_node ty then
2929- match ty.desc with
2828+ match get_desc ty with
3029 | Tvar _ ->
3130 ret := TypeSet.add ty !ret
3231 | Tvariant row ->
3332 let row = row_repr row in
3433 iter_row loop row;
3534 if not (static_row row) then begin
3636- match row.row_more.desc with
3535+ match get_desc row.row_more with
3736 | Tvar _ when param -> ret := TypeSet.add ty !ret
3837 | _ -> loop row.row_more
3938 end
···95949695let constructor_descrs ~current_unit ty_path decl cstrs rep =
9796 let ty_res = newgenconstr ty_path decl.type_params in
9898- let num_consts = ref 0 and num_nonconsts = ref 0 and num_normal = ref 0 in
9797+ let num_consts = ref 0 and num_nonconsts = ref 0 in
9998 List.iter
100100- (fun {cd_args; cd_res; _} ->
101101- if cd_args = Cstr_tuple [] then incr num_consts else incr num_nonconsts;
102102- if cd_res = None then incr num_normal)
9999+ (fun {cd_args; _} ->
100100+ if cd_args = Cstr_tuple [] then incr num_consts else incr num_nonconsts)
103101 cstrs;
104102 let rec describe_constructors idx_const idx_nonconst = function
105103 [] -> []
···139137 cstr_tag = tag;
140138 cstr_consts = !num_consts;
141139 cstr_nonconsts = !num_nonconsts;
142142- cstr_normal = !num_normal;
143140 cstr_private = decl.type_private;
144141 cstr_generalized = cd_res <> None;
145142 cstr_loc = cd_loc;
···169166 cstr_consts = -1;
170167 cstr_nonconsts = -1;
171168 cstr_private = ext.ext_private;
172172- cstr_normal = -1;
173169 cstr_generalized = ext.ext_ret_type <> None;
174170 cstr_loc = ext.ext_loc;
175171 cstr_attributes = ext.ext_attributes;
···177173 cstr_uid = ext.ext_uid;
178174 }
179175180180-let none = Private_type_expr.create (Ttuple [])
181181- ~level:(-1) ~scope:Btype.generic_level ~id:(-1)
182182- (* Clearly ill-formed type *)
176176+let none =
177177+ create_expr (Ttuple []) ~level:(-1) ~scope:Btype.generic_level ~id:(-1)
178178+ (* Clearly ill-formed type *)
179179+183180let dummy_label =
184181 { lbl_name = ""; lbl_res = none; lbl_arg = none; lbl_mut = Immutable;
185182 lbl_pos = (-1); lbl_all = [||]; lbl_repres = Record_regular;
+6-7
typing/env.ml
···2121open Longident
2222open Path
2323open Types
2424-open Btype
25242625open Local_store
2726···13401339 let memo = Hashtbl.create 16 in
13411340 let copy t =
13421341 try
13431343- Hashtbl.find memo t.id
13421342+ Hashtbl.find memo (get_id t)
13441343 with Not_found ->
13451344 let t2 = Subst.type_expr Subst.identity t in
13461346- Hashtbl.add memo t.id t2;
13451345+ Hashtbl.add memo (get_id t) t2;
13471346 t2
13481347 in
13491348 let f = function
···2419241824202419let mark_constructor_description_used usage env cstr =
24212420 let ty_path =
24222422- match repr cstr.cstr_res with
24232423- | {desc=Tconstr(path, _, _)} -> path
24212421+ match get_desc cstr.cstr_res with
24222422+ | Tconstr(path, _, _) -> path
24242423 | _ -> assert false
24252424 in
24262425 mark_type_path_used env ty_path;
···2430242924312430let mark_label_description_used usage env lbl =
24322431 let ty_path =
24332433- match repr lbl.lbl_res with
24342434- | {desc=Tconstr(path, _, _)} -> path
24322432+ match get_desc lbl.lbl_res with
24332433+ | Tconstr(path, _, _) -> path
24352434 | _ -> assert false
24362435 in
24372436 mark_type_path_used env ty_path;
+8-8
typing/includecore.ml
···101101(* Inclusion between manifest types (particularly for private row types) *)
102102103103let is_absrow env ty =
104104- match ty.desc with
105105- | Tconstr(Pident _, _, _) -> begin
104104+ match get_desc ty with
105105+ | Tconstr(Pident _, _, _) ->
106106 (* This function is checking for an abstract row on the side that is being
107107 included into (usually numbered with "2" in this file). In this case,
108108 the abstract row variable has been subsituted for an object or variant
109109 type. *)
110110- match Ctype.expand_head env ty with
111111- | {desc=Tobject _|Tvariant _} -> true
110110+ begin match get_desc (Ctype.expand_head env ty) with
111111+ | Tobject _|Tvariant _ -> true
112112 | _ -> false
113113 end
114114 | _ -> false
···524524 match decl1.type_manifest with
525525 | Some ty1 -> begin
526526 let ty1 = Ctype.expand_head env ty1 in
527527- match ty1.desc with
527527+ match get_desc ty1 with
528528 | Tvariant row when Btype.is_constr_row ~allow_ident:true
529529 (Btype.row_more row) ->
530530 Some Private_row_type
···634634635635let type_manifest env ty1 params1 ty2 params2 priv2 kind2 =
636636 let ty1' = Ctype.expand_head env ty1 and ty2' = Ctype.expand_head env ty2 in
637637- match ty1'.desc, ty2'.desc with
637637+ match get_desc ty1', get_desc ty2' with
638638 | Tvariant row1, Tvariant row2
639639 when is_absrow env (Btype.row_more row2) -> begin
640640 let row1 = Btype.row_repr row1 and row2 = Btype.row_repr row2 in
···657657 match priv2, kind2 with
658658 | Private, Type_abstract -> begin
659659 (* Same checks as the [when] guards from above, inverted *)
660660- match ty2'.desc with
660660+ match get_desc ty2' with
661661 | Tvariant row ->
662662 not (is_absrow env (Btype.row_more row))
663663 | Tobject (fi, _) ->
···770770 if not need_variance then None else
771771 let abstr = abstr || decl2.type_private = Private in
772772 let opn = decl2.type_kind = Type_open && decl2.type_manifest = None in
773773- let constrained ty = not (Btype.(is_Tvar (repr ty))) in
773773+ let constrained ty = not (Btype.is_Tvar ty) in
774774 if List.for_all2
775775 (fun ty (v1,v2) ->
776776 let open Variance in
+3-3
typing/mtype.ml
···518518let lower_nongen nglev mty =
519519 let open Btype in
520520 let it_type_expr it ty =
521521- let ty = repr ty in
522522- match ty with
523523- {desc=Tvar _; level} ->
521521+ match get_desc ty with
522522+ Tvar _ ->
523523+ let level = get_level ty in
524524 if level < generic_level && level > nglev then set_level ty nglev
525525 | _ ->
526526 type_iterators.it_type_expr it ty
+8-7
typing/parmatch.ml
···339339340340(* May need a clean copy, cf. PR#4745 *)
341341let clean_copy ty =
342342- if ty.level = Btype.generic_level then ty
342342+ if get_level ty = Btype.generic_level then ty
343343 else Subst.type_expr Subst.identity ty
344344345345let get_constructor_type_path ty tenv =
346346- let ty = Ctype.repr (Ctype.expand_head tenv (clean_copy ty)) in
347347- match ty.desc with
346346+ let ty = Ctype.expand_head tenv (clean_copy ty) in
347347+ match get_desc ty with
348348 | Tconstr (path,_,_) -> path
349349 | _ -> assert false
350350···724724 match Btype.row_field_repr f with
725725 | Reither(_, _, false, e) ->
726726 (* m=false means that this tag is not explicitly matched *)
727727- Btype.set_row_field e Rabsent;
727727+ set_row_field e Rabsent;
728728 None
729729 | Rabsent | Reither (_, _, true, _) | Rpresent _ -> nm)
730730 row.row_name row.row_fields in
···732732 (* this unification cannot fail *)
733733 Ctype.unify env row.row_more
734734 (Btype.newgenty
735735- (Tvariant {row with row_fields = []; row_more = Btype.newgenvar();
735735+ (Tvariant {row with row_fields = [];
736736+ row_more = Btype.newgenvar();
736737 row_closed = true; row_name = nm}))
737738 end
738739···822823823824let pats_of_type ?(always=false) env ty =
824825 let ty' = Ctype.expand_head env ty in
825825- match ty'.desc with
826826+ match get_desc ty' with
826827 | Tconstr (path, _, _) ->
827828 begin match Env.find_type_descrs path env with
828829 | exception Not_found -> [omega]
···844845 | _ -> [omega]
845846846847let rec get_variant_constructors env ty =
847847- match (Ctype.repr ty).desc with
848848+ match get_desc ty with
848849 | Tconstr (path,_,_) -> begin
849850 try match Env.find_type path env, Env.find_type_descrs path env with
850851 | _, Type_variant (cstrs,_) -> cstrs
+3-3
typing/patterns.ml
···194194 | Some a -> true, [a]
195195 in
196196 let type_row () =
197197- match Ctype.expand_head q.pat_env q.pat_type with
198198- | {desc = Tvariant type_row} -> Btype.row_repr type_row
199199- | _ -> assert false
197197+ match get_desc (Ctype.expand_head q.pat_env q.pat_type) with
198198+ | Tvariant type_row -> Btype.row_repr type_row
199199+ | _ -> assert false
200200 in
201201 Variant {tag; has_arg; cstr_row; type_row}, pats
202202 | `Array args ->
+90-90
typing/printtyp.ml
···484484 if List.memq r v then "Clink loop" else
485485 safe_commu_repr (r::v) !r
486486487487-let rec safe_repr v = function
487487+let rec safe_repr v t =
488488+ match Transient_expr.coerce t with
488489 {desc = Tlink t} when not (List.memq t v) ->
489490 safe_repr (t::v) t
490490- | t -> t
491491+ | t' -> t'
491492492493let rec list_of_memo = function
493494 Mnil -> []
···631632 the {!printing_map} one level further (see also {!Env.run_iter_cont})
632633*)
633634634634-let same_type t t' = repr t == repr t'
635635-636635let rec index l x =
637636 match l with
638637 [] -> raise Not_found
639639- | a :: l -> if x == a then 0 else 1 + index l x
638638+ | a :: l -> if eq_type x a then 0 else 1 + index l x
640639641640let rec uniq = function
642641 [] -> true
643643- | a :: l -> not (List.memq a l) && uniq l
642642+ | a :: l -> not (List.memq (a : int) l) && uniq l
644643645644let rec normalize_type_path ?(cache=false) env p =
646645 try
647646 let (params, ty, _) = Env.find_type_expansion p env in
648648- let params = List.map repr params in
649649- match repr ty with
650650- {desc = Tconstr (p1, tyl, _)} ->
651651- let tyl = List.map repr tyl in
647647+ match get_desc ty with
648648+ Tconstr (p1, tyl, _) ->
652649 if List.length params = List.length tyl
653653- && List.for_all2 (==) params tyl
650650+ && List.for_all2 eq_type params tyl
654651 then normalize_type_path ~cache env p1
655652 else if cache || List.length params <= List.length tyl
656656- || not (uniq tyl) then (p, Id)
653653+ || not (uniq (List.map get_id tyl)) then (p, Id)
657654 else
658655 let l1 = List.map (index params) tyl in
659656 let (p2, s2) = normalize_type_path ~cache env p1 in
660657 (p2, compose l1 s2)
661661- | ty ->
658658+ | _ ->
662659 (p, Nth (index params ty))
663660 with
664661 Not_found ->
···788785789786let is_non_gen mode ty =
790787 match mode with
791791- | Type_scheme -> is_Tvar ty && ty.level <> generic_level
788788+ | Type_scheme -> is_Tvar ty && get_level ty <> generic_level
792789 | Type -> false
793790794791module Names : sig
795792 val reset_names : unit -> unit
796793797797- val add_named_var : type_expr -> unit
794794+ val add_named_var : transient_expr -> unit
798795 val add_subst : (type_expr * type_expr) list -> unit
799796800800- val has_name : type_expr -> bool
797797+ val has_name : transient_expr -> bool
801798802799 val new_name : unit -> string
803800 val new_weak_name : type_expr -> unit -> string
804801805805- val name_of_type : (unit -> string) -> type_expr -> string
806806- val check_name_of_type : type_expr -> unit
802802+ val name_of_type : (unit -> string) -> transient_expr -> string
803803+ val check_name_of_type : transient_expr -> unit
807804808808- val remove_names : type_expr list -> unit
805805+ val remove_names : transient_expr list -> unit
809806810807 val with_local_names : (unit -> 'a) -> 'a
811808···817814 which maps from types to types. The lookup process is
818815 "type -> apply substitution -> find name". The substitution is presumed to
819816 be acyclic. *)
820820- let names = ref ([] : (type_expr * string) list)
821821- let name_subst = ref ([] : (type_expr * type_expr) list)
817817+ let names = ref ([] : (transient_expr * string) list)
818818+ let name_subst = ref ([] : (transient_expr * transient_expr) list)
822819 let name_counter = ref 0
823820 let named_vars = ref ([] : string list)
824821···842839 | exception Not_found -> ty
843840844841 let add_subst subst =
845845- name_subst := subst @ !name_subst
842842+ name_subst :=
843843+ List.map (fun (t1,t2) -> Transient_expr.repr t1, Transient_expr.repr t2)
844844+ subst
845845+ @ !name_subst
846846847847 let has_name ty =
848848 List.mem_assq (substitute ty) !names
···876876 of the union-find class. *)
877877 let t = substitute t in
878878 try List.assq t !names with Not_found ->
879879- try TypeMap.find t !weak_var_map with Not_found ->
879879+ try TransientTypeMap.find t !weak_var_map with Not_found ->
880880 let name =
881881 match t.desc with
882882 Tvar (Some name) | Tunivar (Some name) ->
···904904 let check_name_of_type t = ignore(name_of_type new_name t)
905905906906 let remove_names tyl =
907907- let tyl = List.map (fun ty -> substitute (repr ty)) tyl in
907907+ let tyl = List.map substitute tyl in
908908 names := List.filter (fun (ty,_) -> not (List.memq ty tyl)) !names
909909910910 let with_local_names f =
···920920921921 let refresh_weak () =
922922 let refresh t name (m,s) =
923923- if is_non_gen Type_scheme (repr t) then
923923+ if is_non_gen Type_scheme t then
924924 begin
925925 TypeMap.add t name m,
926926 String.Set.add name s
···932932 weak_var_map := m
933933end
934934935935-let visited_objects = ref ([] : type_expr list)
936936-let aliased = ref ([] : type_expr list)
937937-let delayed = ref ([] : type_expr list)
935935+let visited_objects = ref ([] : transient_expr list)
936936+let aliased = ref ([] : transient_expr list)
937937+let delayed = ref ([] : transient_expr list)
938938939939let add_delayed t =
940940 if not (List.memq t !delayed) then delayed := t :: !delayed
941941942942+let proxy ty = Transient_expr.repr (proxy ty)
943943+942944let is_aliased ty = List.memq (proxy ty) !aliased
943943-let add_alias ty =
944944- let px = proxy ty in
945945- if not (is_aliased px) then begin
945945+let add_alias_proxy px =
946946+ if not (List.memq px !aliased) then begin
946947 aliased := px :: !aliased;
947948 Names.add_named_var px
948949 end
950950+let add_alias ty = add_alias_proxy (proxy ty)
949951950952let aliasable ty =
951951- match ty.desc with
953953+ match get_desc ty with
952954 Tvar _ | Tunivar _ | Tpoly _ -> false
953955 | Tconstr (p, _, _) ->
954956 not (is_nth (snd (best_type_path p)))
···965967 row.row_fields
966968967969let rec mark_loops_rec visited ty =
968968- let ty = repr ty in
969970 let px = proxy ty in
970970- if List.memq px visited && aliasable ty then add_alias px else
971971+ if List.memq px visited && aliasable ty then add_alias_proxy px else
971972 let visited = px :: visited in
972972- match ty.desc with
973973- | Tvar _ -> Names.add_named_var ty
973973+ let tty = Transient_expr.repr ty in
974974+ match tty.desc with
975975+ | Tvar _ -> Names.add_named_var tty
974976 | Tarrow(_, ty1, ty2, _) ->
975977 mark_loops_rec visited ty1; mark_loops_rec visited ty2
976978 | Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
···980982 | Tpackage (_, fl) ->
981983 List.iter (fun (_n, ty) -> mark_loops_rec visited ty) fl
982984 | Tvariant row ->
983983- if List.memq px !visited_objects then add_alias px else
985985+ if List.memq px !visited_objects then add_alias_proxy px else
984986 begin
985987 let row = row_repr row in
986988 if not (static_row row) then
···992994 iter_row (mark_loops_rec visited) row
993995 end
994996 | Tobject (fi, nm) ->
995995- if List.memq px !visited_objects then add_alias px else
997997+ if List.memq px !visited_objects then add_alias_proxy px else
996998 begin
997999 if opened_object ty then
9981000 visited_objects := px :: !visited_objects;
···10181020 | Tpoly (ty, tyl) ->
10191021 List.iter (fun t -> add_alias t) tyl;
10201022 mark_loops_rec visited ty
10211021- | Tunivar _ -> Names.add_named_var ty
10231023+ | Tunivar _ -> Names.add_named_var tty
1022102410231025let mark_loops ty =
10241026 normalize_type ty;
···10441046let print_labels = ref true
1045104710461048let rec tree_of_typexp mode ty =
10471047- let ty = repr ty in
10481049 let px = proxy ty in
10491050 if Names.has_name px && not (List.memq px !delayed) then
10501051 let mark = is_non_gen mode ty in
···10551056 Otyp_var (mark, name) else
1056105710571058 let pr_typ () =
10581058- match ty.desc with
10591059+ let tty = Transient_expr.repr ty in
10601060+ match tty.desc with
10591061 | Tvar _ ->
10601060- (*let lev =
10611061- if is_non_gen mode ty then "/" ^ Int.to_string ty.level else "" in*)
10621062 let non_gen = is_non_gen mode ty in
10631063 let name_gen =
10641064 if non_gen then Names.new_weak_name ty else Names.new_name
10651065 in
10661066- Otyp_var (non_gen, Names.name_of_type name_gen ty)
10661066+ Otyp_var (non_gen, Names.name_of_type name_gen tty)
10671067 | Tarrow(l, ty1, ty2, _) ->
10681068 let lab =
10691069 if !print_labels || is_optional l then string_of_label l else ""
10701070 in
10711071 let t1 =
10721072 if is_optional l then
10731073- match (repr ty1).desc with
10731073+ match get_desc ty1 with
10741074 | Tconstr(path, [ty], _)
10751075 when Path.same path Predef.path_option ->
10761076 tree_of_typexp mode ty
···11101110 if row.row_closed && all_present then
11111111 out_variant
11121112 else
11131113- let non_gen = is_non_gen mode px in
11131113+ let non_gen = is_non_gen mode (Transient_expr.type_expr px) in
11141114 let tags =
11151115 if all_present then None else Some (List.map fst present) in
11161116 Otyp_variant (non_gen, Ovar_typ out_variant, row.row_closed, tags)
11171117 | _ ->
11181118 let non_gen =
11191119- not (row.row_closed && all_present) && is_non_gen mode px in
11191119+ not (row.row_closed && all_present) &&
11201120+ is_non_gen mode (Transient_expr.type_expr px) in
11201121 let fields = List.map (tree_of_row_field mode) fields in
11211122 let tags =
11221123 if all_present then None else Some (List.map fst present) in
···11371138 (*let print_names () =
11381139 List.iter (fun (_, name) -> prerr_string (name ^ " ")) !names;
11391140 prerr_string "; " in *)
11401140- let tyl = List.map repr tyl in
11411141 if tyl = [] then tree_of_typexp mode ty else begin
11421142+ let tyl = List.map Transient_expr.repr tyl in
11421143 let old_delayed = !delayed in
11431144 (* Make the names delayed, so that the real type is
11441145 printed once when used as proxy *)
···11501151 delayed := old_delayed; tr
11511152 end
11521153 | Tunivar _ ->
11531153- Otyp_var (false, Names.name_of_type Names.new_name ty)
11541154+ Otyp_var (false, Names.name_of_type Names.new_name tty)
11541155 | Tpackage (p, fl) ->
11551156 let fl =
11561157 List.map
···11611162 Otyp_module (tree_of_path Module_type p, fl)
11621163 in
11631164 if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
11641164- if is_aliased px && aliasable ty then begin
11651165+ if is_aliased (Transient_expr.type_expr px) && aliasable ty then begin
11651166 Names.check_name_of_type px;
11661167 Otyp_alias (pr_typ (), Names.name_of_type Names.new_name px) end
11671168 else pr_typ ()
···11981199 let (fields, rest) = pr_fields fi in
11991200 Otyp_object (fields, rest)
12001201 | Some (p, ty :: tyl) ->
12011201- let non_gen = is_non_gen mode (repr ty) in
12021202+ let non_gen = is_non_gen mode ty in
12021203 let args = tree_of_typlist mode tyl in
12031204 let (p', s) = best_type_path p in
12041205 assert (s = Id);
···12101211and tree_of_typfields mode rest = function
12111212 | [] ->
12121213 let rest =
12131213- match rest.desc with
12141214+ match get_desc rest with
12141215 | Tvar _ | Tunivar _ -> Some (is_non_gen mode rest)
12151216 | Tconstr _ -> Some false
12161217 | Tnil -> None
···12691270 let params =
12701271 List.fold_left
12711272 (fun tyl ty ->
12721272- let ty = repr ty in
12731273- if List.memq ty tyl then Btype.newgenty (Ttuple [ty]) :: tyl
12731273+ if List.exists (eq_type ty) tyl
12741274+ then newty2 ~level:generic_level (Ttuple [ty]) :: tyl
12741275 else ty :: tyl)
12751276 (* Two parameters might be identical due to a constraint but we need to
12761277 print them differently in order to make the output syntactically valid.
···12931294 | Some ty ->
12941295 let vars = free_variables ty in
12951296 List.iter
12961296- (function {desc = Tvar (Some "_")} as ty ->
12971297- if List.memq ty vars then set_type_desc ty (Tvar None)
12981298- | _ -> ())
12971297+ (fun ty ->
12981298+ if get_desc ty = Tvar (Some "_") && List.exists (eq_type ty) vars
12991299+ then set_type_desc ty (Tvar None))
12991300 params
13001301 | None -> ()
13011302 end;
···13091310 | Some ty ->
13101311 let ty =
13111312 (* Special hack to hide variant name *)
13121312- match repr ty with {desc=Tvariant row} ->
13131313- let row = row_repr row in
13141314- begin match row.row_name with
13151315- Some (Pident id', _) when Ident.same id id' ->
13161316- newgenty (Tvariant {row with row_name = None})
13171317- | _ -> ty
13181318- end
13131313+ match get_desc ty with
13141314+ Tvariant row ->
13151315+ let row = row_repr row in
13161316+ begin match row.row_name with
13171317+ Some (Pident id', _) when Ident.same id id' ->
13181318+ newgenty (Tvariant {row with row_name = None})
13191319+ | _ -> ty
13201320+ end
13191321 | _ -> ty
13201322 in
13211323 mark_loops ty;
···13551357 let vari =
13561358 List.map2
13571359 (fun ty v ->
13581358- let is_var = is_Tvar (repr ty) in
13601360+ let is_var = is_Tvar ty in
13591361 if abstr || not is_var then
13601362 let inj =
13611363 decl.type_kind = Type_abstract && Variance.mem Inj v &&
···15361538(* Print a class type *)
1537153915381540let method_type (_, kind, ty) =
15391539- match field_kind_repr kind, repr ty with
15401540- Fpresent, {desc=Tpoly(ty, tyl)} -> (ty, tyl)
15411541- | _ , ty -> (ty, [])
15411541+ match field_kind_repr kind, get_desc ty with
15421542+ Fpresent, Tpoly(ty, tyl) -> (ty, tyl)
15431543+ | _ , _ -> (ty, [])
1542154415431545let tree_of_metho mode concrete csil (lab, kind, ty) =
15441546 if lab <> dummy_method then begin
···15471549 let virt = not (Concr.mem lab concrete) in
15481550 let (ty, tyl) = method_type (lab, kind, ty) in
15491551 let tty = tree_of_typexp mode ty in
15501550- Names.remove_names tyl;
15521552+ Names.remove_names (List.map Transient_expr.repr tyl);
15511553 Ocsg_method (lab, priv, virt, tty) :: csil
15521554 end
15531555 else csil
···15611563 then prepare_class_type params cty
15621564 else List.iter mark_loops tyl
15631565 | Cty_signature sign ->
15641564- let sty = repr sign.csig_self in
15651566 (* Self may have a name *)
15661566- let px = proxy sty in
15671567- if List.memq px !visited_objects then add_alias sty
15671567+ let px = proxy sign.csig_self in
15681568+ if List.memq px !visited_objects then add_alias sign.csig_self
15681569 else visited_objects := px :: !visited_objects;
15691570 let (fields, _) =
15701571 Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
···15871588 let namespace = Namespace.best_class_namespace p' in
15881589 Octy_constr (tree_of_path namespace p', tree_of_typlist Type_scheme tyl)
15891590 | Cty_signature sign ->
15901590- let sty = repr sign.csig_self in
15911591+ let sty = sign.csig_self in
15911592 let self_ty =
15921593 if is_aliased sty then
15931594 Some (Otyp_var (false, Names.name_of_type Names.new_name (proxy sty)))
···16241625 in
16251626 let tr =
16261627 if is_optional l then
16271627- match (repr ty).desc with
16281628+ match get_desc ty with
16281629 | Tconstr(path, [ty], _) when Path.same path Predef.path_option ->
16291630 tree_of_typexp mode ty
16301631 | _ -> Otyp_stuff "<hidden>"
···16401641 (match tree_of_typexp Type_scheme param with
16411642 Otyp_var (_, s) -> s
16421643 | _ -> "?"),
16431643- if is_Tvar (repr param) then Asttypes.(NoVariance, NoInjectivity)
16441644- else variance
16441644+ if is_Tvar param then Asttypes.(NoVariance, NoInjectivity)
16451645+ else variance
1645164616461647let class_variance =
16471648 let open Variance in let open Asttypes in
···16731674 !Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
1674167516751676let tree_of_cltype_declaration id cl rs =
16761676- let params = List.map repr cl.clty_params in
16771677+ let params = cl.clty_params in
1677167816781679 reset_except_context ();
16791680 List.iter add_alias params;
···19551956(* Print a unification error *)
1956195719571958let same_path t t' =
19581958- let t = repr t and t' = repr t' in
19591959- t == t' ||
19601960- match t.desc, t'.desc with
19591959+ eq_type t t' ||
19601960+ match get_desc t, get_desc t' with
19611961 Tconstr(p,tl,_), Tconstr(p',tl',_) ->
19621962 let (p1, s1) = best_type_path p and (p2, s2) = best_type_path p' in
19631963 begin match s1, s2 with
···19651965 | (Id | Map _), (Id | Map _) when Path.same p1 p2 ->
19661966 let tl = apply_subst s1 tl and tl' = apply_subst s2 tl' in
19671967 List.length tl = List.length tl' &&
19681968- List.for_all2 same_type tl tl'
19681968+ List.for_all2 eq_type tl tl'
19691969 | _ -> false
19701970 end
19711971 | _ ->
···2073207320742074(* Hide variant name and var, to force printing the expanded type *)
20752075let hide_variant_name t =
20762076- match repr t with
20772077- | {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
20782078- newty2 t.level
20762076+ match get_desc t with
20772077+ | Tvariant row when (row_repr row).row_name <> None ->
20782078+ newty2 ~level:(get_level t)
20792079 (Tvariant {(row_repr row) with row_name = None;
20802080- row_more = newvar2 (row_more row).level})
20802080+ row_more = newvar2 (get_level (row_more row))})
20812081 | _ -> t
2082208220832083let prepare_expansion Errortrace.{ty; expanded} =
···20872087 Errortrace.{ty; expanded}
2088208820892089let may_prepare_expansion compact (Errortrace.{ty; expanded} as ty_exp) =
20902090- match (repr expanded).desc with
20902090+ match get_desc expanded with
20912091 Tvariant _ | Tobject _ when compact ->
20922092 mark_loops ty; Errortrace.{ty; expanded = ty}
20932093 | _ -> prepare_expansion ty_exp
···21012101 Format.pp_print_list ~pp_sep:comma print_tag
2102210221032103let is_unit env ty =
21042104- match (Ctype.expand_head env ty).desc with
21042104+ match get_desc (Ctype.expand_head env ty) with
21052105 | Tconstr (p, _, _) -> Path.same p Predef.path_unit
21062106 | _ -> false
21072107···21152115 res
2116211621172117let explanation_diff env t3 t4 : (Format.formatter -> unit) option =
21182118- match t3.desc, t4.desc with
21182118+ match get_desc t3, get_desc t4 with
21192119 | Tarrow (_, ty1, ty2, _), _
21202120 when is_unit env ty1 && unifiable env ty2 t4 ->
21212121 Some (fun ppf ->
···22452245 explain_object o
22462246 | Errortrace.Rec_occur(x,y) ->
22472247 reset_and_mark_loops y;
22482248- begin match x.desc with
22482248+ begin match get_desc x with
22492249 | Tvar _ | Tunivar _ ->
22502250 Some(dprintf "@,@[<hov>The type variable %a occurs inside@ %a@]"
22512251 type_expr x type_expr y)
···22682268 | Some explain -> explain ppf
2269226922702270let warn_on_missing_def env ppf t =
22712271- match t.desc with
22712271+ match get_desc t with
22722272 | Tconstr (p,_,_) ->
22732273 begin
22742274 try
+30-31
typing/subst.ml
···140140141141let newpersty desc =
142142 decr new_id;
143143- Private_type_expr.create
143143+ create_expr
144144 desc ~level:generic_level ~scope:Btype.lowest_level ~id:!new_id
145145146146(* ensure that all occurrences of 'Tvar None' are physically shared *)
···155155156156(* Similar to [Ctype.nondep_type_rec]. *)
157157let rec typexp copy_scope s ty =
158158- let ty = repr ty in
159159- match ty.desc with
160160- Tvar _ | Tunivar _ as desc ->
161161- if s.for_saving || ty.id < 0 then
158158+ let desc = get_desc ty in
159159+ match desc with
160160+ Tvar _ | Tunivar _ ->
161161+ if s.for_saving || get_id ty < 0 then
162162 let ty' =
163163 if s.for_saving then newpersty (norm desc)
164164- else newty2 ty.level desc
164164+ else newty2 ~level:(get_level ty) desc
165165 in
166166- For_copy.save_desc copy_scope ty desc;
167167- Private_type_expr.set_desc ty (Tsubst (ty', None));
168168- (* TODO: move this line to btype.ml
169169- there is a similar problem also in ctype.ml *)
166166+ For_copy.redirect_desc copy_scope ty (Tsubst (ty', None));
170167 ty'
171168 else ty
172169 | Tsubst (ty, _) ->
173170 ty
174171 | Tfield (m, k, _t1, _t2) when not s.for_saving && m = dummy_method
175175- && field_kind_repr k <> Fabsent && (repr ty).level < generic_level ->
172172+ && field_kind_repr k <> Fabsent && get_level ty < generic_level ->
176173 (* do not copy the type of self when it is not generalized *)
177174 ty
178175(* cannot do it, since it would omit substitution
···180177 ty
181178*)
182179 | _ ->
183183- let desc = ty.desc in
184184- For_copy.save_desc copy_scope ty desc;
185180 let tm = row_of_type ty in
186181 let has_fixed_row =
187182 not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm in
188183 (* Make a stub *)
189189- let ty' = if s.for_saving then newpersty (Tvar None) else newgenvar () in
190190- Private_type_expr.set_scope ty' ty.scope;
191191- Private_type_expr.set_desc ty (Tsubst (ty', None));
192192- Private_type_expr.set_desc ty'
193193- begin if has_fixed_row then
194194- match tm.desc with (* PR#7348 *)
184184+ let ty' =
185185+ if s.for_saving then newpersty (Tvar None)
186186+ else newgenstub ~scope:(get_scope ty)
187187+ in
188188+ For_copy.redirect_desc copy_scope ty (Tsubst (ty', None));
189189+ let desc =
190190+ if has_fixed_row then
191191+ match get_desc tm with (* PR#7348 *)
195192 Tconstr (Pdot(m,i), tl, _abbrev) ->
196193 let i' = String.sub i 0 (String.length i - 4) in
197194 Tconstr(type_path s (Pdot(m,i')), tl, ref Mnil)
···221218 Tobject (t1', ref name')
222219 | Tvariant row ->
223220 let row = row_repr row in
224224- let more = repr row.row_more in
221221+ let more = row.row_more in
222222+ let mored = get_desc more in
225223 (* We must substitute in a subtle way *)
226224 (* Tsubst takes a tuple containing the row var and the variant *)
227227- begin match more.desc with
225225+ begin match mored with
228226 Tsubst (_, Some ty2) ->
229227 (* This variant type has been already copied *)
230230- Private_type_expr.set_desc ty (Tsubst (ty2, None));
231231- (* avoid Tlink in the new type *)
228228+ (* Change the stub to avoid Tlink in the new type *)
229229+ For_copy.redirect_desc copy_scope ty (Tsubst (ty2, None));
232230 Tlink ty2
233231 | _ ->
234232 let dup =
235235- s.for_saving || more.level = generic_level || static_row row ||
236236- match more.desc with Tconstr _ -> true | _ -> false in
233233+ s.for_saving || get_level more = generic_level ||
234234+ static_row row || is_Tconstr more in
237235 (* Various cases for the row variable *)
238236 let more' =
239239- match more.desc with
237237+ match mored with
240238 Tsubst (ty, None) -> ty
241239 | Tconstr _ | Tnil -> typexp copy_scope s more
242240 | Tunivar _ | Tvar _ ->
243243- For_copy.save_desc copy_scope more more.desc;
244244- if s.for_saving then newpersty (norm more.desc) else
245245- if dup && is_Tvar more then newgenty more.desc else more
241241+ if s.for_saving then newpersty (norm mored)
242242+ else if dup && is_Tvar more then newgenty mored
243243+ else more
246244 | _ -> assert false
247245 in
248246 (* Register new type first for recursion *)
249249- Private_type_expr.set_desc more
247247+ For_copy.redirect_desc copy_scope more
250248 (Tsubst (more', Some ty'));
251249 (* TODO: check if more' can be eliminated *)
252250 (* Return a new copy *)
···264262 | Tfield(_label, kind, _t1, t2) when field_kind_repr kind = Fabsent ->
265263 Tlink (typexp copy_scope s t2)
266264 | _ -> copy_type_desc (typexp copy_scope s) desc
267267- end;
265265+ in
266266+ Transient_expr.set_stub_desc ty' desc;
268267 ty'
269268270269(*
+15-11
typing/typeclass.ml
···716716 let ty' = cty'.ctyp_type in
717717 Ctype.unify val_env ty' ty
718718 end;
719719- begin match (Ctype.repr ty).desc with
719719+ begin match get_desc ty with
720720 Tvar _ ->
721721 let ty' = Ctype.newvar () in
722722 Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty;
···838838 List.iter
839839 (fun (lab,kind,ty) ->
840840 let k =
841841- if Btype.field_kind_repr kind = Fpresent then Public else Private in
841841+ if Types.field_kind_repr kind = Fpresent then Public else Private in
842842 try Ctype.unify val_env ty
843843 (Ctype.filter_method val_env lab k self_type)
844844 with _ -> assert false)
···864864 csig_inher = inher} in
865865 let methods = get_methods self_type in
866866 let priv_meths =
867867- List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind <> Fpresent)
867867+ List.filter (fun (_,kind,_) -> Types.field_kind_repr kind <> Fpresent)
868868 methods in
869869 (* ensure that inherited methods are listed too *)
870870 List.iter (fun (met, _kind, _ty) ->
···911911912912 (* Check for private methods made public *)
913913 let pub_meths' =
914914- List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind = Fpresent)
914914+ List.filter (fun (_,kind,_) -> Types.field_kind_repr kind = Fpresent)
915915 (get_methods public_self) in
916916 let names = List.map (fun (x,_,_) -> x) in
917917 let l1 = names priv_meths and l2 = names pub_meths' in
···12201220 Typetexp.widen context;
12211221 Ctype.end_def ();
1222122212231223- limited_generalize (Ctype.row_variable (Ctype.self_type cl.cl_type))
12241224- cl.cl_type;
12251225- limited_generalize (Ctype.row_variable (Ctype.self_type clty.cltyp_type))
12231223+ limited_generalize
12241224+ (Ctype.row_variable (Ctype.self_type cl.cl_type))
12251225+ cl.cl_type;
12261226+ limited_generalize
12271227+ (Ctype.row_variable (Ctype.self_type clty.cltyp_type))
12261228 clty.cltyp_type;
1227122912281230 begin match
···14441446 let (cl_params', cl_type) = Ctype.instance_class params typ in
14451447 let ty = Ctype.self_type cl_type in
14461448 Ctype.hide_private_methods ty;
14471447- Ctype.set_object_name obj_id (Ctype.row_variable ty) cl_params ty;
14491449+ Ctype.set_object_name
14501450+ obj_id (Ctype.row_variable ty) cl_params ty;
14481451 begin try
14491452 List.iter2 (Ctype.unify env) cl_params cl_params'
14501453 with Ctype.Unify _ ->
···15721575 Ctype.instance_parameterized_type params (Ctype.self_type typ)
15731576 in
15741577 Ctype.hide_private_methods cl_ty;
15751575- Ctype.set_object_name obj_id (Ctype.row_variable cl_ty) cl_params cl_ty;
15781578+ Ctype.set_object_name
15791579+ obj_id (Ctype.row_variable cl_ty) cl_params cl_ty;
15761580 let cl_abbr =
15771581 let arity = List.length cl_params in
15781582 {
···16141618 in
16151619 List.iter (fun (lab,kind,_) ->
16161620 if lab = dummy_method then
16171617- match Btype.field_kind_repr kind with
16181618- Fvar r -> Btype.set_kind r Fabsent
16211621+ match Types.field_kind_repr kind with
16221622+ Fvar r -> Types.set_kind r Fabsent
16191623 | _ -> ()
16201624 ) methods
16211625 end;
+87-81
typing/typecore.ml
···300300 (type_option texp.exp_type) texp.exp_loc texp.exp_env
301301302302let extract_option_type env ty =
303303- match expand_head env ty with {desc = Tconstr(path, [ty], _)}
304304- when Path.same path Predef.path_option -> ty
303303+ match get_desc (expand_head env ty) with
304304+ Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
305305 | _ -> assert false
306306307307type record_extraction_result =
···336336 | Not_a_record_type | Maybe_a_record_type -> assert false
337337338338let is_principal ty =
339339- (repr ty).level = generic_level || not !Clflags.principal
339339+ not !Clflags.principal || get_level ty = generic_level
340340341341(* Typing of patterns *)
342342···388388(* unification of a type with a Tconstr with freshly created arguments *)
389389let unify_head_only ~refine loc env ty constr =
390390 let path =
391391- match (repr constr.cstr_res).desc with
391391+ match get_desc constr.cstr_res with
392392 | Tconstr(p, _, _) -> p
393393 | _ -> assert false in
394394 let decl = Env.find_type path !env in
···399399(* make all Reither present in open variants *)
400400let finalize_variant pat tag opat r =
401401 let row =
402402- match expand_head pat.pat_env pat.pat_type with
403403- {desc = Tvariant row} -> r := row; row_repr row
402402+ match get_desc (expand_head pat.pat_env pat.pat_type) with
403403+ Tvariant row -> r := row; row_repr row
404404 | _ -> assert false
405405 in
406406 begin match row_field tag row with
···582582 unify_pat env {p with pat_type = ty} ty_res;
583583 let refinable =
584584 lbl.lbl_mut = Immutable && List.mem_assoc lbl.lbl_pos ppl &&
585585- match (repr lbl.lbl_arg).desc with Tpoly _ -> false | _ -> true in
585585+ match get_desc lbl.lbl_arg with Tpoly _ -> false | _ -> true in
586586 if refinable then begin
587587 let arg = List.assoc lbl.lbl_pos ppl in
588588 unify_pat env {arg with pat_type = build_as_type env arg} ty_arg
···612612 let cty, ty, force = Typetexp.transl_simple_type_delayed !env sty in
613613 unify_pat_types ~refine loc env ty (instance expected_ty);
614614 pattern_force := force :: !pattern_force;
615615- match ty.desc with
615615+ match get_desc ty with
616616 | Tpoly (body, tyl) ->
617617 begin_def ();
618618 init_def generic_level;
···661661 [ty2]
662662 | _ ->
663663 unify_pat_types cty.ctyp_loc env ty1 (newty (Ttuple ty_args));
664664- match repr (expand_head !env ty2) with
665665- {desc = Ttuple tyl} -> tyl
664664+ match get_desc (expand_head !env ty2) with
665665+ Ttuple tyl -> tyl
666666 | _ -> assert false
667667 in
668668 if ids <> [] then ignore begin
···670670 let rem =
671671 List.fold_left
672672 (fun rem tv ->
673673- match repr tv with
674674- {desc = Tconstr(Path.Pident id, [], _)}
675675- when List.mem id rem ->
673673+ match get_desc tv with
674674+ Tconstr(Path.Pident id, [], _) when List.mem id rem ->
676675 list_remove id rem
677676 | _ ->
678677 raise (Error (cty.ctyp_loc, !env,
···805804 let tyl = List.map (fun _ -> newvar()) decl.type_params in
806805 let row0 =
807806 let ty = expand_head env (newty(Tconstr(path, tyl, ref Mnil))) in
808808- match ty.desc with
807807+ match get_desc ty with
809808 Tvariant row when static_row row -> row
810809 | _ -> raise(Error(lid.loc, env, Not_a_polymorphic_variant_type lid.txt))
811810 in
···872871 in
873872 match decl with
874873 Some {type_manifest = Some ty} ->
875875- begin match repr ty with
876876- {desc=Tconstr(p,_,_)} -> expand_path env p
874874+ begin match get_desc ty with
875875+ Tconstr(p,_,_) -> expand_path env p
877876 | _ -> assert false
878877 end
879878 | _ ->
···887886exception Wrong_name_disambiguation of Env.t * wrong_name
888887889888let get_constr_type_path ty =
890890- match (repr ty).desc with
889889+ match get_desc ty with
891890 | Tconstr(p, _, _) -> p
892891 | _ -> assert false
893892···14841483 No variable information, as we only backtrack on
14851484 patterns without variables (cf. assert statements). *)
14861485type state =
14871487- { snapshot: Btype.snapshot;
14861486+ { snapshot: snapshot;
14881487 levels: Ctype.levels;
14891488 env: Env.t; }
14901489let save_state env =
···24972496(* List labels in a function type, and whether return type is a variable *)
24982497let rec list_labels_aux env visited ls ty_fun =
24992498 let ty = expand_head env ty_fun in
25002500- if List.memq ty visited then
24992499+ if TypeSet.mem ty visited then
25012500 List.rev ls, false
25022502- else match ty.desc with
25012501+ else match get_desc ty with
25032502 Tarrow (l, _, ty_res, _) ->
25042504- list_labels_aux env (ty::visited) (l::ls) ty_res
25032503+ list_labels_aux env (TypeSet.add ty visited) (l::ls) ty_res
25052504 | _ ->
25062505 List.rev ls, is_Tvar ty
2507250625082507let list_labels env ty =
25092509- wrap_trace_gadt_instances env (list_labels_aux env [] []) ty
25082508+ wrap_trace_gadt_instances env (list_labels_aux env TypeSet.empty []) ty
2510250925112510(* Check that all univars are safe in a type. Both exp.exp_type and
25122511 ty_expected should already be generalized. *)
···25142513 let pty = instance ty_expected in
25152514 begin_def ();
25162515 let exp_ty, vars =
25172517- match pty.desc with
25162516+ match get_desc pty with
25182517 Tpoly (body, tl) ->
25192518 (* Enforce scoping for type_let:
25202519 since body is not generic, instance_poly only makes
···2546254525472546let check_partial_application statement exp =
25482547 let rec f delay =
25492549- let ty = (expand_head exp.exp_env exp.exp_type).desc in
25482548+ let ty = get_desc (expand_head exp.exp_env exp.exp_type) in
25502549 let check_statement () =
25512550 match ty with
25522551 | Tconstr (p, _, _) when Path.same p Predef.path_unit ->
···26162615(* Check that a type is generalizable at some level *)
26172616let generalizable level ty =
26182617 let rec check ty =
26192619- let ty = repr ty in
26202618 if not_marked_node ty then
26212621- if ty.level <= level then raise Exit else
26192619+ if get_level ty <= level then raise Exit else
26222620 (flip_mark_node ty; iter_type_expr check ty)
26232621 in
26242622 try check ty; unmark_type ty; true
···2631262926322630let contains_variant_either ty =
26332631 let rec loop ty =
26342634- let ty = repr ty in
26352632 if try_mark_node ty then
26362636- begin match ty.desc with
26332633+ begin match get_desc ty with
26372634 Tvariant row ->
26382635 let row = row_repr row in
26392636 if not (is_fixed row) then
···28532850 Path.(Pdot (Pident (Ident.create_persistent "CamlinternalFormatBasics"),
28542851 "format6"))
28552852 in
28562856- let is_format = match ty_exp.desc with
28532853+ let is_format = match get_desc ty_exp with
28572854 | Tconstr(path, _, _) when Path.same path fmt6_path ->
28582858- if !Clflags.principal && ty_exp.level <> generic_level then
28552855+ if !Clflags.principal && get_level ty_exp <> generic_level then
28592856 Location.prerr_warning loc
28602857 (Warnings.Not_principal "this coercion to format6");
28612858 true
···29532950 assert (sargs <> []);
29542951 let rec lower_args seen ty_fun =
29552952 let ty = expand_head env ty_fun in
29562956- if List.memq ty seen then () else
29572957- match ty.desc with
29532953+ if TypeSet.mem ty seen then () else
29542954+ match get_desc ty with
29582955 Tarrow (_l, ty_arg, ty_fun, _com) ->
29592956 (try unify_var env (newvar()) ty_arg
29602957 with Unify _ -> assert false);
29612961- lower_args (ty::seen) ty_fun
29582958+ lower_args (TypeSet.add ty seen) ty_fun
29622959 | _ -> ()
29632960 in
29642961 let type_sfunct sfunct =
···29712968 end;
29722969 let ty = instance funct.exp_type in
29732970 end_def ();
29742974- wrap_trace_gadt_instances env (lower_args []) ty;
29712971+ wrap_trace_gadt_instances env (lower_args TypeSet.empty) ty;
29752972 funct
29762973 in
29772974 let funct, sargs =
···30523049 (* Keep sharing *)
30533050 let ty_expected0 = instance ty_expected in
30543051 begin try match
30553055- sarg, expand_head env ty_expected, expand_head env ty_expected0 with
30563056- | Some sarg, {desc = Tvariant row}, {desc = Tvariant row0} ->
30523052+ sarg, get_desc (expand_head env ty_expected),
30533053+ get_desc (expand_head env ty_expected0)
30543054+ with
30553055+ | Some sarg, Tvariant row, Tvariant row0 ->
30573056 let row = row_repr row and row0 = row_repr row0 in
30583057 begin match row_field_repr (List.assoc l row.row_fields),
30593058 row_field_repr (List.assoc l row0.row_fields) with
···33703369 let arg = type_exp env sarg in
33713370 end_def ();
33723371 let tv = newvar () in
33733373- let gen = generalizable tv.level arg.exp_type in
33723372+ let gen = generalizable (get_level tv) arg.exp_type in
33743373 unify_var env tv arg.exp_type;
33753375- begin match arg.exp_desc, !self_coercion, (repr ty').desc with
33743374+ begin match arg.exp_desc, !self_coercion, get_desc ty' with
33763375 Texp_ident(_, _, {val_kind=Val_self _}), (path,r) :: _,
33773376 Tconstr(path',_,_) when Path.same path path' ->
33783377 (* prerr_endline "self coercion"; *)
···34483447 let (id, typ) =
34493448 filter_self_method env met Private meths privty
34503449 in
34513451- if is_Tvar (repr typ) then
34503450+ if is_Tvar typ then
34523451 Location.prerr_warning loc
34533452 (Warnings.Undeclared_virtual_method met);
34543453 (Tmeth_val id, None, typ)
···35183517 generalize_structure typ;
35193518 end;
35203519 let typ =
35213521- match repr typ with
35223522- {desc = Tpoly (ty, [])} ->
35203520+ match get_desc typ with
35213521+ Tpoly (ty, []) ->
35233522 instance ty
35243524- | {desc = Tpoly (ty, tl); level = l} ->
35253525- if !Clflags.principal && l <> generic_level then
35233523+ | Tpoly (ty, tl) ->
35243524+ if !Clflags.principal && get_level typ <> generic_level then
35263525 Location.prerr_warning loc
35273526 (Warnings.Not_principal "this use of a polymorphic method");
35283527 snd (instance_poly false tl ty)
35293529- | {desc = Tvar _} as ty ->
35283528+ | Tvar _ ->
35303529 let ty' = newvar () in
35313531- unify env (instance ty) (newty(Tpoly(ty',[])));
35303530+ unify env (instance typ) (newty(Tpoly(ty',[])));
35323531 (* if not !Clflags.nolabels then
35333532 Location.prerr_warning loc (Warnings.Unknown_method met); *)
35343533 ty'
···35553554 Some
35563555 (Meths.fold (fun meth _meth_ty li -> meth::li) !meths [])
35573556 | None ->
35583558- match (expand_head env obj.exp_type).desc with
35573557+ match get_desc (expand_head env obj.exp_type) with
35593558 | Tobject (fields, _) ->
35603559 let (fields, _) = Ctype.flatten_fields fields in
35613560 let collect_fields li (meth, meth_kind, _meth_ty) =
···36483647 begin_def ();
36493648 let context = Typetexp.narrow () in
36503649 let modl = !type_module env smodl in
36513651- Mtype.lower_nongen ty.level modl.mod_type;
36503650+ Mtype.lower_nongen (get_level ty) modl.mod_type;
36523651 let pres =
36533652 match modl.mod_type with
36543653 | Mty_alias _ -> Mp_absent
···37333732 | Pexp_poly(sbody, sty) ->
37343733 if !Clflags.principal then begin_def ();
37353734 let ty, cty =
37363736- match sty with None -> repr ty_expected, None
37353735+ match sty with None -> ty_expected, None
37373736 | Some sty ->
37383737 let sty = Ast_helper.Typ.force_poly sty in
37393738 let cty = Typetexp.transl_simple_type env false sty in
37403740- repr cty.ctyp_type, Some cty
37393739+ cty.ctyp_type, Some cty
37413740 in
37423741 if !Clflags.principal then begin
37433742 end_def ();
···37473746 with_explanation (fun () ->
37483747 unify_exp_types loc env (instance ty) (instance ty_expected));
37493748 let exp =
37503750- match (expand_head env ty).desc with
37493749+ match get_desc (expand_head env ty) with
37513750 Tpoly (ty', []) ->
37523751 let exp = type_expect env sbody (mk_expected ty') in
37533752 { exp with exp_type = instance ty }
···37923791 type. *)
37933792 let seen = Hashtbl.create 8 in
37943793 let rec replace t =
37953795- if Hashtbl.mem seen t.id then ()
37943794+ if Hashtbl.mem seen (get_id t) then ()
37963795 else begin
37973797- Hashtbl.add seen t.id ();
37983798- match t.desc with
37963796+ Hashtbl.add seen (get_id t) ();
37973797+ match get_desc t with
37993798 | Tconstr (Path.Pident id', _, _) when id == id' -> link_type t ty
38003799 | _ -> Btype.iter_type_expr replace t
38013800 end
···38143813 (Texp_newtype name, loc, sexp.pexp_attributes) :: body.exp_extra }
38153814 | Pexp_pack m ->
38163815 let (p, fl) =
38173817- match Ctype.expand_head env (instance ty_expected) with
38183818- {desc = Tpackage (p, fl)} ->
38163816+ match get_desc (Ctype.expand_head env (instance ty_expected)) with
38173817+ Tpackage (p, fl) ->
38193818 if !Clflags.principal &&
38203820- (Ctype.expand_head env ty_expected).level < Btype.generic_level
38193819+ get_level (Ctype.expand_head env ty_expected)
38203820+ < Btype.generic_level
38213821 then
38223822 Location.prerr_warning loc
38233823 (Warnings.Not_principal "this module packing");
38243824 (p, fl)
38253825- | {desc = Tvar _} ->
38253825+ | Tvar _ ->
38263826 raise (Error (loc, env, Cannot_infer_signature))
38273827 | _ ->
38283828 raise (Error (loc, env, Not_a_packed_module ty_expected))
···39523952and type_ident env ?(recarg=Rejected) lid =
39533953 let (path, desc) = Env.lookup_value ~loc:lid.loc lid.txt env in
39543954 let is_recarg =
39553955- match (repr desc.val_type).desc with
39553955+ match get_desc desc.val_type with
39563956 | Tconstr(p, _, _) -> Path.is_constructor_typath p
39573957 | _ -> false
39583958 in
39593959- begin match is_recarg, recarg, (repr desc.val_type).desc with
39593959+ begin match is_recarg, recarg, get_desc desc.val_type with
39603960 | _, Allowed, _
39613961 | true, Required, _
39623962 | false, Rejected, _ -> ()
···43814381 let may_coerce =
43824382 if not (is_inferred sarg) then None else
43834383 let work () =
43844384- match expand_head env ty_expected' with
43854385- {desc = Tarrow(Nolabel,_,ty_res0,_); level} ->
43864386- Some (no_labels ty_res0, level)
43844384+ let te = expand_head env ty_expected' in
43854385+ match get_desc te with
43864386+ Tarrow(Nolabel,_,ty_res0,_) ->
43874387+ Some (no_labels ty_res0, get_level te)
43874388 | _ -> None
43884389 in
43894390 (* Need to be careful not to expand local constraints here *)
···44034404 generalize_structure texp.exp_type
44044405 end;
44054406 let rec make_args args ty_fun =
44064406- match (expand_head env ty_fun).desc with
44074407+ match get_desc (expand_head env ty_fun) with
44074408 | Tarrow (l,ty_arg,ty_fun,_) when is_optional l ->
44084409 let ty = option_none env (instance ty_arg) sarg.pexp_loc in
44094410 make_args ((l, Some ty) :: args) ty_fun
···44194420 texp
44204421 end else begin
44214422 let warn = !Clflags.principal &&
44224422- (lv <> generic_level || (repr ty_fun').level <> generic_level)
44234423+ (lv <> generic_level || get_level ty_fun' <> generic_level)
44234424 and ty_fun = instance ty_fun' in
44244425 let ty_arg, ty_res =
44254425- match expand_head env ty_expected' with
44264426- {desc = Tarrow(Nolabel,ty_arg,ty_res,_)} -> ty_arg, ty_res
44264426+ match get_desc (expand_head env ty_expected') with
44274427+ Tarrow(Nolabel,ty_arg,ty_res,_) -> ty_arg, ty_res
44274428 | _ -> assert false
44284429 in
44294430 unify_exp env {texp with exp_type = ty_fun} ty_expected;
···44854486 (* funct.exp_type may be generic *)
44864487 let result_type omitted ty_fun =
44874488 List.fold_left
44884488- (fun ty_fun (l,ty,lv) -> newty2 lv (Tarrow(l,ty,ty_fun,Cok)))
44894489+ (fun ty_fun (l,ty,lv) -> newty2 ~level:lv (Tarrow(l,ty,ty_fun,Cok)))
44894490 ty_fun omitted
44904491 in
44914492 let has_label l ty_fun =
···44974498 let type_unknown_arg (ty_fun, typed_args) (lbl, sarg) =
44984499 let (ty_arg, ty_res) =
44994500 let ty_fun = expand_head env ty_fun in
45004500- match ty_fun.desc with
45014501+ match get_desc ty_fun with
45014502 | Tvar _ ->
45024503 let t1 = newvar () and t2 = newvar () in
45034503- if ty_fun.level >= t1.level &&
45044504+ if get_level ty_fun >= get_level t1 &&
45044505 not (is_prim ~name:"%identity" funct)
45054506 then
45064507 Location.prerr_warning sarg.pexp_loc
···45164517 result_type (!omitted_parameters @ !eliminated_optional_arguments)
45174518 ty_fun
45184519 in
45194519- match ty_res.desc with
45204520+ match get_desc ty_res with
45204521 | Tarrow _ ->
45214522 if !Clflags.classic || not (has_label lbl ty_fun) then
45224523 raise (Error(sarg.pexp_loc, env,
···45544555 in
45554556 let warned = ref false in
45564557 let rec type_args args ty_fun ty_fun0 sargs =
45574557- match expand_head env ty_fun, expand_head env ty_fun0 with
45584558- | {desc=Tarrow (l, ty, ty_fun, com); level=lv} as ty_fun',
45594559- {desc=Tarrow (_, ty0, ty_fun0, _)}
45584558+ let ty_fun' = expand_head env ty_fun in
45594559+ match get_desc ty_fun', get_desc (expand_head env ty_fun0) with
45604560+ | Tarrow (l, ty, ty_fun, com), Tarrow (_, ty0, ty_fun0, _)
45604561 when sargs <> [] && commu_repr com = Cok ->
45624562+ let lv = get_level ty_fun' in
45614563 let may_warn loc w =
45624564 if not !warned && !Clflags.principal && lv <> generic_level
45634565 then begin
···47604762 let exp = type_exp env sexp in
47614763 end_def();
47624764 let ty = expand_head env exp.exp_type and tv = newvar() in
47634763- if is_Tvar ty && ty.level > tv.level then
47654765+ if is_Tvar ty && get_level ty > get_level tv then
47644766 Location.prerr_warning
47654767 (final_subexpression exp).exp_loc
47664768 Warnings.Nonreturning_statement;
···47914793 (mkloc (Longident.Lident unpack.tu_name.txt)
47924794 unpack.tu_name.loc)))
47934795 in
47944794- Mtype.lower_nongen ty.level modl.mod_type;
47964796+ Mtype.lower_nongen (get_level ty) modl.mod_type;
47954797 let pres =
47964798 match modl.mod_type with
47974799 | Mty_alias _ -> Mp_absent
···51085110 List.iter2
51095111 (fun pat binding ->
51105112 let pat =
51115111- match pat.pat_type.desc with
51135113+ match get_desc pat.pat_type with
51125114 | Tpoly (ty, tl) ->
51135115 {pat with pat_type =
51145116 snd (instance_poly ~keep_names:true false tl ty)}
···52335235 List.map2
52345236 (fun {pvb_expr=sexp; pvb_attributes; _} (pat, slot) ->
52355237 if is_recursive then current_slot := slot;
52365236- match pat.pat_type.desc with
52385238+ match get_desc pat.pat_type with
52375239 | Tpoly (ty, tl) ->
52385240 if !Clflags.principal then begin_def ();
52395241 let vars, ty' = instance_poly ~keep_names:true true tl ty in
···54575459 | _, _ -> []
5458546054595461let report_literal_type_constraint const = function
54605460- | Some Errortrace.{ expected = { ty = { desc = Tconstr (typ, [], _) } } } ->
54615461- report_literal_type_constraint typ const
54625462- | Some _ | None -> []
54625462+ | Some tr ->
54635463+ begin match get_desc Errortrace.(tr.expected.ty) with
54645464+ Tconstr (typ, [], _) ->
54655465+ report_literal_type_constraint typ const
54665466+ | _ -> []
54675467+ end
54685468+ | None -> []
5463546954645470let report_expr_type_clash_hints exp diff =
54655471 match exp with
···55595565 (function ppf ->
55605566 fprintf ppf "but an expression was expected of type");
55615567 | Apply_non_function typ ->
55625562- begin match (repr typ).desc with
55685568+ begin match get_desc typ with
55635569 Tarrow _ ->
55645570 Location.errorf ~loc
55655571 "@[<v>@[<2>This function has type@ %a@]\
+37-38
typing/typedecl.ml
···142142(* Determine if a type's values are represented by floats at run-time. *)
143143let is_float env ty =
144144 match get_unboxed_type_representation env ty with
145145- Some {desc = Tconstr(p, _, _); _} -> Path.same p Predef.path_float
145145+ Some ty' ->
146146+ begin match get_desc ty' with
147147+ Tconstr(p, _, _) -> Path.same p Predef.path_float
148148+ | _ -> false
149149+ end
146150 | _ -> false
147151148152(* Determine if a type definition defines a fixed type. (PW) *)
···174178 | Some t -> Ctype.expand_head env t
175179 in
176180 let rv =
177177- match tm.desc with
181181+ match get_desc tm with
178182 Tvariant row ->
179183 let row = Btype.row_repr row in
180180- Btype.set_type_desc tm
184184+ set_type_desc tm
181185 (Tvariant {row with row_fixed = Some Fixed_private});
182186 if Btype.static_row row then
183187 (* the syntax hinted at the existence of a row variable,
···193197 r
194198 | _ -> assert false
195199 in
196196- Btype.set_type_desc rv (Tconstr (p, decl.type_params, ref Mnil))
200200+ set_type_desc rv (Tconstr (p, decl.type_params, ref Mnil))
197201198202(* Translate one type declaration *)
199203···231235 List.map
232236 (fun ld ->
233237 let ty = ld.ld_type.ctyp_type in
234234- let ty = match ty.desc with Tpoly(t,[]) -> t | _ -> ty in
238238+ let ty = match get_desc ty with Tpoly(t,[]) -> t | _ -> ty in
235239 {Types.ld_id = ld.ld_id;
236240 ld_mutable = ld.ld_mutable;
237241 ld_type = ty;
···271275 let tret_type = transl_simple_type env false sret_type in
272276 let ret_type = tret_type.ctyp_type in
273277 (* TODO add back type_path as a parameter ? *)
274274- begin match (Ctype.repr ret_type).desc with
278278+ begin match get_desc ret_type with
275279 | Tconstr (p', _, _) when Path.same type_path p' -> ()
276280 | _ ->
277281 let trace =
···480484module TypeMap = Btype.TypeMap
481485482486let rec check_constraints_rec env loc visited ty =
483483- let ty = Ctype.repr ty in
484487 if TypeSet.mem ty !visited then () else begin
485488 visited := TypeSet.add ty !visited;
486486- match ty.desc with
489489+ match get_desc ty with
487490 | Tconstr (path, args, _) ->
488491 let decl =
489492 try Env.find_type path env
···586589 match decl with
587590 { type_kind = (Type_variant _ | Type_record _| Type_open);
588591 type_manifest = Some ty } ->
589589- begin match (Ctype.repr ty).desc with
592592+ begin match get_desc ty with
590593 Tconstr(path, args, _) ->
591594 begin try
592595 let decl' = Env.find_type path env in
···624627let check_well_founded env loc path to_check ty =
625628 let visited = ref TypeMap.empty in
626629 let rec check ty0 parents ty =
627627- let ty = Btype.repr ty in
628630 if TypeSet.mem ty parents then begin
629631 (*Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;*)
630630- if match ty0.desc with
632632+ if match get_desc ty0 with
631633 | Tconstr (p, _, _) -> Path.same p path
632634 | _ -> false
633635 then raise (Error (loc, Recursive_abbrev (Path.name path)))
···643645 in
644646 if fini then () else
645647 let rec_ok =
646646- match ty.desc with
648648+ match get_desc ty with
647649 Tconstr(p,_,_) ->
648650 !Clflags.recursive_types && Ctype.is_contractive env p
649651 | Tobject _ | Tvariant _ -> true
···660662 with e ->
661663 visited := visited'; Some e
662664 in
663663- match ty.desc with
665665+ match get_desc ty with
664666 | Tconstr(p, _, _) when arg_exn <> None || to_check p ->
665667 if to_check p then Option.iter raise arg_exn
666668 else Btype.iter_type_expr (check ty0 TypeSet.empty) ty;
···699701700702 if decl.type_params = [] then () else
701703702702- let visited = ref [] in
704704+ let visited = ref TypeSet.empty in
703705704706 let rec check_regular cpath args prev_exp prev_expansions ty =
705705- let ty = Ctype.repr ty in
706706- if not (List.memq ty !visited) then begin
707707- visited := ty :: !visited;
708708- match ty.desc with
707707+ if not (TypeSet.mem ty !visited) then begin
708708+ visited := TypeSet.add ty !visited;
709709+ match get_desc ty with
709710 | Tconstr(path', args', _) ->
710711 if Path.same path path' then begin
711712 if not (Ctype.is_equal orig_env false args args') then
···799800 | { type_kind = Type_abstract;
800801 type_manifest = Some ty;
801802 type_private = Private; } when is_fixed_type sdecl ->
802802- let ty = Ctype.repr ty in
803803- let ty' = Btype.newty2 ty.level ty.desc in
803803+ let ty' = newty2 ~level:(get_level ty) (get_desc ty) in
804804 if Ctype.deep_occur ty ty' then
805805 let td = Tconstr(Path.Pident id, decl.type_params, ref Mnil) in
806806- Btype.link_type ty (Btype.newty2 ty.level td);
806806+ link_type ty (newty2 ~level:(get_level ty) td);
807807 {decl with type_manifest = Some ty'}
808808 else decl
809809 | _ -> decl
···10081008 let vars =
10091009 Ctype.free_variables (Btype.newgenty (Ttuple args))
10101010 in
10111011- List.iter
10121012- (function {desc = Tvar (Some "_")} as ty
10131013- when List.memq ty vars ->
10141014- Btype.set_type_desc ty (Tvar None)
10151015- | _ -> ())
10161016- typext_params
10111011+ List.iter
10121012+ (fun ty ->
10131013+ if get_desc ty = Tvar (Some "_")
10141014+ && List.exists (eq_type ty) vars
10151015+ then set_type_desc ty (Tvar None))
10161016+ typext_params
10171017 end;
10181018 (* Ensure that constructor's type matches the type being extended *)
10191019 let cstr_type_path, cstr_type_params =
10201020- match cdescr.cstr_res.desc with
10201020+ match get_desc cdescr.cstr_res with
10211021 Tconstr (p, _, _) ->
10221022 let decl = Env.find_type p env in
10231023 p, decl.type_params
···10541054 Types.Cstr_tuple args
10551055 | Some decl ->
10561056 let tl =
10571057- match args with
10581058- | [ {desc=Tconstr(_, tl, _)} ] -> tl
10571057+ match List.map get_desc args with
10581058+ | [ Tconstr(_, tl, _) ] -> tl
10591059 | _ -> assert false
10601060 in
10611061 let decl = Ctype.instance_declaration decl in
···12681268 raise (Error (loc, Multiple_native_repr_attributes))
1269126912701270let native_repr_of_type env kind ty =
12711271- match kind, (Ctype.expand_head_opt env ty).desc with
12711271+ match kind, get_desc (Ctype.expand_head_opt env ty) with
12721272 | Untagged, Tconstr (path, _, _) when Path.same path Predef.path_int ->
12731273 Some Untagged_int
12741274 | Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_float ->
···13141314 end
1315131513161316let rec parse_native_repr_attributes env core_type ty ~global_repr =
13171317- match core_type.ptyp_desc, (Ctype.repr ty).desc,
13171317+ match core_type.ptyp_desc, get_desc ty,
13181318 get_native_repr_attribute core_type.ptyp_attributes ~global_repr:None
13191319 with
13201320 | Ptyp_arrow _, Tarrow _, Native_repr_attr_present kind ->
···1331133113321332let check_unboxable env loc ty =
13331333 let check_type acc ty : Path.Set.t =
13341334- let ty = Ctype.repr (Ctype.expand_head_opt env ty) in
13351335- try match ty.desc with
13341334+ let ty = Ctype.expand_head_opt env ty in
13351335+ try match get_desc ty with
13361336 | Tconstr (p, _, _) ->
13371337 let tydecl = Env.find_type p env in
13381338 if tydecl.type_unboxed_default then
···16361636let explain_unbound_single ppf tv ty =
16371637 let trivial ty =
16381638 explain_unbound ppf tv [ty] (fun t -> t) "type" (fun _ -> "") in
16391639- match (Ctype.repr ty).desc with
16391639+ match get_desc ty with
16401640 Tobject(fi,_) ->
16411641 let (tl, rv) = Ctype.flatten_fields fi in
16421642- if rv == tv then trivial ty else
16421642+ if eq_type rv tv then trivial ty else
16431643 explain_unbound ppf tv tl (fun (_,_,t) -> t)
16441644 "method" (fun (lab,_,_) -> lab ^ ": ")
16451645 | Tvariant row ->
16461646 let row = Btype.row_repr row in
16471647- if row.row_more == tv then trivial ty else
16471647+ if eq_type row.row_more tv then trivial ty else
16481648 explain_unbound ppf tv row.row_fields
16491649 (fun (_l,f) -> match Btype.row_field_repr f with
16501650 Rpresent (Some t) -> t
···17471747 for native-code compilation@]"
17481748 | Unbound_type_var (ty, decl) ->
17491749 fprintf ppf "@[A type variable is unbound in this type declaration";
17501750- let ty = Ctype.repr ty in
17511750 begin match decl.type_kind, decl.type_manifest with
17521751 | Type_variant (tl, _rep), _ ->
17531752 explain_unbound_gen ppf ty tl (fun c ->
···6363 let params =
6464 match def.type_kind with
6565 | Type_variant ([{cd_res = Some ret_type}], _) ->
6666- begin match Ctype.repr ret_type with
6767- | {desc=Tconstr (_, tyl, _)} ->
6868- List.map Ctype.repr tyl
6666+ begin match get_desc ret_type with
6767+ | Tconstr (_, tyl, _) -> tyl
6968 | _ -> assert false
7069 end
7170 | _ -> def.type_params
···128127 parameters as well as the subtype
129128 - it performs a shallow traversal of object types,
130129 while our implementation collects all method types *)
131131- match (Ctype.repr ty).desc with
130130+ match get_desc ty with
132131 (* these are the important cases,
133132 on which immediate_subtypes is called from [check_type] *)
134133 | Tarrow(_,ty1,ty2,_) ->
···156155 | Tpoly (pty, _) -> [pty]
157156 | Tconstr (_path, tys, _) -> tys
158157159159-and immediate_subtypes_object_row acc ty = match (Ctype.repr ty).desc with
158158+and immediate_subtypes_object_row acc ty = match get_desc ty with
160159 | Tnil -> acc
161160 | Tfield (_label, _kind, ty, rest) ->
162161 let acc = ty :: acc in
···169168 immediate_subtypes_variant_row_field acc rf in
170169 List.fold_left add_subtype acc desc.row_fields in
171170 let add_row acc =
172172- let row = Ctype.repr desc.row_more in
173173- match row.desc with
171171+ let row = Btype.row_more desc in
172172+ match get_desc row with
174173 | Tvariant more -> immediate_subtypes_variant_row acc more
175174 | _ -> row :: acc
176175 in
···188187 end
189188190189let free_variables ty =
191191- Ctype.free_variables (Ctype.repr ty)
192192- |> List.map (fun {desc; id; _} ->
193193- match desc with
194194- | Tvar text -> {text; id}
190190+ Ctype.free_variables ty
191191+ |> List.map (fun ty ->
192192+ match get_desc ty with
193193+ Tvar text -> {text; id = get_id ty}
195194 | _ ->
196195 (* Ctype.free_variables only returns Tvar nodes *)
197196 assert false)
···393392 : Env.t -> type_expr -> mode -> context
394393 = fun env ty m ->
395394 let rec check_type hyps ty m =
396396- let ty = Ctype.repr ty in
397395 if Hyps.safe ty m hyps then empty
398396 else if Hyps.unsafe ty m hyps then worst_case ty
399397 else
400398 let hyps = Hyps.add ty m hyps in
401401- match (ty.desc, m) with
399399+ match (get_desc ty, m) with
402400 (* Impossible case due to the call to [Ctype.repr]. *)
403401 | (Tlink _ , _ ) -> assert false
404402 (* Impossible case (according to comment in [typing/types.mli]. *)
···407405 | (_ , Ind ) -> empty
408406 (* Variable case, add constraint. *)
409407 | (Tvar(alpha) , m ) ->
410410- TVarMap.singleton {text = alpha; id = ty.Types.id} m
408408+ TVarMap.singleton {text = alpha; id = get_id ty} m
411409 (* "Separable" case for constructors with known memory representation. *)
412410 | (Tarrow _ , Sep )
413411 | (Ttuple _ , Sep )
···535533 we build a list of modes by repeated consing into
536534 an accumulator variable [acc], setting existential variables
537535 to Ind as we go. *)
538538- let param_instance = Ctype.repr param_instance in
539536 let get context var =
540537 try TVarMap.find var context with Not_found -> Ind in
541538 let set_ind context var =
···543540 let is_ind context var = match get context var with
544541 | Ind -> true
545542 | Sep | Deepsep -> false in
546546- match param_instance.desc with
543543+ match get_desc param_instance with
547544 | Tvar text ->
548548- let var = {text; id = param_instance.Types.id} in
545545+ let var = {text; id = get_id param_instance} in
549546 (get context var) :: acc, (set_ind context var)
550547 | _ ->
551548 let instance_exis = free_variables param_instance in
+3-3
typing/typedecl_unboxed.ml
···2525 to the manifest type of private abbreviations. *)
2626let rec get_unboxed_type_representation env ty fuel =
2727 if fuel < 0 then Unavailable else
2828- let ty = Ctype.repr (Ctype.expand_head_opt env ty) in
2929- match ty.desc with
2828+ let ty = Ctype.expand_head_opt env ty in
2929+ match get_desc ty with
3030 | Tconstr (p, args, _) ->
3131 begin match Env.find_type p env with
3232 | exception Not_found -> This ty
···4040 | Type_variant ([{cd_args = Cstr_record [{ld_type = ty2; _}]; _}],
4141 Variant_unboxed)}
4242 ->
4343- let ty2 = match ty2.desc with Tpoly (t, _) -> t | _ -> ty2 in
4343+ let ty2 = match get_desc ty2 with Tpoly (t, _) -> t | _ -> ty2 in
4444 get_unboxed_type_representation env
4545 (Ctype.apply env type_params ty2 args) (fuel - 1)
4646 | _ -> This ty
+11-14
typing/typedecl_variance.ml
···4343let compute_variance env visited vari ty =
4444 let rec compute_variance_rec vari ty =
4545 (* Format.eprintf "%a: %x@." Printtyp.type_expr ty (Obj.magic vari); *)
4646- let ty = Ctype.repr ty in
4746 let vari' = get_variance ty visited in
4847 if Variance.subset vari vari' then () else
4948 let vari = Variance.union vari vari' in
5049 visited := TypeMap.add ty vari !visited;
5150 let compute_same = compute_variance_rec vari in
5252- match ty.desc with
5151+ match get_desc ty with
5352 Tarrow (_, ty1, ty2, _) ->
5453 let open Variance in
5554 let v = conjugate vari in
···144143 required
145144 in
146145 (* Prepare *)
147147- let params = List.map Btype.repr decl.type_params in
146146+ let params = decl.type_params in
148147 let tvl = ref TypeMap.empty in
149148 (* Compute occurrences in the body *)
150149 let open Variance in
···159158 if Btype.is_Tvar ty || mem Inj (get_variance ty tvl) then () else
160159 let visited = ref TypeSet.empty in
161160 let rec check ty =
162162- let ty = Ctype.repr ty in
163161 if TypeSet.mem ty !visited then () else begin
164162 visited := TypeSet.add ty !visited;
165163 if mem Inj (get_variance ty tvl) then () else
166166- match ty.desc with
164164+ match get_desc ty with
167165 | Tvar _ -> raise Exit
168166 | Tconstr _ ->
169167 let old = !visited in
···172170 with Exit ->
173171 visited := old;
174172 let ty' = Ctype.expand_head_opt env ty in
175175- if ty == ty' then raise Exit else check ty'
173173+ if eq_type ty ty' then raise Exit else check ty'
176174 end
177175 | _ -> Btype.iter_type_expr check ty
178176 end
···197195 (* Check propagation from constrained parameters *)
198196 let args = Btype.newgenty (Ttuple params) in
199197 let fvl = Ctype.free_variables args in
200200- let fvl = List.filter (fun v -> not (List.memq v params)) fvl in
198198+ let fvl =
199199+ List.filter (fun v -> not (List.exists (eq_type v) params)) fvl in
201200 (* If there are no extra variables there is nothing to do *)
202201 if fvl = [] then () else
203202 let tvl2 = ref TypeMap.empty in
···210209 params required;
211210 let visited = ref TypeSet.empty in
212211 let rec check ty =
213213- let ty = Ctype.repr ty in
214212 if TypeSet.mem ty !visited then () else
215213 let visited' = TypeSet.add ty !visited in
216214 visited := visited';
···224222 Btype.backtrack snap;
225223 let (c1,n1) = get_upper v1 and (c2,n2,_,i2) = get_lower v2 in
226224 if c1 && not c2 || n1 && not n2 then
227227- if List.memq ty fvl then
225225+ if List.exists (eq_type ty) fvl then
228226 let code = if not i2 then No_variable
229227 else if c2 || n2 then Variance_not_reflected
230228 else Variance_not_deducible in
···261259(* A parameter is constrained if it is either instantiated,
262260 or it is a variable appearing in another parameter *)
263261let constrained vars ty =
264264- match ty.desc with
265265- | Tvar _ -> List.exists (fun tl -> List.memq ty tl) vars
262262+ match get_desc ty with
263263+ | Tvar _ -> List.exists (List.exists (eq_type ty)) vars
266264 | _ -> true
267265268266let for_constr = function
···279277 compute_variance_type env ~check rloc {decl with type_private = Private}
280278 (for_constr tl)
281279 | Some ret_type ->
282282- match Ctype.repr ret_type with
283283- | {desc=Tconstr (_, tyl, _)} ->
280280+ match get_desc ret_type with
281281+ | Tconstr (_, tyl, _) ->
284282 (* let tyl = List.map (Ctype.expand_head env) tyl in *)
285285- let tyl = List.map Ctype.repr tyl in
286283 let fvl = List.map (Ctype.free_variables ?env:None) tyl in
287284 let _ =
288285 List.fold_left2
+5-5
typing/typemod.ml
···370370 T was not used as a path for a packed module
371371*)
372372let check_usage_of_module_types ~error ~paths ~loc env super =
373373- let it_do_type_expr it ty = match ty.desc with
373373+ let it_do_type_expr it ty = match get_desc ty with
374374 | Tpackage (p, _) ->
375375 begin match List.find_opt (Path.same p) paths with
376376 | Some p -> raise (Error(loc,Lazy.force !env,error p))
···471471 let rec loop = function
472472 | [] -> false
473473 | hd :: tl ->
474474- match (Btype.repr hd).desc with
474474+ match get_desc hd with
475475 | Tvar _ -> List.memq hd tl || loop tl
476476 | _ -> true
477477 in
···21912191 Ctype.generalize_structure exp.exp_type
21922192 end;
21932193 let mty =
21942194- match Ctype.expand_head env exp.exp_type with
21952195- {desc = Tpackage (p, fl)} ->
21942194+ match get_desc (Ctype.expand_head env exp.exp_type) with
21952195+ Tpackage (p, fl) ->
21962196 if List.exists (fun (_n, t) -> Ctype.free_variables t <> []) fl then
21972197 raise (Error (smod.pmod_loc, env,
21982198 Incomplete_packed_module exp.exp_type));
···22022202 Location.prerr_warning smod.pmod_loc
22032203 (Warnings.Not_principal "this module unpacking");
22042204 modtype_of_package env smod.pmod_loc p fl
22052205- | {desc = Tvar _} ->
22052205+ | Tvar _ ->
22062206 raise (Typecore.Error
22072207 (smod.pmod_loc, env, Typecore.Cannot_infer_signature))
22082208 | _ ->
+12-8
typing/typeopt.ml
···23232424let scrape_ty env ty =
2525 let ty = Ctype.expand_head_opt env (Ctype.correct_levels ty) in
2626- match ty.desc with
2626+ match get_desc ty with
2727 | Tconstr (p, _, _) ->
2828 begin match Env.find_type p env with
2929 | {type_kind = ( Type_variant (_, Variant_unboxed)
···3838 | _ -> ty
39394040let scrape env ty =
4141- (scrape_ty env ty).desc
4141+ get_desc (scrape_ty env ty)
4242+4343+let scrape_poly env ty =
4444+ let ty = scrape_ty env ty in
4545+ match get_desc ty with
4646+ | Tpoly (ty, _) -> get_desc ty
4747+ | d -> d
42484349let is_function_type env ty =
4450 match scrape env ty with
···6975let classify env ty =
7076 let ty = scrape_ty env ty in
7177 if maybe_pointer_type env ty = Immediate then Int
7272- else match ty.desc with
7878+ else match get_desc ty with
7379 | Tvar _ | Tunivar _ ->
7480 Any
7581 | Tconstr (p, _args, _abbrev) ->
···100106 assert false
101107102108let array_type_kind env ty =
103103- match scrape env ty with
104104- | Tconstr(p, [elt_ty], _) | Tpoly({desc = Tconstr(p, [elt_ty], _)}, _)
105105- when Path.same p Predef.path_array ->
109109+ match scrape_poly env ty with
110110+ | Tconstr(p, [elt_ty], _) when Path.same p Predef.path_array ->
106111 begin match classify env elt_ty with
107112 | Any -> if Config.flat_float_array then Pgenarray else Paddrarray
108113 | Float -> if Config.flat_float_array then Pfloatarray else Paddrarray
109114 | Addr | Lazy -> Paddrarray
110115 | Int -> Pintarray
111116 end
112112- | Tconstr(p, [], _) | Tpoly({desc = Tconstr(p, [], _)}, _)
113113- when Path.same p Predef.path_floatarray ->
117117+ | Tconstr(p, [], _) when Path.same p Predef.path_floatarray ->
114118 Pfloatarray
115119 | _ ->
116120 (* This can happen with e.g. Obj.field *)
+224-9
typing/types.ml
···19192020(* Type expressions for the core language *)
21212222-type type_expr =
2222+type transient_expr =
2323 { mutable desc: type_desc;
2424 mutable level: int;
2525 mutable scope: int;
2626 id: int }
2727+2828+and type_expr = transient_expr
27292830and type_desc =
2931 Tvar of string option
···7274 | Cunknown
7375 | Clink of commutable ref
74767575-module TypeOps = struct
7777+module TransientTypeOps = struct
7678 type t = type_expr
7779 let compare t1 t2 = t1.id - t2.id
7880 let hash t = t.id
7981 let equal t1 t2 = t1 == t2
8082end
81838282-module Private_type_expr = struct
8383- let create desc ~level ~scope ~id = {desc; level; scope; id}
8484- let set_desc ty d = ty.desc <- d
8585- let set_level ty lv = ty.level <- lv
8686- let set_scope ty sc = ty.scope <- sc
8787-end
8884(* *)
89859086module Uid = struct
···410406 cstr_tag: constructor_tag; (* Tag for heap blocks *)
411407 cstr_consts: int; (* Number of constant constructors *)
412408 cstr_nonconsts: int; (* Number of non-const constructors *)
413413- cstr_normal: int; (* Number of non generalized constrs *)
414409 cstr_generalized: bool; (* Constrained return type? *)
415410 cstr_private: private_flag; (* Read-only constructor? *)
416411 cstr_loc: Location.t;
···477472 | Sig_class (id, _, _, _)
478473 | Sig_class_type (id, _, _, _)
479474 -> id
475475+476476+(* migrating repr from Btype.. *)
477477+478478+(**** Definitions for backtracking ****)
479479+480480+type change =
481481+ Ctype of type_expr * type_desc
482482+ | Ccompress of type_expr * type_desc * type_desc
483483+ | Clevel of type_expr * int
484484+ | Cscope of type_expr * int
485485+ | Cname of
486486+ (Path.t * type_expr list) option ref * (Path.t * type_expr list) option
487487+ | Crow of row_field option ref * row_field option
488488+ | Ckind of field_kind option ref * field_kind option
489489+ | Ccommu of commutable ref * commutable
490490+ | Cuniv of type_expr option ref * type_expr option
491491+492492+type changes =
493493+ Change of change * changes ref
494494+ | Unchanged
495495+ | Invalid
496496+497497+let trail = Local_store.s_table ref Unchanged
498498+499499+let log_change ch =
500500+ let r' = ref Unchanged in
501501+ !trail := Change (ch, r');
502502+ trail := r'
503503+504504+(**** Representative of a type ****)
505505+506506+let rec field_kind_repr =
507507+ function
508508+ Fvar {contents = Some kind} -> field_kind_repr kind
509509+ | kind -> kind
510510+511511+let rec repr_link (t : type_expr) d : type_expr -> type_expr =
512512+ function
513513+ {desc = Tlink t' as d'} ->
514514+ repr_link t d' t'
515515+ | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent ->
516516+ repr_link t d' t'
517517+ | t' ->
518518+ log_change (Ccompress (t, t.desc, d));
519519+ t.desc <- d;
520520+ t'
521521+522522+let repr_link1 t = function
523523+ {desc = Tlink t' as d'} ->
524524+ repr_link t d' t'
525525+ | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent ->
526526+ repr_link t d' t'
527527+ | t' -> t'
528528+529529+let repr t =
530530+ match t.desc with
531531+ Tlink t' ->
532532+ repr_link1 t t'
533533+ | Tfield (_, k, _, t') when field_kind_repr k = Fabsent ->
534534+ repr_link1 t t'
535535+ | _ -> t
536536+537537+(* getters for type_expr *)
538538+539539+let get_desc t = (repr t).desc
540540+let get_level t = (repr t).level
541541+let get_scope t = (repr t).scope
542542+let get_id t = (repr t).id
543543+544544+(* transient type_expr *)
545545+546546+module Transient_expr = struct
547547+ let create desc ~level ~scope ~id = {desc; level; scope; id}
548548+ let set_desc ty d = ty.desc <- d
549549+ let set_stub_desc ty d = assert (ty.desc = Tvar None); ty.desc <- d
550550+ let set_level ty lv = ty.level <- lv
551551+ let set_scope ty sc = ty.scope <- sc
552552+ let coerce ty = ty
553553+ let repr = repr
554554+ let type_expr ty = ty
555555+end
556556+557557+(* Comparison for [type_expr]; cannot be used for functors *)
558558+559559+let eq_type t1 t2 = t1 == t2 || repr t1 == repr t2
560560+let compare_type t1 t2 = compare (get_id t1) (get_id t2)
561561+562562+(**** Some type creators ****)
563563+564564+let new_id = Local_store.s_ref (-1)
565565+566566+let create_expr = Transient_expr.create
567567+568568+let newty3 ~level ~scope desc =
569569+ incr new_id;
570570+ create_expr desc ~level ~scope ~id:!new_id
571571+572572+let newty2 ~level desc =
573573+ newty3 ~level ~scope:Ident.lowest_scope desc
574574+575575+ (**********************************)
576576+ (* Utilities for backtracking *)
577577+ (**********************************)
578578+579579+let undo_change = function
580580+ Ctype (ty, desc) -> Transient_expr.set_desc ty desc
581581+ | Ccompress (ty, desc, _) -> Transient_expr.set_desc ty desc
582582+ | Clevel (ty, level) -> Transient_expr.set_level ty level
583583+ | Cscope (ty, scope) -> Transient_expr.set_scope ty scope
584584+ | Cname (r, v) -> r := v
585585+ | Crow (r, v) -> r := v
586586+ | Ckind (r, v) -> r := v
587587+ | Ccommu (r, v) -> r := v
588588+ | Cuniv (r, v) -> r := v
589589+590590+type snapshot = changes ref * int
591591+let last_snapshot = Local_store.s_ref 0
592592+593593+let log_type ty =
594594+ if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
595595+let link_type ty ty' =
596596+ let ty = repr ty in
597597+ let ty' = repr ty' in
598598+ log_type ty;
599599+ let desc = ty.desc in
600600+ Transient_expr.set_desc ty (Tlink ty');
601601+ (* Name is a user-supplied name for this unification variable (obtained
602602+ * through a type annotation for instance). *)
603603+ match desc, ty'.desc with
604604+ Tvar name, Tvar name' ->
605605+ begin match name, name' with
606606+ | Some _, None -> log_type ty'; Transient_expr.set_desc ty' (Tvar name)
607607+ | None, Some _ -> ()
608608+ | Some _, Some _ ->
609609+ if ty.level < ty'.level then
610610+ (log_type ty'; Transient_expr.set_desc ty' (Tvar name))
611611+ | None, None -> ()
612612+ end
613613+ | _ -> ()
614614+ (* ; assert (check_memorized_abbrevs ()) *)
615615+ (* ; check_expans [] ty' *)
616616+(* TODO: consider eliminating set_type_desc, replacing it with link types *)
617617+let set_type_desc ty td =
618618+ let ty = repr ty in
619619+ if td != ty.desc then begin
620620+ log_type ty;
621621+ Transient_expr.set_desc ty td
622622+ end
623623+(* TODO: separate set_level into two specific functions: *)
624624+(* set_lower_level and set_generic_level *)
625625+let set_level ty level =
626626+ let ty = repr ty in
627627+ if level <> ty.level then begin
628628+ if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
629629+ Transient_expr.set_level ty level
630630+ end
631631+(* TODO: introduce a guard and rename it to set_higher_scope? *)
632632+let set_scope ty scope =
633633+ let ty = repr ty in
634634+ if scope <> ty.scope then begin
635635+ if ty.id <= !last_snapshot then log_change (Cscope (ty, ty.scope));
636636+ Transient_expr.set_scope ty scope
637637+ end
638638+let set_univar rty ty =
639639+ log_change (Cuniv (rty, !rty)); rty := Some ty
640640+let set_name nm v =
641641+ log_change (Cname (nm, !nm)); nm := v
642642+let set_row_field e v =
643643+ log_change (Crow (e, !e)); e := Some v
644644+let set_kind rk k =
645645+ log_change (Ckind (rk, !rk)); rk := Some k
646646+let set_commu rc c =
647647+ log_change (Ccommu (rc, !rc)); rc := c
648648+649649+let snapshot () =
650650+ let old = !last_snapshot in
651651+ last_snapshot := !new_id;
652652+ (!trail, old)
653653+654654+let rec rev_log accu = function
655655+ Unchanged -> accu
656656+ | Invalid -> assert false
657657+ | Change (ch, next) ->
658658+ let d = !next in
659659+ next := Invalid;
660660+ rev_log (ch::accu) d
661661+662662+let backtrack ~cleanup_abbrev (changes, old) =
663663+ match !changes with
664664+ Unchanged -> last_snapshot := old
665665+ | Invalid -> failwith "Btype.backtrack"
666666+ | Change _ as change ->
667667+ cleanup_abbrev ();
668668+ let backlog = rev_log [] change in
669669+ List.iter undo_change backlog;
670670+ changes := Unchanged;
671671+ last_snapshot := old;
672672+ trail := changes
673673+674674+let rec rev_compress_log log r =
675675+ match !r with
676676+ Unchanged | Invalid ->
677677+ log
678678+ | Change (Ccompress _, next) ->
679679+ rev_compress_log (r::log) next
680680+ | Change (_, next) ->
681681+ rev_compress_log log next
682682+683683+let undo_compress (changes, _old) =
684684+ match !changes with
685685+ Unchanged
686686+ | Invalid -> ()
687687+ | Change _ ->
688688+ let log = rev_compress_log [] changes in
689689+ List.iter
690690+ (fun r -> match !r with
691691+ Change (Ccompress (ty, desc, d), next) when ty.desc == d ->
692692+ Transient_expr.set_desc ty desc; r := !next
693693+ | _ -> ())
694694+ log
+86-14
typing/types.mli
···55555656 Note on mutability: TBD.
5757 *)
5858-type type_expr = private
5959- { mutable desc: type_desc;
6060- mutable level: int;
6161- mutable scope: int;
6262- id: int }
5858+type type_expr
63596464-and type_desc =
6060+type type_desc =
6561 | Tvar of string option
6662 (** [Tvar (Some "a")] ==> ['a] or ['_a]
6763 [Tvar None] ==> [_] *)
···236232 | Cunknown
237233 | Clink of commutable ref
238234239239-module Private_type_expr : sig
240240- val create : type_desc -> level: int -> scope: int -> id: int -> type_expr
241241- val set_desc : type_expr -> type_desc -> unit
242242- val set_level : type_expr -> int -> unit
243243- val set_scope : type_expr -> int -> unit
235235+(** Getters for type_expr; calls repr before answering a value *)
236236+237237+val get_desc: type_expr -> type_desc
238238+val get_level: type_expr -> int
239239+val get_scope: type_expr -> int
240240+val get_id: type_expr -> int
241241+242242+(** Transient [type_expr].
243243+ Should only be used immediately after [Transient_expr.repr] *)
244244+type transient_expr = private
245245+ { mutable desc: type_desc;
246246+ mutable level: int;
247247+ mutable scope: int;
248248+ id: int }
249249+250250+module Transient_expr : sig
251251+ (** Operations on [transient_expr] *)
252252+253253+ val create: type_desc -> level: int -> scope: int -> id: int -> transient_expr
254254+ val set_desc: transient_expr -> type_desc -> unit
255255+ val set_level: transient_expr -> int -> unit
256256+ val set_scope: transient_expr -> int -> unit
257257+ val repr: type_expr -> transient_expr
258258+ val type_expr: transient_expr -> type_expr
259259+ val coerce: type_expr -> transient_expr
260260+ (** Coerce without normalizing with [repr] *)
261261+262262+ val set_stub_desc: type_expr -> type_desc -> unit
263263+ (** Instantiate a not yet instantiated stub.
264264+ Fail if already instantiated. *)
244265end
245266246246-module TypeOps : sig
247247- type t = type_expr
267267+val create_expr: type_desc -> level: int -> scope: int -> id: int -> type_expr
268268+269269+(** Functions and definitions moved from Btype *)
270270+271271+val newty3: level:int -> scope:int -> type_desc -> type_expr
272272+ (** Create a type with a fresh id *)
273273+274274+val newty2: level:int -> type_desc -> type_expr
275275+ (** Create a type with a fresh id and no scope *)
276276+277277+val field_kind_repr: field_kind -> field_kind
278278+ (** Return the canonical representative of an object field kind. *)
279279+280280+module TransientTypeOps : sig
281281+ (** Comparisons for functors *)
282282+283283+ type t = transient_expr
248284 val compare : t -> t -> int
249285 val equal : t -> t -> bool
250286 val hash : t -> int
251287end
288288+289289+(** Comparisons for [type_expr]; cannot be used for functors *)
290290+291291+val eq_type: type_expr -> type_expr -> bool
292292+val compare_type: type_expr -> type_expr -> int
252293253294(* *)
254295···543584 cstr_tag: constructor_tag; (* Tag for heap blocks *)
544585 cstr_consts: int; (* Number of constant constructors *)
545586 cstr_nonconsts: int; (* Number of non-const constructors *)
546546- cstr_normal: int; (* Number of non generalized constrs *)
547587 cstr_generalized: bool; (* Constrained return type? *)
548588 cstr_private: private_flag; (* Read-only constructor? *)
549589 cstr_loc: Location.t;
···587627val bound_value_identifiers: signature -> Ident.t list
588628589629val signature_item_id : signature_item -> Ident.t
630630+631631+(**** Utilities for backtracking ****)
632632+633633+type snapshot
634634+ (* A snapshot for backtracking *)
635635+val snapshot: unit -> snapshot
636636+ (* Make a snapshot for later backtracking. Costs nothing *)
637637+val backtrack: cleanup_abbrev:(unit -> unit) -> snapshot -> unit
638638+ (* Backtrack to a given snapshot. Only possible if you have
639639+ not already backtracked to a previous snapshot.
640640+ Calls [cleanup_abbrev] internally *)
641641+val undo_compress: snapshot -> unit
642642+ (* Backtrack only path compression. Only meaningful if you have
643643+ not already backtracked to a previous snapshot.
644644+ Does not call [cleanup_abbrev] *)
645645+646646+(* Functions to use when modifying a type (only Ctype?) *)
647647+val link_type: type_expr -> type_expr -> unit
648648+ (* Set the desc field of [t1] to [Tlink t2], logging the old
649649+ value if there is an active snapshot *)
650650+val set_type_desc: type_expr -> type_desc -> unit
651651+ (* Set directly the desc field, without sharing *)
652652+val set_level: type_expr -> int -> unit
653653+val set_scope: type_expr -> int -> unit
654654+val set_name:
655655+ (Path.t * type_expr list) option ref ->
656656+ (Path.t * type_expr list) option -> unit
657657+val set_row_field: row_field option ref -> row_field -> unit
658658+val set_univar: type_expr option ref -> type_expr -> unit
659659+val set_kind: field_kind option ref -> field_kind -> unit
660660+val set_commu: commutable ref -> commutable -> unit
661661+ (* Set references, logging the old value *)
+45-43
typing/typetexp.ml
···230230 match decl.type_manifest with
231231 None -> unify_var
232232 | Some ty ->
233233- if (repr ty).level = Btype.generic_level then unify_var else unify
233233+ if get_level ty = Btype.generic_level then unify_var else unify
234234 in
235235 List.iter2
236236 (fun (sty, cty) ty' ->
···253253 match decl.type_manifest with
254254 None -> raise Not_found
255255 | Some ty ->
256256- match (repr ty).desc with
256256+ match get_desc ty with
257257 Tvariant row when Btype.static_row row -> ()
258258 | Tconstr (path, _, _) ->
259259 check (Env.find_type path env)
···291291 (List.combine stl args) params;
292292 let ty_args = List.map (fun ctyp -> ctyp.ctyp_type) args in
293293 let ty = Ctype.expand_head env (newconstr path ty_args) in
294294- let ty = match ty.desc with
294294+ let ty = match get_desc ty with
295295 Tvariant row ->
296296 let row = Btype.row_repr row in
297297 let fields =
···353353 end;
354354 let t = instance t in
355355 let px = Btype.proxy t in
356356- begin match px.desc with
357357- | Tvar None -> Btype.set_type_desc px (Tvar (Some alias))
358358- | Tunivar None -> Btype.set_type_desc px (Tunivar (Some alias))
356356+ begin match get_desc px with
357357+ | Tvar None -> set_type_desc px (Tvar (Some alias))
358358+ | Tunivar None -> set_type_desc px (Tunivar (Some alias))
359359 | _ -> ()
360360 end;
361361 { ty with ctyp_type = t }
···410410 let cty = transl_type env policy sty in
411411 let ty = cty.ctyp_type in
412412 let nm =
413413- match repr cty.ctyp_type with
414414- {desc=Tconstr(p, tl, _)} -> Some(p, tl)
415415- | _ -> None
413413+ match get_desc cty.ctyp_type with
414414+ Tconstr(p, tl, _) -> Some(p, tl)
415415+ | _ -> None
416416 in
417417 name := if Hashtbl.length hfields <> 0 then None else nm;
418418- let fl = match expand_head env cty.ctyp_type, nm with
419419- {desc=Tvariant row}, _ when Btype.static_row row ->
418418+ let fl = match get_desc (expand_head env cty.ctyp_type), nm with
419419+ Tvariant row, _ when Btype.static_row row ->
420420 let row = Btype.row_repr row in
421421 row.row_fields
422422- | {desc=Tvar _}, Some(p, _) ->
422422+ | Tvar _, Some(p, _) ->
423423 raise(Error(sty.ptyp_loc, env, Undefined_type_constructor p))
424424 | _ ->
425425 raise(Error(sty.ptyp_loc, env, Not_a_variant ty))
···481481 (fun tyl (name, ty1) ->
482482 let v = Btype.proxy ty1 in
483483 if deep_occur v ty then begin
484484- match v.desc with
485485- Tvar name when v.level = Btype.generic_level ->
486486- Btype.set_type_desc v (Tunivar name);
484484+ match get_desc v with
485485+ Tvar name when get_level v = Btype.generic_level ->
486486+ set_type_desc v (Tunivar name);
487487 v :: tyl
488488 | _ ->
489489- raise (Error (styp.ptyp_loc, env, Cannot_quantify (name, v)))
489489+ raise (Error (styp.ptyp_loc, env,
490490+ Cannot_quantify (name, v)))
490491 end else tyl)
491492 [] new_univars
492493 in
···544545 | Oinherit sty -> begin
545546 let cty = transl_type env policy sty in
546547 let nm =
547547- match repr cty.ctyp_type with
548548- {desc=Tconstr(p, _, _)} -> Some p
549549- | _ -> None in
548548+ match get_desc cty.ctyp_type with
549549+ Tconstr(p, _, _) -> Some p
550550+ | _ -> None in
550551 let t = expand_head env cty.ctyp_type in
551551- match t, nm with
552552- {desc=Tobject ({desc=(Tfield _ | Tnil) as tf}, _)}, _ -> begin
553553- if opened_object t then
554554- raise (Error (sty.ptyp_loc, env, Opened_object nm));
555555- let rec iter_add = function
556556- | Tfield (s, _k, ty1, ty2) -> begin
557557- add_typed_field sty.ptyp_loc s ty1;
558558- iter_add ty2.desc
559559- end
560560- | Tnil -> ()
561561- | _ -> assert false in
562562- iter_add tf;
563563- OTinherit cty
552552+ match get_desc t, nm with
553553+ Tobject (tf, _), _
554554+ when (match get_desc tf with Tfield _ | Tnil -> true | _ -> false) ->
555555+ begin
556556+ if opened_object t then
557557+ raise (Error (sty.ptyp_loc, env, Opened_object nm));
558558+ let rec iter_add ty =
559559+ match get_desc ty with
560560+ | Tfield (s, _k, ty1, ty2) ->
561561+ add_typed_field sty.ptyp_loc s ty1;
562562+ iter_add ty2
563563+ | Tnil -> ()
564564+ | _ -> assert false
565565+ in
566566+ iter_add tf;
567567+ OTinherit cty
564568 end
565565- | {desc=Tvar _}, Some p ->
569569+ | Tvar _, Some p ->
566570 raise (Error (sty.ptyp_loc, env, Undefined_type_constructor p))
567571 | _ -> raise (Error (sty.ptyp_loc, env, Not_an_object t))
568572 end in
···582586583587(* Make the rows "fixed" in this type, to make universal check easier *)
584588let rec make_fixed_univars ty =
585585- let ty = repr ty in
586589 if Btype.try_mark_node ty then
587587- begin match ty.desc with
590590+ begin match get_desc ty with
588591 | Tvariant row ->
589592 let row = Btype.row_repr row in
590593 let more = Btype.row_more row in
591594 if Btype.is_Tunivar more then
592592- Btype.set_type_desc ty
595595+ set_type_desc ty
593596 (Tvariant
594594- {row with row_fixed=Some(Univar more);
597597+ {row with row_fixed = Some (Univar more);
595598 row_fields = List.map
596599 (fun (s,f as p) -> match Btype.row_field_repr f with
597600 Reither (c, tl, _m, r) -> s, Reither (c, tl, true, r)
···618621 then try
619622 r := (loc, v, TyVarMap.find name !type_variables) :: !r
620623 with Not_found ->
621621- if fixed && Btype.is_Tvar (repr ty) then
624624+ if fixed && Btype.is_Tvar ty then
622625 raise(Error(loc, env, Unbound_type_variable ("'"^name)));
623626 let v2 = new_global_var () in
624627 r := (loc, v, v2) :: !r;
···657660 let univs =
658661 List.fold_left
659662 (fun acc v ->
660660- let v = repr v in
661661- match v.desc with
662662- Tvar name when v.level = Btype.generic_level ->
663663- Btype.set_type_desc v (Tunivar name); v :: acc
663663+ match get_desc v with
664664+ Tvar name when get_level v = Btype.generic_level ->
665665+ set_type_desc v (Tunivar name); v :: acc
664666 | _ -> acc)
665667 [] !pre_univars
666668 in
···753755 fprintf ppf
754756 "@[The type %a@ does not expand to a polymorphic variant type@]"
755757 Printtyp.type_expr ty;
756756- begin match ty.desc with
758758+ begin match get_desc ty with
757759 | Tvar (Some s) ->
758760 (* PR#7012: help the user that wrote 'Foo instead of `Foo *)
759761 Misc.did_you_mean ppf (fun () -> ["`" ^ s])
+1-1
utils/warnings.ml
···689689let ref_manual_explanation () =
690690 (* manual references are checked a posteriori by the manual
691691 cross-reference consistency check in manual/tests*)
692692- let[@manual.ref "s:comp-warnings"] chapter, section = 9, 5 in
692692+ let[@manual.ref "s:comp-warnings"] chapter, section = 11, 5 in
693693 Printf.sprintf "(See manual section %d.%d)" chapter section
694694695695let message = function