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