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