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