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