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