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