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