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