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