Debian Codegraph @

pretyping/coercion.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* Created by Hugo Herbelin for Coq V7 by isolating the coercion
12 mechanism out of the type inference algorithm in file trad.ml from
13 Coq V6.3, Nov 1999; The coercion mechanism was implemented in
14 trad.ml by Amokrane Saïbi, May 1996 *)
15 (* Addition of products and sorts in canonical structures by Pierre
16 Corbineau, Feb 2008 *)
17 (* Turned into an abstract compilation unit by Matthieu Sozeau, March 2006 *)
18
19 open CErrors
20 open Util
21 open Names
22 open Constr
23 open Context
24 open Environ
25 open EConstr
26 open Vars
27 open Reductionops
28 open Pretype_errors
29 open Coercionops
30 open Evarutil
31 open Evarconv
32 open Evd
33 open Globnames
34
35 let { Goptions.get = get_use_typeclasses_for_conversion } =
36 Goptions.declare_bool_option_and_ref
37 ~key:["Typeclass"; "Resolution"; "For"; "Conversion"]
38 ~value:true
39 ()
40
41 (* Typing operations dealing with coercions *)
42 exception NoCoercion
43 exception NoCoercionNoUnifier of evar_map * unification_error
44
45 let apply_coercion_args env sigma isproj bo ty arg arg_ty nparams =
46 let destProd sigma typ =
47 match EConstr.kind sigma (whd_all env sigma typ) with
48 | Prod (_, c1, c2) -> c1, c2
49 | _ -> anomaly (Pp.str "apply_coercion_args.") in
50 let rec apply_rec sigma acc typ nparams =
51 if nparams <= 0 then sigma, List.rev acc, typ else
52 let c1, c2 = destProd sigma typ in
53 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma c1 in
54 let sigma, x = Evarutil.new_evar ~typeclass_candidate env sigma c1 in
55 apply_rec sigma (x :: acc) (subst1 x c2) (nparams - 1) in
56 let sigma, params, typ = apply_rec sigma [] ty nparams in
57 let sigma, args, typ =
58 let c1, c2 = destProd sigma typ in
59 let sigma =
60 let arg_ty = whd_zeta env sigma arg_ty in
61 try Evarconv.unify_leq_delay env sigma arg_ty c1
62 with Evarconv.UnableToUnify _ -> raise NoCoercion in
63 sigma, params @ [arg], subst1 arg c2 in
64 let bo, args =
65 match isproj with
66 | None -> bo, args
67 | Some (p,r) ->
68 let npars = Projection.Repr.npars p in
69 let p = Projection.make p false in
70 let args = List.skipn npars args in
71 let hd, tl = match args with hd :: tl -> hd, tl | [] -> assert false in
72 mkProj (p, r, hd), tl in
73 sigma, applist (bo, args), params, typ
74
75 (* appliquer le chemin de coercions de patterns p *)
76 let apply_pattern_coercion ?loc pat p =
77 List.fold_left
78 (fun pat (co,n) ->
79 let f i =
80 if i<n then (DAst.make ?loc @@ Glob_term.PatVar Anonymous) else pat in
81 DAst.make ?loc @@ Glob_term.PatCstr (co, List.init (n+1) f, Anonymous))
82 pat p
83
84 (* raise Not_found if no coercion found *)
85 let inh_pattern_coerce_to ?loc env pat ind1 ind2 =
86 let p = lookup_pattern_path_between env (ind1,ind2) in
87 apply_pattern_coercion ?loc pat p
88
89 (* Program coercions *)
90
91 open Program
92
93 let make_existential ?loc ?(opaque = not (get_proofs_transparency ())) na env sigma c =
94 let src = Loc.tag ?loc (Evar_kinds.QuestionMark {
95 Evar_kinds.default_question_mark with
96 Evar_kinds.qm_obligation=Evar_kinds.Define opaque;
97 Evar_kinds.qm_name=na;
98 }) in
99 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma c in
100 let sigma, v = Evarutil.new_evar ~typeclass_candidate env sigma ~src c in
101 let sigma = Evd.set_obligation_evar sigma (fst (destEvar sigma v)) in
102 sigma, v
103
104 let app_opt env sigma f t =
105 let sigma, t =
106 match f with
107 | None -> sigma, t
108 | Some f -> f sigma t
109 in
110 sigma, whd_betaiota env sigma t
111
112 let pair_of_array a = (a.(0), a.(1))
113
114 let disc_subset env sigma x =
115 match EConstr.kind sigma x with
116 | App (c, l) ->
117 (match EConstr.kind sigma c with
118 Ind (i,_) ->
119 let len = Array.length l in
120 let sigty = delayed_force sig_typ in
121 if Int.equal len 2 && QInd.equal env i (Globnames.destIndRef sigty)
122 then
123 let (a, b) = pair_of_array l in
124 Some (a, b)
125 else None
126 | _ -> None)
127 | _ -> None
128
129 exception NoSubtacCoercion
130
131 let hnf env sigma c = whd_all env sigma c
132 let hnf_nodelta env sigma c = whd_betaiota env sigma c
133
134 let has_undefined_head_evar sigma c =
135 let rec hrec c = match kind sigma c with
136 | Evar (evk,_) -> true
137 | Case (_, _, _, _, _, c, _) -> hrec c
138 | App (c,_) -> hrec c
139 | Cast (c,_,_) -> hrec c
140 | Proj (_, _, c) -> hrec c
141 | _ -> false
142 in hrec c
143
144 let lift_args n sign =
145 let rec liftrec k = function
146 | t::sign -> liftn n k t :: (liftrec (k-1) sign)
147 | [] -> []
148 in
149 liftrec (List.length sign) sign
150
151 let coerce ?loc env sigma (x : EConstr.constr) (y : EConstr.constr)
152 : evar_map * (evar_map -> EConstr.constr -> evar_map * EConstr.constr) option
153 =
154 let open Context.Rel.Declaration in
155 let rec coerce_unify env sigma x y =
156 let x = hnf env sigma x and y = hnf env sigma y in
157 try
158 Evarconv.unify_leq_delay env sigma x y, None
159 with
160 Evarconv.UnableToUnify _ -> coerce' env sigma x y
161 and coerce' env sigma x y : evar_map * (evar_map -> EConstr.constr -> evar_map * EConstr.constr) option =
162 let subco sigma = subset_inferred env sigma x y in
163 let whd_decompose_prod c =
164 match Reductionops.whd_decompose_prod_n env sigma 1 c with
165 | ([(na, t)], c) -> (na, t), c
166 | _ -> raise NoSubtacCoercion (* should not happen: there are arguments to consume *)
167 in
168 let coerce_application sigma typ typ' c c' l l' =
169 let len = Array.length l in
170 let rec aux sigma tele typ typ' i co =
171 if i < len then
172 let hdx = l.(i) and hdy = l'.(i) in
173 try
174 let sigma = unify_leq_delay env sigma hdx hdy in
175 let (n, eqT), restT = whd_decompose_prod typ in
176 let (n', eqT'), restT' = whd_decompose_prod typ' in
177 aux sigma (hdx :: tele) (subst1 hdx restT) (subst1 hdy restT') (succ i) co
178 with UnableToUnify _ as exn ->
179 let _, info = Exninfo.capture exn in
180 let (n, eqT), restT = whd_decompose_prod typ in
181 let (n', eqT'), restT' = whd_decompose_prod typ' in
182 let sigma =
183 try
184 unify_leq_delay env sigma eqT eqT'
185 with UnableToUnify _ ->
186 let e, info = Exninfo.capture exn in
187 Exninfo.iraise (NoSubtacCoercion,info)
188 in
189 (* Disallow equalities on arities *)
190 if Reductionops.is_arity env sigma eqT then
191 Exninfo.iraise (NoSubtacCoercion,info);
192 let restargs = lift_args 1
193 (List.rev (Array.to_list (Array.sub l (succ i) (len - (succ i)))))
194 in
195 let args = List.rev (restargs @ mkRel 1 :: List.map (lift 1) tele) in
196 let pred = mkLambda (n, eqT, applist (lift 1 c, args)) in
197 let sigma, eq = papp env sigma coq_eq_ind [| eqT; hdx; hdy |] in
198 let sigma, evar = make_existential ?loc n.binder_name env sigma eq in
199 let eq_app sigma x = papp env sigma coq_eq_rect
200 [| eqT; hdx; pred; x; hdy; evar|]
201 in
202 aux sigma (hdy :: tele) (subst1 hdx restT)
203 (subst1 hdy restT') (succ i) (fun sigma x -> let sigma, x = co sigma x in eq_app sigma x)
204 else
205 sigma, Some (fun sigma x ->
206 let sigma, term = co sigma x in
207 let sigma, term = Typing.solve_evars env sigma term in
208 sigma, term)
209 in
210 if isEvar sigma c || isEvar sigma c' || not (Program.is_program_generalized_coercion ()) then
211 (* Second-order unification needed. *)
212 raise NoSubtacCoercion;
213 aux sigma [] typ typ' 0 (fun sigma x -> sigma, x)
214 in
215 match (EConstr.kind sigma x, EConstr.kind sigma y) with
216 | Sort s, Sort s' ->
217 (match ESorts.kind sigma s, ESorts.kind sigma s' with
218 | Prop, Prop | Set, Set -> sigma, None
219 | (Prop | Set), Type _ -> sigma, None
220 | Type x, Type y when Univ.Universe.equal x y -> sigma, None (* false *)
221 | _ -> subco sigma)
222 | Prod (name, a, b), Prod (name', a', b') ->
223 let name' =
224 {name' with
225 binder_name =
226 Name (Namegen.next_ident_away
227 Namegen.default_dependent_ident (Termops.vars_of_env env))}
228 in
229 let env' = push_rel (LocalAssum (name', a')) env in
230 let sigma, c1 = coerce_unify env' sigma (lift 1 a') (lift 1 a) in
231 (* env, x : a' |- c1 : lift 1 a' > lift 1 a *)
232 let sigma, coec1 = app_opt env' sigma c1 (mkRel 1) in
233 (* env, x : a' |- c1[x] : lift 1 a *)
234 let sigma, c2 = coerce_unify env' sigma (subst1 coec1 (liftn 1 2 b)) b' in
235 (* env, x : a' |- c2 : b[c1[x]/x]] > b' *)
236 (match c1, c2 with
237 | None, None -> sigma, None
238 | _, _ ->
239 sigma,
240 Some (fun sigma f ->
241 let sigma, t = app_opt env' sigma c2
242 (mkApp (lift 1 f, [| coec1 |])) in
243 sigma, mkLambda (name', a', t)))
244
245 | App (c, l), App (c', l') ->
246 (match EConstr.kind sigma c, EConstr.kind sigma c' with
247 Ind (i, u), Ind (i', u') -> (* Inductive types *)
248 let len = Array.length l in
249 let sigT = delayed_force sigT_typ in
250 let prod = delayed_force prod_typ in
251 (* Sigma types *)
252 if Int.equal len (Array.length l') && Int.equal len 2 && QInd.equal env i i'
253 && (QInd.equal env i (destIndRef sigT) || QInd.equal env i (destIndRef prod))
254 then
255 if QInd.equal env i (destIndRef sigT)
256 then
257 begin
258 let (a, pb), (a', pb') =
259 pair_of_array l, pair_of_array l'
260 in
261 let sigma, c1 = coerce_unify env sigma a a' in
262 let remove_head sigma a c =
263 match EConstr.kind sigma c with
264 | Lambda (n, t, t') -> sigma, (c, t')
265 | Evar (k, args) ->
266 let (sigma, t) = Evardefine.define_evar_as_lambda env sigma (k,args) in
267 let (n, dom, rng) = destLambda sigma t in
268 let sigma =
269 if isEvar sigma dom then
270 let (domk, args) = destEvar sigma dom in
271 define domk a sigma
272 else sigma
273 in
274 sigma, (t, rng)
275 | _ -> raise NoSubtacCoercion
276 in
277 let sigma, (pb, b) = remove_head sigma a pb in
278 let sigma, (pb', b') = remove_head sigma a' pb' in
279 let ra = Retyping.relevance_of_type env sigma a in
280 let env' = push_rel
281 (LocalAssum (make_annot (Name Namegen.default_dependent_ident) ra, a))
282 env
283 in
284 let sigma, c2 = coerce_unify env' sigma b b' in
285 match c1, c2 with
286 | None, None -> sigma, None
287 | _, _ ->
288 sigma,
289 Some (fun sigma x ->
290 let sigma, t1 = papp env sigma sigT_proj1 [| a; pb; x |] in
291 let sigma, t2 = papp env sigma sigT_proj2 [| a; pb; x |] in
292 let sigma, x = app_opt env' sigma c1 t1 in
293 let sigma, y = app_opt env' sigma c2 t2 in
294 papp env sigma sigT_intro [| a'; pb'; x ; y |])
295 end
296 else
297 begin
298 let (a, b), (a', b') =
299 pair_of_array l, pair_of_array l'
300 in
301 let sigma, c1 = coerce_unify env sigma a a' in
302 let sigma, c2 = coerce_unify env sigma b b' in
303 match c1, c2 with
304 | None, None -> sigma, None
305 | _, _ ->
306 sigma,
307 Some (fun sigma x ->
308 let sigma, t1 = papp env sigma prod_proj1 [| a; b; x |] in
309 let sigma, t2 = papp env sigma prod_proj2 [| a; b; x |] in
310 let sigma, x = app_opt env sigma c1 t1 in
311 let sigma, y = app_opt env sigma c2 t2 in
312 papp env sigma prod_intro [| a'; b'; x ; y |])
313 end
314 else
315 if QInd.equal env i i' && Int.equal len (Array.length l') then
316 (try subco sigma
317 with NoSubtacCoercion ->
318 let sigma, typ = Typing.type_of env sigma c in
319 let sigma, typ' = Typing.type_of env sigma c' in
320 coerce_application sigma typ typ' c c' l l')
321 else
322 subco sigma
323 | x, y when EConstr.eq_constr sigma c c' ->
324 if Int.equal (Array.length l) (Array.length l') then
325 let sigma, lam_type = Typing.type_of env sigma c in
326 let sigma, lam_type' = Typing.type_of env sigma c' in
327 coerce_application sigma lam_type lam_type' c c' l l'
328 else subco sigma
329 | _ -> subco sigma)
330 | _, _ -> subco sigma
331
332 and subset_inferred env sigma x y =
333 match disc_subset env sigma x with
334 Some (u, p) ->
335 let sigma, c = coerce_unify env sigma u y in
336 let f sigma x =
337 let sigma, t = papp env sigma sig_proj1 [| u; p; x |] in
338 app_opt env sigma c t
339 in sigma, Some f
340 | None ->
341 match disc_subset env sigma y with
342 Some (u, p) ->
343 let sigma, c = coerce_unify env sigma x u in
344 sigma, Some
345 (fun sigma x ->
346 let sigma, cx = app_opt env sigma c x in
347 let sigma, evar = make_existential ?loc Anonymous env sigma (mkApp (p, [| cx |]))
348 in
349 (papp env sigma sig_intro [| u; p; cx; evar |]))
350 | None ->
351 raise NoSubtacCoercion
352 in coerce_unify env sigma x y
353
354 let app_coercion env sigma coercion v =
355 match coercion with
356 | None -> sigma, v
357 | Some f ->
358 let sigma, v' = f sigma v in
359 let sigma, v' = Typing.solve_evars env sigma v' in
360 sigma, whd_betaiota env sigma v'
361
362 let coerce_itf ?loc env sigma v t c1 =
363 let sigma, coercion = coerce ?loc env sigma t c1 in
364 app_coercion env sigma coercion v
365
366 let saturate_evd env sigma =
367 Typeclasses.resolve_typeclasses
368 ~filter:Typeclasses.no_goals ~fail:false env sigma
369
370 type coercion_trace =
371 | IdCoe
372 | PrimProjCoe of {
373 proj : Projection.Repr.t;
374 relevance : ERelevance.t;
375 args : econstr list;
376 previous : coercion_trace;
377 }
378 | Coe of {
379 head : econstr;
380 args : econstr list;
381 previous : coercion_trace;
382 }
383 | ProdCoe of { na : Name.t binder_annot; ty : econstr; dom : coercion_trace; body : coercion_trace }
384 | ReplaceCoe of econstr
385
386 let empty_coercion_trace = IdCoe
387
388 (* similar to iterated apply_coercion_args *)
389 let rec reapply_coercions sigma trace c = match trace with
390 | IdCoe -> c
391 | ReplaceCoe c -> c
392 | PrimProjCoe { proj; relevance; args; previous } ->
393 let c = reapply_coercions sigma previous c in
394 let args = args@[c] in
395 let head, args = match args with [] -> assert false | hd :: tl -> hd, tl in
396 applist (mkProj (Projection.make proj false, relevance, head), args)
397 | Coe {head; args; previous} ->
398 let c = reapply_coercions sigma previous c in
399 let args = args@[c] in
400 applist (head, args)
401 | ProdCoe { na; ty; dom; body } ->
402 let x = reapply_coercions sigma dom (mkRel 1) in
403 let c = beta_applist sigma (lift 1 c, [x]) in
404 let c = reapply_coercions sigma body c in
405 mkLambda (na, ty, c)
406
407 let instance_of_global_constr sigma c =
408 match kind sigma c with
409 | Const (_,u) | Ind (_,u) | Construct (_,u) -> u
410 | _ -> EInstance.empty
411
412 (* Apply coercion path from p to h of type hty; raise NoCoercion if not applicable *)
413 let apply_coercion env sigma p h hty =
414 let j, jty, trace, sigma =
415 List.fold_left
416 (fun (j,jty,trace,sigma) i ->
417 let isid = i.coe_is_identity in
418 let isproj = i.coe_is_projection in
419 let sigma, c = Evd.fresh_global env sigma i.coe_value in
420 let u = instance_of_global_constr sigma c in
421 let isproj = Option.map (fun p ->
422 p, Retyping.relevance_of_projection_repr env (p,u))
423 isproj
424 in
425 let typ = Coercionops.coercion_type env sigma (i,u) in
426 let sigma, j', args, jty =
427 apply_coercion_args env sigma isproj c typ j jty i.coe_param in
428 let trace =
429 if isid then trace
430 else match isproj with
431 | None -> Coe {head=c;args;previous=trace}
432 | Some (proj,relevance) ->
433 let args = List.skipn (Projection.Repr.npars proj) args in
434 PrimProjCoe {proj; args; relevance; previous=trace } in
435 (if isid then j else j'), jty, trace, sigma)
436 (h, hty, IdCoe, sigma) p
437 in sigma, j, jty, trace
438
439 let remove_subset env sigma t =
440 let rec aux v =
441 let v' = hnf env sigma v in
442 match disc_subset env sigma v' with
443 | Some (u, p) ->
444 aux u
445 | None -> v
446 in
447 aux t
448
449 let mu env sigma t =
450 let rec aux v =
451 let v' = hnf env sigma v in
452 match disc_subset env sigma v' with
453 | Some (u, p) ->
454 let sigma, (f, ct, trace) = aux u in
455 let p = hnf_nodelta env sigma p in
456 let p1 = delayed_force sig_proj1 in
457 let sigma, p1 = Evd.fresh_global env sigma p1 in
458 sigma,
459 (Some (fun sigma x ->
460 app_opt env sigma
461 f (mkApp (p1, [| u; p; x |]))),
462 ct,
463 Coe {head=p1; args=[u;p]; previous=trace})
464 | None -> sigma, (None, v, IdCoe)
465 in aux t
466
467 let unify_product env sigma typ =
468 let t = whd_all env sigma typ in
469 match EConstr.kind sigma t with
470 | Prod _ -> Inl sigma
471 | Evar ev ->
472 let sigma, _ = Evardefine.define_evar_as_product env sigma ev in
473 Inl sigma
474 | _ ->
475 let sigma, (domain_hole, s) = Evarutil.new_type_evar env sigma Evd.univ_flexible in
476 let r = ESorts.relevance_of_sort s in
477 let na = make_annot Anonymous r in
478 let env' = push_rel Context.(Rel.Declaration.LocalAssum (na, domain_hole)) env in
479 let sigma, (codomain_hole, _) = Evarutil.new_type_evar env' sigma Evd.univ_flexible in
480 let prod = mkProd (na, domain_hole, codomain_hole) in
481 (* NB: unification needs the un-reduced type to do heuristics like canonical structures *)
482 try Inl (Evarconv.unify env sigma Conversion.CUMUL typ prod)
483 with PretypeError _ -> Inr t (* return the reduced type to avoid double reducing *)
484
485 (* Invariant: if [proj] is [Some] then [args_len < npars]
486 (and always [args_len = length rev_args + length args in head]) *)
487 type delayed_app_body = {
488 mutable head : constr;
489 mutable rev_args : constr list;
490 args_len : int;
491 proj : (Projection.Repr.t * ERelevance.t) option
492 }
493
494 let force_app_body ({head;rev_args} as body) =
495 let head = mkApp (head, Array.rev_of_list rev_args) in
496 body.head <- head;
497 body.rev_args <- [];
498 head
499
500 let push_arg {head;rev_args;args_len;proj} arg =
501 match proj with
502 | None ->
503 {
504 head;
505 rev_args=arg::rev_args;
506 args_len=args_len+1;
507 proj=None;
508 }
509 | Some (p,r) ->
510 let npars = Projection.Repr.npars p in
511 if Int.equal args_len npars then
512 {
513 head = mkProj (Projection.make p false, r, arg);
514 rev_args=[];
515 args_len=0;
516 proj=None;
517 }
518 else
519 {
520 head;
521 rev_args=arg::rev_args;
522 args_len=args_len+1;
523 proj;
524 }
525
526 let start_app_body sigma head =
527 let proj = match EConstr.kind sigma head with
528 | Const (p,u) ->
529 Structures.PrimitiveProjections.find_opt_with_relevance (p,u)
530 | _ -> None
531 in
532 {head; rev_args=[]; args_len=0; proj}
533
534 let reapply_coercions_body sigma trace body =
535 match trace with
536 | IdCoe -> body
537 | _ ->
538 let body = force_app_body body in
539 let body = reapply_coercions sigma trace body in
540 start_app_body sigma body
541
542 type expected = Type of types | Sort | Product
543
544 type hook = env -> evar_map -> flags:Evarconv.unify_flags -> constr ->
545 inferred:types -> expected:expected -> (evar_map * constr * constr) option
546
547 let all_hooks = ref (CString.Map.empty : hook CString.Map.t)
548
549 let register_hook ~name ?(override=false) h =
550 if not override && CString.Map.mem name !all_hooks then
551 CErrors.anomaly ~label:"Coercion.register_hook"
552 Pp.(str "Hook already registered: \"" ++ str name ++ str "\".");
553 all_hooks := CString.Map.add name h !all_hooks
554
555 let active_hooks = Summary.ref ~name:"coercion_hooks" ([] : string list)
556
557 let deactivate_hook ~name =
558 active_hooks := List.filter (fun s -> not (String.equal s name)) !active_hooks
559
560 let activate_hook ~name =
561 assert (CString.Map.mem name !all_hooks);
562 deactivate_hook ~name;
563 active_hooks := name :: !active_hooks
564
565 let apply_hooks env sigma ~flags body ~inferred ~expected =
566 List.find_map (fun name -> CString.Map.get name !all_hooks env sigma ~flags body ~inferred ~expected) !active_hooks
567
568 let default_flags_of env =
569 default_flags_of TransparentState.full
570
571 (* Try to coerce to a funclass; raise NoCoercion if not possible *)
572 let inh_app_fun_core ~program_mode ?(use_coercions=true) env sigma body typ =
573 match unify_product env sigma typ with
574 | Inl sigma -> sigma, body, typ, IdCoe
575 | Inr t ->
576 try
577 if not use_coercions then raise NoCoercion;
578 let p = lookup_path_to_fun_from env sigma typ in
579 let body = force_app_body body in
580 let sigma, body, typ, trace = apply_coercion env sigma p body typ in
581 sigma, start_app_body sigma body, typ, trace
582 with (Not_found | NoCoercion) as exn ->
583 let _, info = Exninfo.capture exn in
584 if program_mode then
585 try
586 let sigma, (coercef, t, trace) = mu env sigma t in
587 let j = {uj_val=force_app_body body; uj_type = typ} in
588 let sigma, uj_val = app_opt env sigma coercef j.uj_val in
589 (sigma, start_app_body sigma uj_val, t, trace)
590 with NoSubtacCoercion | NoCoercion ->
591 (sigma,body,typ,IdCoe)
592 else Exninfo.iraise (NoCoercion,info)
593
594 (* Try to coerce to a funclass; returns [j] if no coercion is applicable *)
595 let inh_app_fun ~program_mode ~resolve_tc ?use_coercions env sigma ?(flags=default_flags_of env) body typ =
596 try
597 try inh_app_fun_core ~program_mode ?use_coercions env sigma body typ
598 with
599 | NoCoercion when resolve_tc
600 && (get_use_typeclasses_for_conversion ()) ->
601 inh_app_fun_core ~program_mode ?use_coercions env (saturate_evd env sigma) body typ
602 with
603 | NoCoercion -> match apply_hooks env sigma ~flags (force_app_body body) ~inferred:typ ~expected:Product with
604 | Some (sigma, r, typ) -> (sigma, start_app_body sigma r, typ, ReplaceCoe r)
605 | None -> (sigma, body, typ, IdCoe)
606
607 let type_judgment env sigma j =
608 match EConstr.kind sigma (whd_all env sigma j.uj_type) with
609 | Sort s -> {utj_val = j.uj_val; utj_type = s }
610 | _ -> error_not_a_type env sigma j
611
612 let inh_tosort_force ?loc env sigma ?(flags=default_flags_of env) ({ uj_val; uj_type } as j) =
613 try
614 let p = lookup_path_to_sort_from env sigma uj_type in
615 let sigma, uj_val, uj_type,_trace = apply_coercion env sigma p uj_val uj_type in
616 let j2 = Environ.on_judgment_type (whd_evar sigma) { uj_val ; uj_type } in
617 (sigma, type_judgment env sigma j2)
618 with Not_found | NoCoercion -> match apply_hooks env sigma ~flags uj_val ~inferred:uj_type ~expected:Sort with
619 | Some (sigma, r, typ) -> let j2 = Environ.on_judgment_type (whd_evar sigma) { uj_val = r ; uj_type = typ } in
620 (sigma, type_judgment env sigma j2)
621 | None -> error_not_a_type ?loc env sigma j
622
623 let inh_coerce_to_sort ?loc ?(use_coercions=true) env sigma j =
624 let typ = whd_all env sigma j.uj_type in
625 match EConstr.kind sigma typ with
626 | Sort s -> (sigma,{ utj_val = j.uj_val; utj_type = s })
627 | Evar ev ->
628 let (sigma,s) = Evardefine.define_evar_as_sort env sigma ev in
629 (sigma,{ utj_val = j.uj_val; utj_type = s })
630 | _ ->
631 if use_coercions then inh_tosort_force ?loc env sigma j
632 else error_not_a_type ?loc env sigma j
633
634 let inh_coerce_to_base ?loc ~program_mode env sigma j =
635 if program_mode then
636 let sigma, (ct, typ', _trace) = mu env sigma j.uj_type in
637 let sigma, uj_val = app_coercion env sigma ct j.uj_val in
638 let res = { uj_val; uj_type = typ' } in
639 sigma, res
640 else (sigma, j)
641
642 let class_has_args = function
643 | CL_FUN
644 | CL_SORT -> false
645 | _ -> true
646 let lookup_path_between_class_reflexive (c1,c2) =
647 if c1 = c2 then []
648 else lookup_path_between_class (c1,c2)
649
650 (* We find a path to a common class such that the path from src_expected is
651 reversible (the casted term is unknown but inferrable via unification,
652 eg CS inference) *)
653 let lookup_reversible_path_to_common_point env sigma ~src_expected ~src_inferred =
654 let _, c_expected = class_of env sigma src_expected in
655 let _, c_inferred = class_of env sigma src_inferred in
656 let reachable_from_expected = reachable_from c_expected in
657 let reachable_from_inferred = reachable_from c_inferred in
658 let r = ClTypSet.(elements (inter reachable_from_expected reachable_from_inferred)) in
659 (* XXX this order relation is not total ... *)
660 let r = List.sort (fun c1 c2 -> if ClTypSet.mem c1 (reachable_from c2) then 1 else -1) r in
661 let r = (if ClTypSet.mem c_inferred reachable_from_expected then [c_inferred] else []) @ r in
662 (* This is unneeded since there is a dedicated case in inh_coerce_to_fail:
663 let r = (if ClTypSet.mem c_expected reachable_from_inferred then [c_expected] else []) @ r in *)
664 let rec aux = function
665 | [] -> raise Not_found
666 | c :: cs ->
667 let reversible = lookup_path_between_class_reflexive (c_expected,c) in
668 if path_is_reversible reversible then
669 let direct = lookup_path_between_class_reflexive (c_inferred,c) in
670 class_has_args c_expected, class_has_args c_inferred, reversible, direct
671 else
672 aux cs
673 in
674 aux r
675
676 let add_reverse_coercion env sigma v'_ty v_ty v' v =
677 match Rocqlib.lib_ref_opt "core.coercion.reverse_coercion" with
678 | None -> sigma, v'
679 | Some reverse_coercion ->
680 let sigma, v'_ty =
681 Evarsolve.refresh_universes ~onlyalg:true ~status:Evd.univ_flexible
682 (Some false) env sigma v'_ty in
683 let sigma, v_ty =
684 Evarsolve.refresh_universes ~onlyalg:true ~status:Evd.univ_flexible
685 (Some false) env sigma v_ty in
686 let sigma, reverse_coercion = Evd.fresh_global env sigma reverse_coercion in
687 Typing.checked_appvect env sigma reverse_coercion [| v'_ty; v_ty; v'; v |]
688
689 let inh_coerce_to_fail ?(use_coercions=true) flags env sigma rigidonly v v_ty target_type =
690 if not use_coercions || (rigidonly && not (Heads.is_rigid env sigma target_type && Heads.is_rigid env sigma v_ty))
691 then
692 raise NoCoercion
693 else
694 try
695 let sigma, v', v'_ty, trace =
696 try
697 (* 1 path c of direct coercions *)
698 let c = lookup_path_between env sigma ~src:v_ty ~tgt:target_type in
699 apply_coercion env sigma c v v_ty
700 with Not_found ->
701 (* 2 paths: one of direct coercions, one of reversible coercions *)
702 let target_type_has_args, v_ty_has_args, reversible, direct =
703 lookup_reversible_path_to_common_point env sigma ~src_expected:target_type ~src_inferred:v_ty in
704 if not (v_ty_has_args || target_type_has_args) then raise Not_found;
705 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma target_type in
706 let sigma, x = Evarutil.new_evar ~typeclass_candidate env sigma target_type in
707 let sigma, rev_x, _, _ = apply_coercion env sigma reversible x target_type in
708 let sigma, direct_v, _, _ = apply_coercion env sigma direct v v_ty in
709 let sigma = unify_leq_delay ~flags env sigma direct_v rev_x in
710 if has_undefined_head_evar sigma x then raise Not_found;
711 let sigma, rev_x = add_reverse_coercion env sigma target_type v_ty x v in
712 sigma, rev_x, target_type, ReplaceCoe rev_x
713 in
714 unify_leq_delay ~flags env sigma v'_ty target_type, v', trace
715 with (Evarconv.UnableToUnify _ | Not_found) as exn ->
716 let _, info = Exninfo.capture exn in
717 (* 3 if none of the above works, try hook *)
718 match apply_hooks env sigma ~flags v ~inferred:v_ty ~expected:(Type target_type) with
719 | Some (sigma, r, _) -> (sigma, r, ReplaceCoe r)
720 | None -> Exninfo.iraise (NoCoercion,info)
721
722 let rec inh_conv_coerce_to_fail ?loc ?use_coercions env sigma ?(flags=default_flags_of env) rigidonly v t c1 =
723 try (unify_leq_delay ~flags env sigma t c1, v, IdCoe)
724 with UnableToUnify (best_failed_sigma,e) as exn ->
725 let _, info = Exninfo.capture exn in
726 try inh_coerce_to_fail ?use_coercions flags env sigma rigidonly v t c1
727 with NoCoercion ->
728 match
729 EConstr.kind sigma (whd_all env sigma t),
730 EConstr.kind sigma (whd_all env sigma c1)
731 with
732 | Prod (name,t1,t2), Prod (_,u1,u2) ->
733 (* Conversion did not work, we may succeed with a coercion. *)
734 (* We eta-expand (hence possibly modifying the original term!) *)
735 (* and look for a coercion c:u1->t1 s.t. fun x:u1 => v' (c x)) *)
736 (* has type forall (x:u1), u2 (with v' recursively obtained) *)
737 (* Note: we retype the term because template polymorphism may have *)
738 (* weakened its type *)
739 let name = map_annot (function
740 | Anonymous -> Name Namegen.default_dependent_ident
741 | na -> na) name in
742 let open Context.Rel.Declaration in
743 let env1 = push_rel (LocalAssum (name,u1)) env in
744 let (sigma, v1, trace1) =
745 inh_conv_coerce_to_fail ?loc ?use_coercions env1 sigma rigidonly
746 (mkRel 1) (lift 1 u1) (lift 1 t1) in
747 let v2 = beta_applist sigma (lift 1 v,[v1]) in
748 let t2 = Retyping.get_type_of env1 sigma v2 in
749 let (sigma,v2',trace2) = inh_conv_coerce_to_fail ?loc ?use_coercions env1 sigma rigidonly v2 t2 u2 in
750 let trace = ProdCoe { na=name; ty=u1; dom=trace1; body=trace2 } in
751 (sigma, mkLambda (name, u1, v2'), trace)
752 | _ ->
753 Exninfo.iraise (NoCoercionNoUnifier (best_failed_sigma,e), info)
754
755 let default_flags_of env sigma =
756 { (default_flags_of env) with allowed_evars = Evarsolve.allow_all_but_rrpat_evars sigma }
757
758 (* Look for cj' obtained from cj by inserting coercions, s.t. cj'.typ = t *)
759 let inh_conv_coerce_to_gen ?loc ~program_mode ~resolve_tc ?use_coercions rigidonly env sigma ?(flags=default_flags_of env sigma) cj t =
760 let (sigma, val', otrace) =
761 try
762 let (sigma, val', trace) = inh_conv_coerce_to_fail ?loc ?use_coercions env sigma ~flags rigidonly cj.uj_val cj.uj_type t in
763 (sigma, val', Some trace)
764 with NoCoercionNoUnifier (best_failed_sigma,e) as exn ->
765 let _, info = Exninfo.capture exn in
766 try
767 if program_mode then
768 let (sigma, val') = coerce_itf ?loc env sigma cj.uj_val cj.uj_type t in
769 (sigma, val', None)
770 else Exninfo.iraise (NoSubtacCoercion,info)
771 with
772 | NoSubtacCoercion as exn when not resolve_tc || not (get_use_typeclasses_for_conversion ()) ->
773 let _, info = Exninfo.capture exn in
774 error_actual_type ?loc ~info env best_failed_sigma cj t e
775 | NoSubtacCoercion as exn ->
776 let _, info = Exninfo.capture exn in
777 let sigma' = saturate_evd env sigma in
778 try
779 if sigma' == sigma then
780 error_actual_type ?loc ~info env best_failed_sigma cj t e
781 else
782 let sigma = sigma' in
783 let (sigma, val', trace) = inh_conv_coerce_to_fail ?loc ?use_coercions env sigma rigidonly cj.uj_val cj.uj_type t in
784 (sigma, val', Some trace)
785 with NoCoercionNoUnifier (_sigma,_error) as exn ->
786 let _, info = Exninfo.capture exn in
787 error_actual_type ?loc ~info env best_failed_sigma cj t e
788 in
789 (sigma,{ uj_val = val'; uj_type = t },otrace)
790
791 let inh_conv_coerce_to_gen ?loc ~program_mode ~resolve_tc ?use_coercions rigidonly env sigma ?flags cj t =
792 try inh_conv_coerce_to_gen ?loc ~program_mode ~resolve_tc ?use_coercions rigidonly env sigma ?flags cj t
793 with e when Option.has_some loc ->
794 let _, info as iexn = Exninfo.capture e in
795 match Loc.get_loc info with
796 | Some _ -> Exninfo.iraise iexn
797 | None -> Exninfo.iraise (e, Loc.add_loc info (Option.get loc))
798
799 let inh_conv_coerce_to ?loc ~program_mode ~resolve_tc ?use_coercions env sigma ?flags =
800 inh_conv_coerce_to_gen ?loc ~program_mode ~resolve_tc ?use_coercions false ?flags env sigma
801 let inh_conv_coerce_rigid_to ?loc ~program_mode ~resolve_tc ?use_coercions env sigma ?flags =
802 inh_conv_coerce_to_gen ?loc ~program_mode ~resolve_tc ?use_coercions true ?flags env sigma