]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicMetaSubst.ml
4441fa16921b0852410b5a83c408dcc95f72f4df
[helm.git] / helm / software / components / ng_refiner / nCicMetaSubst.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14
15 (*open Printf
16
17 (* PROFILING *)
18 (*
19 let deref_counter = ref 0
20 let apply_subst_context_counter = ref 0
21 let apply_subst_metasenv_counter = ref 0
22 let lift_counter = ref 0
23 let subst_counter = ref 0
24 let whd_counter = ref 0
25 let are_convertible_counter = ref 0
26 let metasenv_length = ref 0
27 let context_length = ref 0
28 let reset_counters () =
29  apply_subst_counter := 0;
30  apply_subst_context_counter := 0;
31  apply_subst_metasenv_counter := 0;
32  lift_counter := 0;
33  subst_counter := 0;
34  whd_counter := 0;
35  are_convertible_counter := 0;
36  metasenv_length := 0;
37  context_length := 0
38 let print_counters () =
39   debug_print (lazy (Printf.sprintf
40 "apply_subst: %d
41 apply_subst_context: %d
42 apply_subst_metasenv: %d
43 lift: %d
44 subst: %d
45 whd: %d
46 are_convertible: %d
47 metasenv length: %d (avg = %.2f)
48 context length: %d (avg = %.2f)
49 "
50   !apply_subst_counter !apply_subst_context_counter
51   !apply_subst_metasenv_counter !lift_counter !subst_counter !whd_counter
52   !are_convertible_counter !metasenv_length
53   ((float !metasenv_length) /. (float !apply_subst_metasenv_counter))
54   !context_length
55   ((float !context_length) /. (float !apply_subst_context_counter))
56   ))*)
57
58
59
60 exception MetaSubstFailure of string Lazy.t
61 exception Uncertain of string Lazy.t
62 exception AssertFailure of string Lazy.t
63 exception DeliftingARelWouldCaptureAFreeVariable;;
64
65 let debug_print = fun _ -> ()
66
67 type substitution = (int * (Cic.context * Cic.term)) list
68
69 (* 
70 let rec deref subst =
71   let third _,_,a = a in
72   function
73       Cic.Meta(n,l) as t -> 
74         (try 
75            deref subst
76              (CicSubstitution.subst_meta 
77                 l (third (CicUtil.lookup_subst n subst))) 
78          with 
79            CicUtil.Subst_not_found _ -> t)
80     | t -> t
81 ;;
82 *)
83
84 let lookup_subst = CicUtil.lookup_subst
85 ;;
86
87 (* clean_up_meta take a metasenv and a term and make every local context
88 of each occurrence of a metavariable consistent with its canonical context, 
89 with respect to the hidden hipothesis *)
90
91 (*
92 let clean_up_meta subst metasenv t =
93   let module C = Cic in
94   let rec aux t =
95   match t with
96       C.Rel _
97     | C.Sort _  -> t
98     | C.Implicit _ -> assert false
99     | C.Meta (n,l) as t ->
100         let cc =
101           (try
102              let (cc,_) = lookup_subst n subst in cc
103            with CicUtil.Subst_not_found _ ->
104              try
105                let (_,cc,_) = CicUtil.lookup_meta n metasenv in cc
106              with CicUtil.Meta_not_found _ -> assert false) in
107         let l' = 
108           (try 
109              List.map2
110                (fun t1 t2 ->
111                   match t1,t2 with 
112                       None , _ -> None
113                     | _ , t -> t) cc l
114            with 
115                Invalid_argument _ -> assert false) in
116         C.Meta (n, l')
117     | C.Cast (te,ty) -> C.Cast (aux te, aux ty)
118     | C.Prod (name,so,dest) -> C.Prod (name, aux so, aux dest)
119     | C.Lambda (name,so,dest) -> C.Lambda (name, aux so, aux dest)
120     | C.LetIn (name,so,dest) -> C.LetIn (name, aux so, aux dest)
121     | C.Appl l -> C.Appl (List.map aux l)
122     | C.Var (uri,exp_named_subst) ->
123         let exp_named_subst' =
124           List.map (fun (uri,t) -> (uri, aux t)) exp_named_subst
125         in
126         C.Var (uri, exp_named_subst')
127     | C.Const (uri, exp_named_subst) ->
128         let exp_named_subst' =
129           List.map (fun (uri,t) -> (uri, aux t)) exp_named_subst
130         in
131         C.Const (uri, exp_named_subst')
132     | C.MutInd (uri,tyno,exp_named_subst) ->
133         let exp_named_subst' =
134           List.map (fun (uri,t) -> (uri, aux t)) exp_named_subst
135         in
136         C.MutInd (uri, tyno, exp_named_subst')
137     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
138         let exp_named_subst' =
139           List.map (fun (uri,t) -> (uri, aux t)) exp_named_subst
140         in
141         C.MutConstruct (uri, tyno, consno, exp_named_subst')
142     | C.MutCase (uri,tyno,out,te,pl) ->
143         C.MutCase (uri, tyno, aux out, aux te, List.map aux pl)
144     | C.Fix (i,fl) ->
145        let fl' =
146          List.map
147           (fun (name,j,ty,bo) -> (name, j, aux ty, aux bo)) fl
148        in
149        C.Fix (i, fl')
150     | C.CoFix (i,fl) ->
151        let fl' =
152          List.map
153           (fun (name,ty,bo) -> (name, aux ty, aux bo)) fl
154        in
155        C.CoFix (i, fl')
156  in
157  aux t *)
158
159 (*** Functions to apply a substitution ***)
160
161 let apply_subst_gen ~appl_fun subst term =
162  let rec um_aux =
163   let module C = Cic in
164   let module S = CicSubstitution in 
165    function
166       C.Rel _ as t -> t
167     | C.Var (uri,exp_named_subst) ->
168        let exp_named_subst' =
169          List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
170        in
171        C.Var (uri, exp_named_subst')
172     | C.Meta (i, l) -> 
173         (try
174           let (_, t,_) = lookup_subst i subst in
175           um_aux (S.subst_meta l t)
176         with CicUtil.Subst_not_found _ -> 
177           (* unconstrained variable, i.e. free in subst*)
178           let l' =
179             List.map (function None -> None | Some t -> Some (um_aux t)) l
180           in
181            C.Meta (i,l'))
182     | C.Sort _
183     | C.Implicit _ as t -> t
184     | C.Cast (te,ty) -> C.Cast (um_aux te, um_aux ty)
185     | C.Prod (n,s,t) -> C.Prod (n, um_aux s, um_aux t)
186     | C.Lambda (n,s,t) -> C.Lambda (n, um_aux s, um_aux t)
187     | C.LetIn (n,s,ty,t) -> C.LetIn (n, um_aux s, um_aux ty, um_aux t)
188     | C.Appl (hd :: tl) -> appl_fun um_aux hd tl
189     | C.Appl _ -> assert false
190     | C.Const (uri,exp_named_subst) ->
191        let exp_named_subst' =
192          List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
193        in
194        C.Const (uri, exp_named_subst')
195     | C.MutInd (uri,typeno,exp_named_subst) ->
196        let exp_named_subst' =
197          List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
198        in
199        C.MutInd (uri,typeno,exp_named_subst')
200     | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
201        let exp_named_subst' =
202          List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
203        in
204        C.MutConstruct (uri,typeno,consno,exp_named_subst')
205     | C.MutCase (sp,i,outty,t,pl) ->
206        let pl' = List.map um_aux pl in
207        C.MutCase (sp, i, um_aux outty, um_aux t, pl')
208     | C.Fix (i, fl) ->
209        let fl' =
210          List.map (fun (name, i, ty, bo) -> (name, i, um_aux ty, um_aux bo)) fl
211        in
212        C.Fix (i, fl')
213     | C.CoFix (i, fl) ->
214        let fl' =
215          List.map (fun (name, ty, bo) -> (name, um_aux ty, um_aux bo)) fl
216        in
217        C.CoFix (i, fl')
218  in
219   um_aux term
220 ;;
221
222 let apply_subst =
223   let appl_fun um_aux he tl =
224     let tl' = List.map um_aux tl in
225     let t' =
226      match um_aux he with
227         Cic.Appl l -> Cic.Appl (l@tl')
228       | he' -> Cic.Appl (he'::tl')
229     in
230      begin
231       match he with
232          Cic.Meta (m,_) -> CicReduction.head_beta_reduce t'
233        | _ -> t'
234      end
235   in
236   fun subst t ->
237 (*     incr apply_subst_counter; *)
238 match subst with
239    [] -> t
240  | _ -> apply_subst_gen ~appl_fun subst t
241 ;;
242
243 let profiler = HExtlib.profile "U/CicMetaSubst.apply_subst"
244 let apply_subst s t = 
245   profiler.HExtlib.profile (apply_subst s) t
246
247
248 let apply_subst_context subst context =
249  match subst with
250     [] -> context
251   | _ ->
252 (*
253   incr apply_subst_context_counter;
254   context_length := !context_length + List.length context;
255 *)
256   List.fold_right
257     (fun item context ->
258       match item with
259       | Some (n, Cic.Decl t) ->
260           let t' = apply_subst subst t in
261           Some (n, Cic.Decl t') :: context
262       | Some (n, Cic.Def (t, ty)) ->
263           let ty' = apply_subst subst ty in
264           let t' = apply_subst subst t in
265           Some (n, Cic.Def (t', ty')) :: context
266       | None -> None :: context)
267     context []
268
269 let apply_subst_metasenv subst metasenv =
270 (*
271   incr apply_subst_metasenv_counter;
272   metasenv_length := !metasenv_length + List.length metasenv;
273 *)
274 match subst with
275    [] -> metasenv
276  | _ ->
277   List.map
278     (fun (n, context, ty) ->
279       (n, apply_subst_context subst context, apply_subst subst ty))
280     (List.filter
281       (fun (i, _, _) -> not (List.mem_assoc i subst))
282       metasenv)
283
284 (***** Pretty printing functions ******)
285
286 let ppterm ~metasenv subst term =
287  CicPp.ppterm ~metasenv (apply_subst subst term)
288
289 let ppterm_in_name_context ~metasenv subst term name_context =
290  CicPp.pp ~metasenv (apply_subst subst term) name_context
291
292 let ppterm_in_context ~metasenv subst term context =
293  let name_context =
294   List.map (function None -> None | Some (n,_) -> Some n) context
295  in
296   ppterm_in_name_context ~metasenv subst term name_context
297
298 let ppterm_in_context_ref = ref ppterm_in_context
299 let set_ppterm_in_context f =
300  ppterm_in_context_ref := f
301 let use_low_level_ppterm_in_context = ref false
302
303 let ppterm_in_context ~metasenv subst term context =
304  if !use_low_level_ppterm_in_context then
305   ppterm_in_context ~metasenv subst term context
306  else
307   !ppterm_in_context_ref ~metasenv subst term context
308
309 let ppcontext' ~metasenv ?(sep = "\n") subst context =
310  let separate s = if s = "" then "" else s ^ sep in
311   List.fold_right 
312    (fun context_entry (i,name_context) ->
313      match context_entry with
314         Some (n,Cic.Decl t) ->
315          sprintf "%s%s : %s" (separate i) (CicPp.ppname n)
316           (ppterm_in_name_context ~metasenv subst t name_context),
317           (Some n)::name_context
318       | Some (n,Cic.Def (bo,ty)) ->
319          sprintf "%s%s : %s := %s" (separate i) (CicPp.ppname n)
320           (ppterm_in_name_context ~metasenv subst ty name_context)
321           (ppterm_in_name_context ~metasenv subst bo name_context), (Some n)::name_context
322        | None ->
323           sprintf "%s_ :? _" (separate i), None::name_context
324     ) context ("",[])
325
326 let ppsubst_unfolded ~metasenv subst =
327   String.concat "\n"
328     (List.map
329       (fun (idx, (c, t,ty)) ->
330         let context,name_context = ppcontext' ~metasenv ~sep:"; " subst c in
331          sprintf "%s |- ?%d : %s := %s" context idx
332 (ppterm_in_name_context ~metasenv [] ty name_context)
333           (ppterm_in_name_context ~metasenv subst t name_context))
334        subst)
335 (* 
336         Printf.sprintf "?%d := %s" idx (CicPp.ppterm term))
337       subst) *)
338 ;;
339
340 let ppsubst ~metasenv subst =
341   String.concat "\n"
342     (List.map
343       (fun (idx, (c, t, ty)) ->
344         let context,name_context = ppcontext' ~metasenv ~sep:"; " [] c in
345          sprintf "%s |- ?%d : %s := %s" context idx (ppterm_in_name_context ~metasenv [] ty name_context)
346           (ppterm_in_name_context ~metasenv [] t name_context))
347        subst)
348 ;;
349
350 let ppcontext ~metasenv ?sep subst context =
351  fst (ppcontext' ~metasenv ?sep subst context)
352
353 let ppmetasenv ?(sep = "\n") subst metasenv =
354   String.concat sep
355     (List.map
356       (fun (i, c, t) ->
357         let context,name_context = ppcontext' ~metasenv ~sep:"; " subst c in
358          sprintf "%s |- ?%d: %s" context i
359           (ppterm_in_name_context ~metasenv subst t name_context))
360       (List.filter
361         (fun (i, _, _) -> not (List.mem_assoc i subst))
362         metasenv))
363
364 let tempi_type_of_aux_subst = ref 0.0;;
365 let tempi_subst = ref 0.0;;
366 let tempi_type_of_aux = ref 0.0;;
367
368 (**** DELIFT ****)
369 (* the delift function takes in input a metavariable index, an ordered list of
370  * optional terms [t1,...,tn] and a term t, and substitutes every tk = Some
371  * (rel(nk)) with rel(k).  Typically, the list of optional terms is the explicit
372  * substitution that is applied to a metavariable occurrence and the result of
373  * the delift function is a term the implicit variable can be substituted with
374  * to make the term [t] unifiable with the metavariable occurrence.  In general,
375  * the problem is undecidable if we consider equivalence in place of alpha
376  * convertibility. Our implementation, though, is even weaker than alpha
377  * convertibility, since it replace the term [tk] if and only if [tk] is a Rel
378  * (missing all the other cases). Does this matter in practice?
379  * The metavariable index is the index of the metavariable that must not occur
380  * in the term (for occur check).
381  *)
382
383 exception NotInTheList;;
384
385 let position n =
386   let rec aux k =
387    function 
388        [] -> raise NotInTheList
389      | (Some (Cic.Rel m))::_ when m=n -> k
390      | _::tl -> aux (k+1) tl in
391   aux 1
392 ;;
393
394 exception Occur;;
395
396 let rec force_does_not_occur subst to_be_restricted t =
397  let module C = Cic in
398  let more_to_be_restricted = ref [] in
399  let rec aux k = function
400       C.Rel r when List.mem (r - k) to_be_restricted -> raise Occur
401     | C.Rel _
402     | C.Sort _ as t -> t
403     | C.Implicit _ -> assert false
404     | C.Meta (n, l) ->
405        (* we do not retrieve the term associated to ?n in subst since *)
406        (* in this way we can restrict if something goes wrong         *)
407        let l' =
408          let i = ref 0 in
409          List.map
410            (function t ->
411              incr i ;
412              match t with
413                 None -> None
414               | Some t ->
415                  try
416                    Some (aux k t)
417                  with Occur ->
418                    more_to_be_restricted := (n,!i) :: !more_to_be_restricted;
419                    None)
420            l
421        in
422         C.Meta (n, l')
423     | C.Cast (te,ty) -> C.Cast (aux k te, aux k ty)
424     | C.Prod (name,so,dest) -> C.Prod (name, aux k so, aux (k+1) dest)
425     | C.Lambda (name,so,dest) -> C.Lambda (name, aux k so, aux (k+1) dest)
426     | C.LetIn (name,so,ty,dest) ->
427        C.LetIn (name, aux k so, aux k ty, aux (k+1) dest)
428     | C.Appl l -> C.Appl (List.map (aux k) l)
429     | C.Var (uri,exp_named_subst) ->
430         let exp_named_subst' =
431           List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
432         in
433         C.Var (uri, exp_named_subst')
434     | C.Const (uri, exp_named_subst) ->
435         let exp_named_subst' =
436           List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
437         in
438         C.Const (uri, exp_named_subst')
439     | C.MutInd (uri,tyno,exp_named_subst) ->
440         let exp_named_subst' =
441           List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
442         in
443         C.MutInd (uri, tyno, exp_named_subst')
444     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
445         let exp_named_subst' =
446           List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
447         in
448         C.MutConstruct (uri, tyno, consno, exp_named_subst')
449     | C.MutCase (uri,tyno,out,te,pl) ->
450         C.MutCase (uri, tyno, aux k out, aux k te, List.map (aux k) pl)
451     | C.Fix (i,fl) ->
452        let len = List.length fl in
453        let k_plus_len = k + len in
454        let fl' =
455          List.map
456           (fun (name,j,ty,bo) -> (name, j, aux k ty, aux k_plus_len bo)) fl
457        in
458        C.Fix (i, fl')
459     | C.CoFix (i,fl) ->
460        let len = List.length fl in
461        let k_plus_len = k + len in
462        let fl' =
463          List.map
464           (fun (name,ty,bo) -> (name, aux k ty, aux k_plus_len bo)) fl
465        in
466        C.CoFix (i, fl')
467  in
468  let res = aux 0 t in
469  (!more_to_be_restricted, res)
470  
471 let rec restrict subst to_be_restricted metasenv =
472  match to_be_restricted with
473  | [] -> metasenv, subst
474  | _ ->
475   let names_of_context_indexes context indexes =
476     String.concat ", "
477       (List.map
478         (fun i ->
479           try
480            match List.nth context (i-1) with
481            | None -> assert false
482            | Some (n, _) -> CicPp.ppname n
483           with
484            Failure _ -> assert false
485         ) indexes)
486   in
487   let force_does_not_occur_in_context to_be_restricted = function
488     | None -> [], None
489     | Some (name, Cic.Decl t) ->
490         let (more_to_be_restricted, t') =
491           force_does_not_occur subst to_be_restricted t
492         in
493         more_to_be_restricted, Some (name, Cic.Decl t')
494     | Some (name, Cic.Def (bo, ty)) ->
495         let (more_to_be_restricted, bo') =
496           force_does_not_occur subst to_be_restricted bo
497         in
498         let more_to_be_restricted, ty' =
499          let more_to_be_restricted', ty' =
500            force_does_not_occur subst to_be_restricted ty
501          in
502          more_to_be_restricted @ more_to_be_restricted',
503          ty'
504         in
505         more_to_be_restricted, Some (name, Cic.Def (bo', ty'))
506   in
507   let rec erase i to_be_restricted n = function
508     | [] -> [], to_be_restricted, []
509     | hd::tl ->
510         let more_to_be_restricted,restricted,tl' =
511           erase (i+1) to_be_restricted n tl
512         in
513         let restrict_me = List.mem i restricted in
514         if restrict_me then
515           more_to_be_restricted, restricted, None:: tl'
516         else
517           (try
518             let more_to_be_restricted', hd' =
519               let delifted_restricted =
520                let rec aux =
521                 function
522                    [] -> []
523                  | j::tl when j > i -> (j - i)::aux tl
524                  | _::tl -> aux tl
525                in
526                 aux restricted
527               in
528                force_does_not_occur_in_context delifted_restricted hd
529             in
530              more_to_be_restricted @ more_to_be_restricted',
531              restricted, hd' :: tl'
532           with Occur ->
533             more_to_be_restricted, (i :: restricted), None :: tl')
534   in
535   let (more_to_be_restricted, metasenv) =  (* restrict metasenv *)
536     List.fold_right
537       (fun (n, context, t) (more, metasenv) ->
538         let to_be_restricted =
539           List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
540         in
541         let (more_to_be_restricted, restricted, context') =
542          (* just an optimization *)
543          if to_be_restricted = [] then
544           [],[],context
545          else
546           erase 1 to_be_restricted n context
547         in
548         try
549           let more_to_be_restricted', t' =
550             force_does_not_occur subst restricted t
551           in
552           let metasenv' = (n, context', t') :: metasenv in
553           (more @ more_to_be_restricted @ more_to_be_restricted',
554           metasenv')
555         with Occur ->
556           raise (MetaSubstFailure (lazy (sprintf
557             "Cannot restrict the context of the metavariable ?%d over the hypotheses %s since metavariable's type depends on at least one of them"
558             n (names_of_context_indexes context to_be_restricted)))))
559       metasenv ([], [])
560   in
561   let (more_to_be_restricted', subst) = (* restrict subst *)
562     List.fold_right
563       (* TODO: cambiare dopo l'aggiunta del ty *)
564       (fun (n, (context, term,ty)) (more, subst') ->
565         let to_be_restricted =
566           List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
567         in
568         (try
569           let (more_to_be_restricted, restricted, context') =
570            (* just an optimization *)
571             if to_be_restricted = [] then
572               [], [], context
573             else
574               erase 1 to_be_restricted n context
575           in
576           let more_to_be_restricted', term' =
577             force_does_not_occur subst restricted term
578           in
579           let more_to_be_restricted'', ty' =
580             force_does_not_occur subst restricted ty in
581           let subst' = (n, (context', term',ty')) :: subst' in
582           let more = 
583             more @ more_to_be_restricted 
584             @ more_to_be_restricted'@more_to_be_restricted'' in
585           (more, subst')
586         with Occur ->
587           let error_msg = lazy (sprintf
588             "Cannot restrict the context of the metavariable ?%d over the hypotheses %s since ?%d is already instantiated with %s and at least one of the hypotheses occurs in the substituted term"
589             n (names_of_context_indexes context to_be_restricted) n
590             (ppterm ~metasenv subst term))
591           in 
592           (* DEBUG
593           debug_print (lazy error_msg);
594           debug_print (lazy ("metasenv = \n" ^ (ppmetasenv metasenv subst)));
595           debug_print (lazy ("subst = \n" ^ (ppsubst subst)));
596           debug_print (lazy ("context = \n" ^ (ppcontext subst context))); *)
597           raise (MetaSubstFailure error_msg))) 
598       subst ([], []) 
599   in
600    restrict subst (more_to_be_restricted @ more_to_be_restricted') metasenv
601 ;;
602
603 (*CSC: maybe we should rename delift in abstract, as I did in my dissertation *)(*Andrea: maybe not*)
604
605 let delift n subst context metasenv l t =
606 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
607    otherwise the occur check does not make sense *)
608
609 (*
610  debug_print (lazy ("sto deliftando il termine " ^ (CicPp.ppterm t) ^ " rispetto
611  al contesto locale " ^ (CicPp.ppterm (Cic.Meta(0,l)))));
612 *)
613
614  let module S = CicSubstitution in
615   let l =
616    let (_, canonical_context, _) =
617     try
618      CicUtil.lookup_meta n metasenv
619     with CicUtil.Meta_not_found _ ->
620      raise (MetaSubstFailure (lazy
621       ("delifting error: the metavariable " ^ string_of_int n ^ " is not " ^
622        "declared in the metasenv")))
623     in
624    List.map2 (fun ct lt ->
625      match (ct, lt) with
626      | None, _ -> None
627      | Some _, _ -> lt)
628      canonical_context l
629   in
630   let to_be_restricted = ref [] in
631   let rec deliftaux k =
632    let module C = Cic in
633     function
634      | C.Rel m as t-> 
635          if m <=k then
636           t
637          else
638            (try
639             match List.nth context (m-k-1) with
640                Some (_,C.Def (t,_)) ->
641                 (try
642                   C.Rel ((position (m-k) l) + k)
643                  with
644                   NotInTheList ->
645                 (*CSC: Hmmm. This bit of reduction is not in the spirit of    *)
646                 (*CSC: first order unification. Does it help or does it harm? *)
647                 (*CSC: ANSWER: it hurts performances since it is possible to  *)
648                 (*CSC: have an exponential explosion of the size of the proof.*)
649                 (*CSC: However, without this bit of reduction some "apply" in *)
650                 (*CSC: the library fail (e.g. nat/nth_prime.ma).              *)
651                   deliftaux k (S.lift m t))
652              | Some (_,C.Decl t) ->
653                 C.Rel ((position (m-k) l) + k)
654              | None -> raise (MetaSubstFailure (lazy "RelToHiddenHypothesis"))
655            with
656             Failure _ -> 
657              raise (MetaSubstFailure (lazy "Unbound variable found in deliftaux"))
658           )
659      | C.Var (uri,exp_named_subst) ->
660         let exp_named_subst' =
661          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
662         in
663          C.Var (uri,exp_named_subst')
664      | C.Meta (i, l1) as t -> 
665          (try
666            let (_,t,_) = CicUtil.lookup_subst i subst in
667              deliftaux k (CicSubstitution.subst_meta l1 t)
668          with CicUtil.Subst_not_found _ ->
669            (* see the top level invariant *)
670            if (i = n) then 
671             raise (MetaSubstFailure (lazy (sprintf
672               "Cannot unify the metavariable ?%d with a term that has as subterm %s in which the same metavariable occurs (occur check)"
673               i (ppterm ~metasenv subst t))))
674           else
675             begin
676            (* I do not consider the term associated to ?i in subst since *)
677            (* in this way I can restrict if something goes wrong.        *)
678               let rec deliftl j =
679                 function
680                     [] -> []
681                   | None::tl -> None::(deliftl (j+1) tl)
682                   | (Some t)::tl ->
683                       let l1' = (deliftl (j+1) tl) in
684                         try
685                           Some (deliftaux k t)::l1'
686                         with
687                             NotInTheList
688                           | MetaSubstFailure _ ->
689                               to_be_restricted := 
690                               (i,j)::!to_be_restricted ; None::l1'
691               in
692               let l' = deliftl 1 l1 in
693                 C.Meta(i,l')
694             end)
695      | C.Sort _ as t -> t
696      | C.Implicit _ as t -> t
697      | C.Cast (te,ty) -> C.Cast (deliftaux k te, deliftaux k ty)
698      | C.Prod (n,s,t) -> C.Prod (n, deliftaux k s, deliftaux (k+1) t)
699      | C.Lambda (n,s,t) -> C.Lambda (n, deliftaux k s, deliftaux (k+1) t)
700      | C.LetIn (n,s,ty,t) ->
701         C.LetIn (n, deliftaux k s, deliftaux k ty, deliftaux (k+1) t)
702      | C.Appl l -> C.Appl (List.map (deliftaux k) l)
703      | C.Const (uri,exp_named_subst) ->
704         let exp_named_subst' =
705          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
706         in
707          C.Const (uri,exp_named_subst')
708      | C.MutInd (uri,typeno,exp_named_subst) ->
709         let exp_named_subst' =
710          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
711         in
712          C.MutInd (uri,typeno,exp_named_subst')
713      | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
714         let exp_named_subst' =
715          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
716         in
717          C.MutConstruct (uri,typeno,consno,exp_named_subst')
718      | C.MutCase (sp,i,outty,t,pl) ->
719         C.MutCase (sp, i, deliftaux k outty, deliftaux k t,
720          List.map (deliftaux k) pl)
721      | C.Fix (i, fl) ->
722         let len = List.length fl in
723         let liftedfl =
724          List.map
725           (fun (name, i, ty, bo) ->
726            (name, i, deliftaux k ty, deliftaux (k+len) bo))
727            fl
728         in
729          C.Fix (i, liftedfl)
730      | C.CoFix (i, fl) ->
731         let len = List.length fl in
732         let liftedfl =
733          List.map
734           (fun (name, ty, bo) -> (name, deliftaux k ty, deliftaux (k+len) bo))
735            fl
736         in
737          C.CoFix (i, liftedfl)
738   in
739    let res =
740     try
741      deliftaux 0 t
742     with
743      NotInTheList ->
744       (* This is the case where we fail even first order unification. *)
745       (* The reason is that our delift function is weaker than first  *)
746       (* order (in the sense of alpha-conversion). See comment above  *)
747       (* related to the delift function.                              *)
748 (* debug_print (lazy "First Order UnificationFailure during delift") ;
749 debug_print(lazy (sprintf
750         "Error trying to abstract %s over [%s]: the algorithm only tried to abstract over bound variables"
751         (ppterm subst t)
752         (String.concat "; "
753           (List.map
754             (function Some t -> ppterm subst t | None -> "_") l
755           )))); *)
756       let msg = (lazy (sprintf
757         "Error trying to abstract %s over [%s]: the algorithm only tried to abstract over bound variables"
758         (ppterm ~metasenv subst t)
759         (String.concat "; "
760           (List.map
761             (function Some t -> ppterm ~metasenv subst t | None -> "_")
762             l))))
763       in
764        if
765          List.exists
766           (function
767               Some t -> CicUtil.is_meta_closed (apply_subst subst t)
768             | None -> true) l
769        then
770         raise (Uncertain msg)
771        else
772         raise (MetaSubstFailure msg)
773    in
774    let (metasenv, subst) = restrict subst !to_be_restricted metasenv in
775     res, metasenv, subst
776 ;;
777
778 (* delifts a term t of n levels strating from k, that is changes (Rel m)
779  * to (Rel (m - n)) when m > (k + n). if k <= m < k + n delift fails
780  *)
781 let delift_rels_from subst metasenv k n =
782  let rec liftaux subst metasenv k =
783   let module C = Cic in
784    function
785       C.Rel m as t ->
786        if m < k then
787         t, subst, metasenv
788        else if m < k + n then
789          raise DeliftingARelWouldCaptureAFreeVariable
790        else
791         C.Rel (m - n), subst, metasenv
792     | C.Var (uri,exp_named_subst) ->
793        let exp_named_subst',subst,metasenv = 
794         List.fold_right
795          (fun (uri,t) (l,subst,metasenv) ->
796            let t',subst,metasenv = liftaux subst metasenv k t in
797             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
798        in
799         C.Var (uri,exp_named_subst'),subst,metasenv
800     | C.Meta (i,l) ->
801         (try
802           let (_, t,_) = lookup_subst i subst in
803            liftaux subst metasenv k (CicSubstitution.subst_meta l t)
804          with CicUtil.Subst_not_found _ -> 
805           let l',to_be_restricted,subst,metasenv =
806            let rec aux con l subst metasenv =
807             match l with
808                [] -> [],[],subst,metasenv
809              | he::tl ->
810                 let tl',to_be_restricted,subst,metasenv =
811                  aux (con + 1) tl subst metasenv in
812                 let he',more_to_be_restricted,subst,metasenv =
813                  match he with
814                     None -> None,[],subst,metasenv
815                   | Some t ->
816                      try
817                       let t',subst,metasenv = liftaux subst metasenv k t in
818                        Some t',[],subst,metasenv
819                      with
820                       DeliftingARelWouldCaptureAFreeVariable ->
821                        None,[i,con],subst,metasenv
822                 in
823                  he'::tl',more_to_be_restricted@to_be_restricted,subst,metasenv
824            in
825             aux 1 l subst metasenv in
826           let metasenv,subst = restrict subst to_be_restricted metasenv in
827            C.Meta(i,l'),subst,metasenv)
828     | C.Sort _ as t -> t,subst,metasenv
829     | C.Implicit _ as t -> t,subst,metasenv
830     | C.Cast (te,ty) ->
831        let te',subst,metasenv = liftaux subst metasenv k te in
832        let ty',subst,metasenv = liftaux subst metasenv k ty in
833         C.Cast (te',ty'),subst,metasenv
834     | C.Prod (n,s,t) ->
835        let s',subst,metasenv = liftaux subst metasenv k s in
836        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
837         C.Prod (n,s',t'),subst,metasenv
838     | C.Lambda (n,s,t) ->
839        let s',subst,metasenv = liftaux subst metasenv k s in
840        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
841         C.Lambda (n,s',t'),subst,metasenv
842     | C.LetIn (n,s,ty,t) ->
843        let s',subst,metasenv = liftaux subst metasenv k s in
844        let ty',subst,metasenv = liftaux subst metasenv k ty in
845        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
846         C.LetIn (n,s',ty',t'),subst,metasenv
847     | C.Appl l ->
848        let l',subst,metasenv =
849         List.fold_right
850          (fun t (l,subst,metasenv) ->
851            let t',subst,metasenv = liftaux subst metasenv k t in
852             t'::l,subst,metasenv) l ([],subst,metasenv) in
853        C.Appl l',subst,metasenv
854     | C.Const (uri,exp_named_subst) ->
855        let exp_named_subst',subst,metasenv = 
856         List.fold_right
857          (fun (uri,t) (l,subst,metasenv) ->
858            let t',subst,metasenv = liftaux subst metasenv k t in
859             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
860        in
861         C.Const (uri,exp_named_subst'),subst,metasenv
862     | C.MutInd (uri,tyno,exp_named_subst) ->
863        let exp_named_subst',subst,metasenv = 
864         List.fold_right
865          (fun (uri,t) (l,subst,metasenv) ->
866            let t',subst,metasenv = liftaux subst metasenv k t in
867             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
868        in
869         C.MutInd (uri,tyno,exp_named_subst'),subst,metasenv
870     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
871        let exp_named_subst',subst,metasenv = 
872         List.fold_right
873          (fun (uri,t) (l,subst,metasenv) ->
874            let t',subst,metasenv = liftaux subst metasenv k t in
875             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
876        in
877         C.MutConstruct (uri,tyno,consno,exp_named_subst'),subst,metasenv
878     | C.MutCase (sp,i,outty,t,pl) ->
879        let outty',subst,metasenv = liftaux subst metasenv k outty in
880        let t',subst,metasenv = liftaux subst metasenv k t in
881        let pl',subst,metasenv =
882         List.fold_right
883          (fun t (l,subst,metasenv) ->
884            let t',subst,metasenv = liftaux subst metasenv k t in
885             t'::l,subst,metasenv) pl ([],subst,metasenv)
886        in
887         C.MutCase (sp,i,outty',t',pl'),subst,metasenv
888     | C.Fix (i, fl) ->
889        let len = List.length fl in
890        let liftedfl,subst,metasenv =
891         List.fold_right
892          (fun (name, i, ty, bo) (l,subst,metasenv) ->
893            let ty',subst,metasenv = liftaux subst metasenv k ty in
894            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
895             (name,i,ty',bo')::l,subst,metasenv
896          ) fl ([],subst,metasenv)
897        in
898         C.Fix (i, liftedfl),subst,metasenv
899     | C.CoFix (i, fl) ->
900        let len = List.length fl in
901        let liftedfl,subst,metasenv =
902         List.fold_right
903          (fun (name, ty, bo) (l,subst,metasenv) ->
904            let ty',subst,metasenv = liftaux subst metasenv k ty in
905            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
906             (name,ty',bo')::l,subst,metasenv
907          ) fl ([],subst,metasenv)
908        in
909         C.CoFix (i, liftedfl),subst,metasenv
910  in
911   liftaux subst metasenv k
912
913 let delift_rels subst metasenv n t =
914   delift_rels_from subst metasenv 1 n t
915  
916
917 (**** END OF DELIFT ****)
918
919
920 (** {2 Format-like pretty printers} *)
921
922 let fpp_gen ppf s =
923   Format.pp_print_string ppf s;
924   Format.pp_print_newline ppf ();
925   Format.pp_print_flush ppf ()
926
927 let fppsubst ppf subst = fpp_gen ppf (ppsubst ~metasenv:[] subst)
928 let fppterm ppf term = fpp_gen ppf (CicPp.ppterm term)
929 let fppmetasenv ppf metasenv = fpp_gen ppf (ppmetasenv [] metasenv)
930 *)