]> matita.cs.unibo.it Git - helm.git/blob - components/cic_unification/cicMetaSubst.ml
added support for "polymorphic" coercions
[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 rec apply_subst_context subst context =
257 (*
258   incr apply_subst_context_counter;
259   context_length := !context_length + List.length context;
260 *)
261   List.fold_right
262     (fun item context ->
263       match item with
264       | Some (n, Cic.Decl t) ->
265           let t' = apply_subst subst t in
266           Some (n, Cic.Decl t') :: context
267       | Some (n, Cic.Def (t, ty)) ->
268           let ty' =
269             match ty with
270             | None -> None
271             | Some ty -> Some (apply_subst subst ty)
272           in
273           let t' = apply_subst subst t in
274           Some (n, Cic.Def (t', ty')) :: context
275       | None -> None :: context)
276     context []
277
278 let apply_subst_metasenv subst metasenv =
279 (*
280   incr apply_subst_metasenv_counter;
281   metasenv_length := !metasenv_length + List.length metasenv;
282 *)
283   List.map
284     (fun (n, context, ty) ->
285       (n, apply_subst_context subst context, apply_subst subst ty))
286     (List.filter
287       (fun (i, _, _) -> not (List.mem_assoc i subst))
288       metasenv)
289
290 (***** Pretty printing functions ******)
291
292 let ppterm subst term = CicPp.ppterm (apply_subst subst term)
293
294 let ppterm_in_name_context subst term name_context =
295  CicPp.pp (apply_subst subst term) name_context
296
297 let ppterm_in_context subst term context =
298  let name_context =
299   List.map (function None -> None | Some (n,_) -> Some n) context
300  in
301   ppterm_in_name_context subst term name_context
302
303 let ppcontext' ?(sep = "\n") subst context =
304  let separate s = if s = "" then "" else s ^ sep in
305   List.fold_right 
306    (fun context_entry (i,name_context) ->
307      match context_entry with
308         Some (n,Cic.Decl t) ->
309          sprintf "%s%s : %s" (separate i) (CicPp.ppname n)
310           (ppterm_in_name_context subst t name_context), (Some n)::name_context
311       | Some (n,Cic.Def (bo,ty)) ->
312          sprintf "%s%s : %s := %s" (separate i) (CicPp.ppname n)
313           (match ty with
314               None -> "_"
315             | Some ty -> ppterm_in_name_context subst ty name_context)
316           (ppterm_in_name_context subst bo name_context), (Some n)::name_context
317        | None ->
318           sprintf "%s_ :? _" (separate i), None::name_context
319     ) context ("",[])
320
321 let ppsubst_unfolded subst =
322   String.concat "\n"
323     (List.map
324       (fun (idx, (c, t,_)) ->
325         let context,name_context = ppcontext' ~sep:"; " subst c in
326          sprintf "%s |- ?%d:= %s" context idx
327           (ppterm_in_name_context subst t name_context))
328        subst)
329 (* 
330         Printf.sprintf "?%d := %s" idx (CicPp.ppterm term))
331       subst) *)
332 ;;
333
334 let ppsubst subst =
335   String.concat "\n"
336     (List.map
337       (fun (idx, (c, t, _)) ->
338         let context,name_context = ppcontext' ~sep:"; " [] c in
339          sprintf "%s |- ?%d:= %s" context idx
340           (ppterm_in_name_context [] t name_context))
341        subst)
342 ;;
343
344 let ppcontext ?sep subst context = fst (ppcontext' ?sep subst context)
345
346 let ppmetasenv ?(sep = "\n") subst metasenv =
347   String.concat sep
348     (List.map
349       (fun (i, c, t) ->
350         let context,name_context = ppcontext' ~sep:"; " subst c in
351          sprintf "%s |- ?%d: %s" context i
352           (ppterm_in_name_context subst t name_context))
353       (List.filter
354         (fun (i, _, _) -> not (List.mem_assoc i subst))
355         metasenv))
356
357 let tempi_type_of_aux_subst = ref 0.0;;
358 let tempi_subst = ref 0.0;;
359 let tempi_type_of_aux = ref 0.0;;
360
361 (**** DELIFT ****)
362 (* the delift function takes in input a metavariable index, an ordered list of
363  * optional terms [t1,...,tn] and a term t, and substitutes every tk = Some
364  * (rel(nk)) with rel(k).  Typically, the list of optional terms is the explicit
365  * substitution that is applied to a metavariable occurrence and the result of
366  * the delift function is a term the implicit variable can be substituted with
367  * to make the term [t] unifiable with the metavariable occurrence.  In general,
368  * the problem is undecidable if we consider equivalence in place of alpha
369  * convertibility. Our implementation, though, is even weaker than alpha
370  * convertibility, since it replace the term [tk] if and only if [tk] is a Rel
371  * (missing all the other cases). Does this matter in practice?
372  * The metavariable index is the index of the metavariable that must not occur
373  * in the term (for occur check).
374  *)
375
376 exception NotInTheList;;
377
378 let position n =
379   let rec aux k =
380    function 
381        [] -> raise NotInTheList
382      | (Some (Cic.Rel m))::_ when m=n -> k
383      | _::tl -> aux (k+1) tl in
384   aux 1
385 ;;
386
387 exception Occur;;
388
389 let rec force_does_not_occur subst to_be_restricted t =
390  let module C = Cic in
391  let more_to_be_restricted = ref [] in
392  let rec aux k = function
393       C.Rel r when List.mem (r - k) to_be_restricted -> raise Occur
394     | C.Rel _
395     | C.Sort _ as t -> t
396     | C.Implicit _ -> assert false
397     | C.Meta (n, l) ->
398        (* we do not retrieve the term associated to ?n in subst since *)
399        (* in this way we can restrict if something goes wrong         *)
400        let l' =
401          let i = ref 0 in
402          List.map
403            (function t ->
404              incr i ;
405              match t with
406                 None -> None
407               | Some t ->
408                  try
409                    Some (aux k t)
410                  with Occur ->
411                    more_to_be_restricted := (n,!i) :: !more_to_be_restricted;
412                    None)
413            l
414        in
415         C.Meta (n, l')
416     | C.Cast (te,ty) -> C.Cast (aux k te, aux k ty)
417     | C.Prod (name,so,dest) -> C.Prod (name, aux k so, aux (k+1) dest)
418     | C.Lambda (name,so,dest) -> C.Lambda (name, aux k so, aux (k+1) dest)
419     | C.LetIn (name,so,dest) -> C.LetIn (name, aux k so, aux (k+1) dest)
420     | C.Appl l -> C.Appl (List.map (aux k) l)
421     | C.Var (uri,exp_named_subst) ->
422         let exp_named_subst' =
423           List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
424         in
425         C.Var (uri, exp_named_subst')
426     | C.Const (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.Const (uri, exp_named_subst')
431     | C.MutInd (uri,tyno,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.MutInd (uri, tyno, exp_named_subst')
436     | C.MutConstruct (uri,tyno,consno,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.MutConstruct (uri, tyno, consno, exp_named_subst')
441     | C.MutCase (uri,tyno,out,te,pl) ->
442         C.MutCase (uri, tyno, aux k out, aux k te, List.map (aux k) pl)
443     | C.Fix (i,fl) ->
444        let len = List.length fl in
445        let k_plus_len = k + len in
446        let fl' =
447          List.map
448           (fun (name,j,ty,bo) -> (name, j, aux k ty, aux k_plus_len bo)) fl
449        in
450        C.Fix (i, fl')
451     | C.CoFix (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,ty,bo) -> (name, aux k ty, aux k_plus_len bo)) fl
457        in
458        C.CoFix (i, fl')
459  in
460  let res = aux 0 t in
461  (!more_to_be_restricted, res)
462  
463 let rec restrict subst to_be_restricted metasenv =
464   let names_of_context_indexes context indexes =
465     String.concat ", "
466       (List.map
467         (fun i ->
468           try
469            match List.nth context (i-1) with
470            | None -> assert false
471            | Some (n, _) -> CicPp.ppname n
472           with
473            Failure _ -> assert false
474         ) indexes)
475   in
476   let force_does_not_occur_in_context to_be_restricted = function
477     | None -> [], None
478     | Some (name, Cic.Decl t) ->
479         let (more_to_be_restricted, t') =
480           force_does_not_occur subst to_be_restricted t
481         in
482         more_to_be_restricted, Some (name, Cic.Decl t')
483     | Some (name, Cic.Def (bo, ty)) ->
484         let (more_to_be_restricted, bo') =
485           force_does_not_occur subst to_be_restricted bo
486         in
487         let more_to_be_restricted, ty' =
488           match ty with
489           | None ->  more_to_be_restricted, None
490           | Some ty ->
491               let more_to_be_restricted', ty' =
492                 force_does_not_occur subst to_be_restricted ty
493               in
494               more_to_be_restricted @ more_to_be_restricted',
495               Some ty'
496         in
497         more_to_be_restricted, Some (name, Cic.Def (bo', ty'))
498   in
499   let rec erase i to_be_restricted n = function
500     | [] -> [], to_be_restricted, []
501     | hd::tl ->
502         let more_to_be_restricted,restricted,tl' =
503           erase (i+1) to_be_restricted n tl
504         in
505         let restrict_me = List.mem i restricted in
506         if restrict_me then
507           more_to_be_restricted, restricted, None:: tl'
508         else
509           (try
510             let more_to_be_restricted', hd' =
511               let delifted_restricted =
512                let rec aux =
513                 function
514                    [] -> []
515                  | j::tl when j > i -> (j - i)::aux tl
516                  | _::tl -> aux tl
517                in
518                 aux restricted
519               in
520                force_does_not_occur_in_context delifted_restricted hd
521             in
522              more_to_be_restricted @ more_to_be_restricted',
523              restricted, hd' :: tl'
524           with Occur ->
525             more_to_be_restricted, (i :: restricted), None :: tl')
526   in
527   let (more_to_be_restricted, metasenv) =  (* restrict metasenv *)
528     List.fold_right
529       (fun (n, context, t) (more, metasenv) ->
530         let to_be_restricted =
531           List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
532         in
533         let (more_to_be_restricted, restricted, context') =
534          (* just an optimization *)
535          if to_be_restricted = [] then
536           [],[],context
537          else
538           erase 1 to_be_restricted n context
539         in
540         try
541           let more_to_be_restricted', t' =
542             force_does_not_occur subst restricted t
543           in
544           let metasenv' = (n, context', t') :: metasenv in
545           (more @ more_to_be_restricted @ more_to_be_restricted',
546           metasenv')
547         with Occur ->
548           raise (MetaSubstFailure (lazy (sprintf
549             "Cannot restrict the context of the metavariable ?%d over the hypotheses %s since metavariable's type depends on at least one of them"
550             n (names_of_context_indexes context to_be_restricted)))))
551       metasenv ([], [])
552   in
553   let (more_to_be_restricted', subst) = (* restrict subst *)
554     List.fold_right
555       (* TODO: cambiare dopo l'aggiunta del ty *)
556       (fun (n, (context, term,ty)) (more, subst') ->
557         let to_be_restricted =
558           List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
559         in
560         (try
561           let (more_to_be_restricted, restricted, context') =
562            (* just an optimization *)
563             if to_be_restricted = [] then
564               [], [], context
565             else
566               erase 1 to_be_restricted n context
567           in
568           let more_to_be_restricted', term' =
569             force_does_not_occur subst restricted term
570           in
571           let more_to_be_restricted'', ty' =
572             force_does_not_occur subst restricted ty in
573           let subst' = (n, (context', term',ty')) :: subst' in
574           let more = 
575             more @ more_to_be_restricted 
576             @ more_to_be_restricted'@more_to_be_restricted'' in
577           (more, subst')
578         with Occur ->
579           let error_msg = lazy (sprintf
580             "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"
581             n (names_of_context_indexes context to_be_restricted) n
582             (ppterm subst term))
583           in 
584           (* DEBUG
585           debug_print (lazy error_msg);
586           debug_print (lazy ("metasenv = \n" ^ (ppmetasenv metasenv subst)));
587           debug_print (lazy ("subst = \n" ^ (ppsubst subst)));
588           debug_print (lazy ("context = \n" ^ (ppcontext subst context))); *)
589           raise (MetaSubstFailure error_msg))) 
590       subst ([], []) 
591   in
592   match more_to_be_restricted @ more_to_be_restricted' with
593   | [] -> (metasenv, subst)
594   | l -> restrict subst l metasenv
595 ;;
596
597 (*CSC: maybe we should rename delift in abstract, as I did in my dissertation *)(*Andrea: maybe not*)
598
599 let delift n subst context metasenv l t =
600 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
601    otherwise the occur check does not make sense *)
602
603 (*
604  debug_print (lazy ("sto deliftando il termine " ^ (CicPp.ppterm t) ^ " rispetto
605  al contesto locale " ^ (CicPp.ppterm (Cic.Meta(0,l)))));
606 *)
607
608  let module S = CicSubstitution in
609   let l =
610    let (_, canonical_context, _) = CicUtil.lookup_meta n metasenv in
611    List.map2 (fun ct lt ->
612      match (ct, lt) with
613      | None, _ -> None
614      | Some _, _ -> lt)
615      canonical_context l
616   in
617   let to_be_restricted = ref [] in
618   let rec deliftaux k =
619    let module C = Cic in
620     function
621        C.Rel m -> 
622          if m <=k then
623           C.Rel m   (*CSC: che succede se c'e' un Def? Dovrebbe averlo gia' *)
624                     (*CSC: deliftato la regola per il LetIn                 *)
625                     (*CSC: FALSO! La regola per il LetIn non lo fa          *)
626          else
627           (try
628             match List.nth context (m-k-1) with
629                Some (_,C.Def (t,_)) ->
630                 (*CSC: Hmmm. This bit of reduction is not in the spirit of    *)
631                 (*CSC: first order unification. Does it help or does it harm? *)
632                 deliftaux k (S.lift m t)
633              | Some (_,C.Decl t) ->
634                 C.Rel ((position (m-k) l) + k)
635              | None -> raise (MetaSubstFailure (lazy "RelToHiddenHypothesis"))
636            with
637             Failure _ ->
638              raise (MetaSubstFailure (lazy "Unbound variable found in deliftaux"))
639           )
640      | C.Var (uri,exp_named_subst) ->
641         let exp_named_subst' =
642          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
643         in
644          C.Var (uri,exp_named_subst')
645      | C.Meta (i, l1) as t -> 
646          (try
647            let (_,t,_) = CicUtil.lookup_subst i subst in
648              deliftaux k (CicSubstitution.subst_meta l1 t)
649          with CicUtil.Subst_not_found _ ->
650            (* see the top level invariant *)
651            if (i = n) then 
652             raise (MetaSubstFailure (lazy (sprintf
653               "Cannot unify the metavariable ?%d with a term that has as subterm %s in which the same metavariable occurs (occur check)"
654               i (ppterm subst t))))
655           else
656             begin
657            (* I do not consider the term associated to ?i in subst since *)
658            (* in this way I can restrict if something goes wrong.        *)
659               let rec deliftl j =
660                 function
661                     [] -> []
662                   | None::tl -> None::(deliftl (j+1) tl)
663                   | (Some t)::tl ->
664                       let l1' = (deliftl (j+1) tl) in
665                         try
666                           Some (deliftaux k t)::l1'
667                         with
668                             NotInTheList
669                           | MetaSubstFailure _ ->
670                               to_be_restricted := 
671                               (i,j)::!to_be_restricted ; None::l1'
672               in
673               let l' = deliftl 1 l1 in
674                 C.Meta(i,l')
675             end)
676      | C.Sort _ as t -> t
677      | C.Implicit _ as t -> t
678      | C.Cast (te,ty) -> C.Cast (deliftaux k te, deliftaux k ty)
679      | C.Prod (n,s,t) -> C.Prod (n, deliftaux k s, deliftaux (k+1) t)
680      | C.Lambda (n,s,t) -> C.Lambda (n, deliftaux k s, deliftaux (k+1) t)
681      | C.LetIn (n,s,t) -> C.LetIn (n, deliftaux k s, deliftaux (k+1) t)
682      | C.Appl l -> C.Appl (List.map (deliftaux k) l)
683      | C.Const (uri,exp_named_subst) ->
684         let exp_named_subst' =
685          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
686         in
687          C.Const (uri,exp_named_subst')
688      | C.MutInd (uri,typeno,exp_named_subst) ->
689         let exp_named_subst' =
690          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
691         in
692          C.MutInd (uri,typeno,exp_named_subst')
693      | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
694         let exp_named_subst' =
695          List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
696         in
697          C.MutConstruct (uri,typeno,consno,exp_named_subst')
698      | C.MutCase (sp,i,outty,t,pl) ->
699         C.MutCase (sp, i, deliftaux k outty, deliftaux k t,
700          List.map (deliftaux k) pl)
701      | C.Fix (i, fl) ->
702         let len = List.length fl in
703         let liftedfl =
704          List.map
705           (fun (name, i, ty, bo) ->
706            (name, i, deliftaux k ty, deliftaux (k+len) bo))
707            fl
708         in
709          C.Fix (i, liftedfl)
710      | C.CoFix (i, fl) ->
711         let len = List.length fl in
712         let liftedfl =
713          List.map
714           (fun (name, ty, bo) -> (name, deliftaux k ty, deliftaux (k+len) bo))
715            fl
716         in
717          C.CoFix (i, liftedfl)
718   in
719    let res =
720     try
721      deliftaux 0 t
722     with
723      NotInTheList ->
724       (* This is the case where we fail even first order unification. *)
725       (* The reason is that our delift function is weaker than first  *)
726       (* order (in the sense of alpha-conversion). See comment above  *)
727       (* related to the delift function.                              *)
728 (* debug_print (lazy "First Order UnificationFailure during delift") ;
729 debug_print(lazy (sprintf
730         "Error trying to abstract %s over [%s]: the algorithm only tried to abstract over bound variables"
731         (ppterm subst t)
732         (String.concat "; "
733           (List.map
734             (function Some t -> ppterm subst t | None -> "_") l
735           )))); *)
736       raise (Uncertain (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 -> "_")
742             l)))))
743    in
744    let (metasenv, subst) = restrict subst !to_be_restricted metasenv in
745     res, metasenv, subst
746 ;;
747
748 (* delifts a term t of n levels strating from k, that is changes (Rel m)
749  * to (Rel (m - n)) when m > (k + n). if k <= m < k + n delift fails
750  *)
751 let delift_rels_from subst metasenv k n =
752  let rec liftaux subst metasenv k =
753   let module C = Cic in
754    function
755       C.Rel m ->
756        if m < k then
757         C.Rel m, subst, metasenv
758        else if m < k + n then
759          raise DeliftingARelWouldCaptureAFreeVariable
760        else
761         C.Rel (m - n), subst, metasenv
762     | C.Var (uri,exp_named_subst) ->
763        let exp_named_subst',subst,metasenv = 
764         List.fold_right
765          (fun (uri,t) (l,subst,metasenv) ->
766            let t',subst,metasenv = liftaux subst metasenv k t in
767             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
768        in
769         C.Var (uri,exp_named_subst'),subst,metasenv
770     | C.Meta (i,l) ->
771         (try
772           let (_, t,_) = lookup_subst i subst in
773            liftaux subst metasenv k (CicSubstitution.subst_meta l t)
774          with CicUtil.Subst_not_found _ -> 
775           let l',to_be_restricted,subst,metasenv =
776            let rec aux con l subst metasenv =
777             match l with
778                [] -> [],[],subst,metasenv
779              | he::tl ->
780                 let tl',to_be_restricted,subst,metasenv =
781                  aux (con + 1) tl subst metasenv in
782                 let he',more_to_be_restricted,subst,metasenv =
783                  match he with
784                     None -> None,[],subst,metasenv
785                   | Some t ->
786                      try
787                       let t',subst,metasenv = liftaux subst metasenv k t in
788                        Some t',[],subst,metasenv
789                      with
790                       DeliftingARelWouldCaptureAFreeVariable ->
791                        None,[i,con],subst,metasenv
792                 in
793                  he'::tl',more_to_be_restricted@to_be_restricted,subst,metasenv
794            in
795             aux 1 l subst metasenv in
796           let metasenv,subst = restrict subst to_be_restricted metasenv in
797            C.Meta(i,l'),subst,metasenv)
798     | C.Sort _ as t -> t,subst,metasenv
799     | C.Implicit _ as t -> t,subst,metasenv
800     | C.Cast (te,ty) ->
801        let te',subst,metasenv = liftaux subst metasenv k te in
802        let ty',subst,metasenv = liftaux subst metasenv k ty in
803         C.Cast (te',ty'),subst,metasenv
804     | C.Prod (n,s,t) ->
805        let s',subst,metasenv = liftaux subst metasenv k s in
806        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
807         C.Prod (n,s',t'),subst,metasenv
808     | C.Lambda (n,s,t) ->
809        let s',subst,metasenv = liftaux subst metasenv k s in
810        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
811         C.Lambda (n,s',t'),subst,metasenv
812     | C.LetIn (n,s,t) ->
813        let s',subst,metasenv = liftaux subst metasenv k s in
814        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
815         C.LetIn (n,s',t'),subst,metasenv
816     | C.Appl l ->
817        let l',subst,metasenv =
818         List.fold_right
819          (fun t (l,subst,metasenv) ->
820            let t',subst,metasenv = liftaux subst metasenv k t in
821             t'::l,subst,metasenv) l ([],subst,metasenv) in
822        C.Appl l',subst,metasenv
823     | C.Const (uri,exp_named_subst) ->
824        let exp_named_subst',subst,metasenv = 
825         List.fold_right
826          (fun (uri,t) (l,subst,metasenv) ->
827            let t',subst,metasenv = liftaux subst metasenv k t in
828             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
829        in
830         C.Const (uri,exp_named_subst'),subst,metasenv
831     | C.MutInd (uri,tyno,exp_named_subst) ->
832        let exp_named_subst',subst,metasenv = 
833         List.fold_right
834          (fun (uri,t) (l,subst,metasenv) ->
835            let t',subst,metasenv = liftaux subst metasenv k t in
836             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
837        in
838         C.MutInd (uri,tyno,exp_named_subst'),subst,metasenv
839     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
840        let exp_named_subst',subst,metasenv = 
841         List.fold_right
842          (fun (uri,t) (l,subst,metasenv) ->
843            let t',subst,metasenv = liftaux subst metasenv k t in
844             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
845        in
846         C.MutConstruct (uri,tyno,consno,exp_named_subst'),subst,metasenv
847     | C.MutCase (sp,i,outty,t,pl) ->
848        let outty',subst,metasenv = liftaux subst metasenv k outty in
849        let t',subst,metasenv = liftaux subst metasenv k t in
850        let pl',subst,metasenv =
851         List.fold_right
852          (fun t (l,subst,metasenv) ->
853            let t',subst,metasenv = liftaux subst metasenv k t in
854             t'::l,subst,metasenv) pl ([],subst,metasenv)
855        in
856         C.MutCase (sp,i,outty',t',pl'),subst,metasenv
857     | C.Fix (i, fl) ->
858        let len = List.length fl in
859        let liftedfl,subst,metasenv =
860         List.fold_right
861          (fun (name, i, ty, bo) (l,subst,metasenv) ->
862            let ty',subst,metasenv = liftaux subst metasenv k ty in
863            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
864             (name,i,ty',bo')::l,subst,metasenv
865          ) fl ([],subst,metasenv)
866        in
867         C.Fix (i, liftedfl),subst,metasenv
868     | C.CoFix (i, fl) ->
869        let len = List.length fl in
870        let liftedfl,subst,metasenv =
871         List.fold_right
872          (fun (name, ty, bo) (l,subst,metasenv) ->
873            let ty',subst,metasenv = liftaux subst metasenv k ty in
874            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
875             (name,ty',bo')::l,subst,metasenv
876          ) fl ([],subst,metasenv)
877        in
878         C.CoFix (i, liftedfl),subst,metasenv
879  in
880   liftaux subst metasenv k
881
882 let delift_rels subst metasenv n t =
883   delift_rels_from subst metasenv 1 n t
884  
885
886 (**** END OF DELIFT ****)
887
888
889 (** {2 Format-like pretty printers} *)
890
891 let fpp_gen ppf s =
892   Format.pp_print_string ppf s;
893   Format.pp_print_newline ppf ();
894   Format.pp_print_flush ppf ()
895
896 let fppsubst ppf subst = fpp_gen ppf (ppsubst subst)
897 let fppterm ppf term = fpp_gen ppf (CicPp.ppterm term)
898 let fppmetasenv ppf metasenv = fpp_gen ppf (ppmetasenv [] metasenv)
899