]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicMetaSubst.ml
f63aa9a30759d4a36acae98f99f892738e444dfd
[helm.git] / helm / software / components / ng_refiner / nCicMetaSubst.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 let debug = ref false;;
15 let indent = ref "";;
16 let times = ref [];;
17 let pp s =
18  if !debug then
19   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
20 ;;
21 let inside c =
22  if !debug then
23   begin
24    let time1 = Unix.gettimeofday () in
25    indent := !indent ^ String.make 1 c;
26    times := time1 :: !times;
27    prerr_endline ("{{{" ^ !indent ^ " ")
28   end
29 ;;
30 let outside exc_opt =
31  if !debug then
32   begin
33    let time2 = Unix.gettimeofday () in
34    let time1 =
35     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
36    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
37    (match exc_opt with
38    | Some e ->  prerr_endline ("exception raised: " ^ Printexc.to_string e)
39    | None -> ());
40    try
41     indent := String.sub !indent 0 (String.length !indent -1)
42    with
43     Invalid_argument _ -> indent := "??"; ()
44   end
45 ;;
46
47 exception MetaSubstFailure of string Lazy.t
48 exception Uncertain of string Lazy.t
49
50 let newmeta,maxmeta = 
51   let maxmeta = ref 0 in
52   (fun () -> incr maxmeta; !maxmeta),
53   (fun () -> !maxmeta)
54 ;;
55
56 exception NotInTheList;;
57
58 let position to_skip n (shift, lc) =
59   match lc with
60   | NCic.Irl _ when to_skip > 0 -> assert false  (* unclear to me *)
61   | NCic.Irl len when n <= shift || n > shift + len -> raise NotInTheList
62   | NCic.Irl _ -> n - shift
63   | NCic.Ctx tl ->
64       let rec aux to_skip k = function 
65          | [] -> raise NotInTheList
66          | _ :: tl when to_skip > 0 -> aux (to_skip - 1) (k+1) tl
67          | (NCic.Rel m)::_ when m + shift = n -> k
68          | _::tl -> aux to_skip (k+1) tl 
69       in
70        aux to_skip 1 tl
71 ;;
72
73 let pack_lc orig = 
74   let rec are_contiguous k = function
75     | [] -> true
76     | (NCic.Rel j) :: tl when j = k+1 -> are_contiguous j tl
77     | _ -> false
78   in
79   match orig with
80   | _, NCic.Ctx [] -> 0, NCic.Irl 0
81   | shift, NCic.Ctx (NCic.Rel k::tl as l) when are_contiguous k tl ->
82       shift+k-1, NCic.Irl (List.length l)
83   | _ -> orig
84 ;;
85
86
87
88 let mk_perforated_irl shift len restrictions =
89   let rec aux n =
90     if n = 0 then [] else
91      if List.mem (n+shift) restrictions then aux (n-1)
92      else (NCic.Rel n) :: aux (n-1)
93   in
94     pack_lc (shift, NCic.Ctx (List.rev (aux len)))
95 ;;
96
97 exception Occur;;
98
99 let rec force_does_not_occur metasenv subst restrictions t =
100  let rec aux k ms = function
101     | NCic.Rel r when List.mem (r - k) restrictions -> raise Occur
102     | NCic.Rel r as orig ->
103         let amount = 
104           List.length (List.filter (fun x -> x < r - k) restrictions) 
105         in
106         if amount > 0 then ms, NCic.Rel (r - amount) else ms, orig
107     | NCic.Meta (n, (shift,lc as l)) as orig ->
108        (try
109          let _,_,bo,_ = NCicUtils.lookup_subst n subst in
110           aux k ms (NCicSubstitution.subst_meta l bo)
111         with
112          NCicUtils.Subst_not_found _ ->
113           (* we ignore the subst since restrict will take care of already
114            * instantiated/restricted metavariabels *)
115           let (metasenv,subst as ms), restrictions_for_n, l' =
116             let l = NCicUtils.expand_local_context lc in
117          
118             let ms, _, restrictions_for_n, l =
119              List.fold_right
120                (fun t (ms, i, restrictions_for_n, l) ->
121                  try 
122                    let ms, t = aux (k-shift) ms t in
123                    ms, i-1, restrictions_for_n, t::l
124                  with Occur ->
125                    ms, i-1, i::restrictions_for_n, l)
126                l (ms, List.length l, [], [])
127             in
128                 
129              ms, restrictions_for_n, pack_lc (shift, NCic.Ctx l)
130           in
131           if restrictions_for_n = [] then
132             ms, if l = l' then orig else NCic.Meta (n, l')
133           else
134             let metasenv, subst, newmeta = 
135               restrict metasenv subst n restrictions_for_n 
136             in
137               (metasenv, subst), NCic.Meta (newmeta, l'))
138     | t -> NCicUntrusted.map_term_fold_a (fun _ k -> k+1) k aux ms t
139  in
140    aux 0 (metasenv,subst) t 
141
142 and force_does_not_occur_in_context metasenv subst restrictions = function
143   | name, NCic.Decl t as orig ->
144       let (metasenv, subst), t' =
145         force_does_not_occur metasenv subst restrictions t in
146       metasenv, subst, (if t == t' then orig else (name,NCic.Decl t'))
147   | name, NCic.Def (bo, ty) as orig ->
148       let (metasenv, subst), bo' =
149         force_does_not_occur metasenv subst restrictions bo in
150       let (metasenv, subst), ty' =
151         force_does_not_occur metasenv subst restrictions ty in
152       metasenv, subst, 
153        (if bo == bo' && ty == ty' then orig else (name, NCic.Def (bo', ty')))
154
155 and erase_in_context metasenv subst pos restrictions = function
156   | [] -> metasenv, subst, restrictions, []
157   | hd::tl as orig ->
158       let metasenv, subst, restricted, tl' = 
159         erase_in_context metasenv subst (pos+1) restrictions tl in
160       if List.mem pos restricted then
161         metasenv, subst, restricted, tl'
162       else
163         try
164           let metasenv, subst, hd' =
165             let delifted_restricted = 
166               List.map ((+) ~-pos) (List.filter ((<=) pos) restricted) in
167             force_does_not_occur_in_context 
168               metasenv subst delifted_restricted hd
169           in
170            metasenv, subst, restricted, 
171             (if hd' == hd && tl' == tl then orig else (hd' :: tl'))
172         with Occur ->
173             metasenv, subst, (pos :: restricted), tl'
174
175 and restrict metasenv subst i restrictions =
176   assert (restrictions <> []);
177   try 
178     let name, ctx, bo, ty = NCicUtils.lookup_subst i subst in
179       try 
180         let metasenv, subst, restrictions, newctx = 
181           erase_in_context metasenv subst 1 restrictions ctx in
182         let (metasenv, subst), newty =  
183           force_does_not_occur metasenv subst restrictions ty in
184         let (metasenv, subst), newbo =  
185           force_does_not_occur metasenv subst restrictions bo in
186         let j = newmeta () in
187         let subst_entry_j = j, (name, newctx, newbo, newty) in
188         let reloc_irl = mk_perforated_irl 0 (List.length ctx) restrictions in
189         let subst_entry_i = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
190         let new_subst = 
191           subst_entry_j :: List.map 
192             (fun (n,_) as orig -> if i = n then subst_entry_i else orig) subst
193         in
194 (*
195     prerr_endline ("restringo nella subst: " ^string_of_int i ^ " -> " ^ 
196       string_of_int j ^ "\n" ^ 
197       NCicPp.ppsubst ~metasenv [subst_entry_j] ^ "\n\n" ^
198       NCicPp.ppsubst ~metasenv [subst_entry_i] ^ "\n" ^
199       NCicPp.ppterm ~metasenv ~subst ~context:ctx bo ^ " ---- " ^
200       NCicPp.ppterm ~metasenv ~subst ~context:newctx newbo
201             );
202 *)
203         metasenv, new_subst, j
204       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
205             ("Cannot restrict the context of the metavariable ?%d over "^^
206             "the hypotheses %s since ?%d is already instantiated "^^
207             "with %s and at least one of the hypotheses occurs in "^^
208             "the substituted term") i  (String.concat ", " 
209             (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)) i
210             (NCicPp.ppterm ~metasenv ~subst ~context:ctx bo))))
211   with NCicUtils.Subst_not_found _ -> 
212     try 
213       let name, ctx, ty = NCicUtils.lookup_meta i metasenv in
214       try
215         let metasenv, subst, restrictions, newctx = 
216           erase_in_context metasenv subst 1 restrictions ctx in
217         let (metasenv, subst), newty =  
218           force_does_not_occur metasenv subst restrictions ty in
219         let j = newmeta () in
220         let metasenv_entry = j, (name, newctx, newty) in
221         let reloc_irl = 
222           mk_perforated_irl 0 (List.length ctx) restrictions in
223         let subst_entry = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
224         List.map 
225           (fun (n,_) as orig -> if i = n then metasenv_entry else orig) 
226           metasenv,
227         subst_entry :: subst, j
228       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
229           ("Cannot restrict the context of the metavariable ?%d "^^
230           "over the hypotheses %s since metavariable's type depends "^^
231           "on at least one of them") i (String.concat ", " 
232           (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)))))
233     with 
234     | NCicUtils.Meta_not_found _ -> assert false
235 ;;
236
237 let rec flexible_arg context subst = function 
238   | NCic.Meta (i,_) ->
239       (try 
240         let _,_,t,_ = List.assoc i subst in
241         flexible_arg context subst t
242       with Not_found -> true)
243   | NCic.Appl (NCic.Meta (i,_) :: args)-> 
244       (try 
245         let _,_,t,_ = List.assoc i subst in
246         flexible_arg context subst 
247           (NCicReduction.head_beta_reduce ~delta:max_int 
248             (NCic.Appl (t :: args)))
249       with Not_found -> true)
250    (* this is a cheap whd, it only performs zeta-reduction.
251     * 
252     * it works when the **omissis** disambiguation algorithm
253     * is run on `let x := K a b in t`, K is substituted for a 
254     * ? and thus in t metavariables have a flexible Rel
255     *)
256   | NCic.Rel i ->
257       (try
258          match List.nth context (i-1)
259          with 
260          | _,NCic.Def (bo,_) ->
261                flexible_arg context subst
262                  (NCicSubstitution.lift i bo)
263          | _ -> false
264       with 
265       | Failure _ -> 
266           prerr_endline (Printf.sprintf "Rel %d inside context:\n%s" i  
267             (NCicPp.ppcontext ~subst ~metasenv:[] context));
268           assert false
269       | Invalid_argument _ -> assert false)
270   | _ -> false
271 ;;
272
273 let is_out_scope = function `OutScope _ -> true | _ -> false;;
274 let is_out_scope_tag = List.exists is_out_scope;;
275 let int_of_out_scope_tag tag = 
276  match List.filter is_out_scope tag with [`OutScope n] -> n | _ -> assert false
277 ;;
278
279
280 exception Found;;
281
282 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
283    otherwise the occur check does not make sense in case of unification
284    of ?n with ?n *)
285 let delift ~unify metasenv subst context n l t =
286   (*D*)  inside 'D'; try let rc =  
287   let is_in_scope_meta subst = function
288     | NCic.Meta (i,_) ->
289         (try 
290            let tag, _, _, _ = NCicUtils.lookup_subst i subst in 
291             List.mem `InScope tag
292         with NCicUtils.Subst_not_found _ -> false)
293     | _ -> false
294   in
295   let contains_in_scope subst t = 
296     let rec aux _ () = function
297       | NCic.Meta _ as t ->
298           if is_in_scope_meta subst t then raise Found
299           else ()
300       | t -> 
301           if is_in_scope_meta subst t then raise Found
302           else NCicUtils.fold (fun _ () -> ()) () aux () t
303     in
304     try aux () () t; false with Found -> true
305   in
306   let unify_list in_scope = 
307     match l with
308     | _, NCic.Irl _ -> fun _ _ _ _ _ -> None
309     | shift, NCic.Ctx l -> fun metasenv subst context k t ->
310        if flexible_arg context subst t || contains_in_scope subst t then None else
311          let lb = 
312            List.map (fun t -> 
313             let t = NCicSubstitution.lift (k+shift) t in
314             t, flexible_arg context subst t) 
315            l 
316          in
317          HExtlib.list_findopt
318           (fun (li,flexible) i ->
319             if flexible || i < in_scope then None else
320              match unify metasenv subst context li t with
321              | Some (metasenv,subst) -> 
322                  Some ((metasenv, subst), NCic.Rel (i+1+k))
323              | None -> None)
324           lb
325   in
326   let rec aux (context,k,in_scope) (metasenv, subst as ms) t = 
327    match unify_list in_scope metasenv subst context k t with
328    | Some x -> x
329    | None -> 
330     match t with 
331     | NCic.Rel n as t when n <= k -> ms, t
332     | NCic.Rel n -> 
333         (try
334           match List.nth context (n-1) with
335           | _,NCic.Def (bo,_) -> 
336                 (try ms, NCic.Rel ((position in_scope (n-k) l) + k)
337                  with NotInTheList ->
338                 (* CSC: This bit of reduction hurts performances since it is
339                  * possible to  have an exponential explosion of the size of the
340                  * proof. required for nat/nth_prime.ma *)
341                   aux (context,k,in_scope) ms (NCicSubstitution.lift n bo))
342           | _,NCic.Decl _ -> ms, NCic.Rel ((position in_scope (n-k) l) + k)
343         with Failure _ -> assert false) (*Unbound variable found in delift*)
344     | NCic.Meta (i,_) when i=n ->
345          raise (MetaSubstFailure (lazy (Printf.sprintf (
346            "Cannot unify the metavariable ?%d with a term that has "^^
347            "as subterm %s in which the same metavariable "^^
348            "occurs (occur check)") i 
349             (NCicPp.ppterm ~context ~metasenv ~subst t))))
350     | NCic.Meta (i,l1) as orig ->
351         (try
352            let tag,c,t,ty = NCicUtils.lookup_subst i subst in
353            let in_scope, clear = 
354             if List.mem `InScope tag then 0, true
355             else if is_out_scope_tag tag then int_of_out_scope_tag tag,true
356             else in_scope, false
357            in
358            let ms = 
359              if not clear then ms
360              else 
361                metasenv, 
362                (i,([],c,t,ty)) :: List.filter (fun j,_ -> i <> j) subst
363            in
364            aux (context,k,in_scope) ms (NCicSubstitution.subst_meta l1 t)
365          with NCicUtils.Subst_not_found _ ->
366            if snd l1 = NCic.Irl 0 || snd l1 = NCic.Ctx [] then ms, orig
367            else
368               let shift1,lc1 = l1 in
369               let shift,lc = l in
370               let shift = shift + k in
371               match lc, lc1 with
372               | NCic.Irl len, NCic.Irl len1 
373                 when shift1 + len1 < shift || shift1 > shift + len ->
374                   let restrictions = HExtlib.list_seq 1 (len1 + 1) in
375                   let metasenv, subst, newmeta = 
376                      restrict metasenv subst i restrictions 
377                   in
378                   (metasenv, subst), 
379                     NCic.Meta (newmeta, (0,NCic.Irl (max 0 (k-shift1))))
380               | NCic.Irl len, NCic.Irl len1 ->
381                   let low_restrictions, new_shift = 
382                     if k <= shift1 && shift1 < shift then 
383                       HExtlib.list_seq 1 (shift - shift1 + 1), k
384                     else if shift1 < k (* <= shift *) then
385                       let save_below = k - shift1 in
386                       HExtlib.list_seq (save_below + 1) (shift - shift1 + 1),
387                       shift1
388                     else [], shift1 - shift + k
389                   in
390                   let high_restrictions = 
391                     let last = shift + len in
392                     let last1 = shift1 + len1 in
393                     if last1 > last then
394                       let high_gap = last1 - last in
395                       HExtlib.list_seq (len1 - high_gap + 1) (len1 + 1)
396                     else []
397                   in
398                   let restrictions = low_restrictions @ high_restrictions in
399                   if restrictions = [] then
400                     if shift = k then ms, orig
401                     else ms, NCic.Meta (i, (new_shift, lc1))
402                   else
403                     let metasenv, subst, newmeta = 
404                        restrict metasenv subst i restrictions
405                     in
406 (* {{{
407                   prerr_endline ("RESTRICTIONS FOR: " ^ 
408                     NCicPp.ppterm ~metasenv ~subst ~context:[] 
409                     (NCic.Meta (i,l1))^" that was part of a term unified with "
410                     ^ NCicPp.ppterm ~metasenv ~subst ~context:[] (NCic.Meta
411                     (n,l)) ^ " ====> " ^ String.concat "," (List.map
412                     string_of_int restrictions) ^ "\nMENV:\n" ^
413                     NCicPp.ppmetasenv ~subst metasenv ^ "\nSUBST:\n" ^
414                     NCicPp.ppsubst subst ~metasenv);
415 }}} *)
416                     let newlc_len = len1 - List.length restrictions in 
417                     let meta = 
418                        NCic.Meta(newmeta,(new_shift, NCic.Irl newlc_len))
419                     in
420                     assert (
421                       let _, cctx, _ = NCicUtils.lookup_meta newmeta metasenv in
422                       List.length cctx = newlc_len);
423                     (metasenv, subst), meta
424
425               | _ ->
426                   let lc1 = NCicUtils.expand_local_context lc1 in
427                   let lc1 = List.map (NCicSubstitution.lift shift1) lc1 in
428                   let rec deliftl tbr j ms = function
429                     | [] -> ms, tbr, []
430                     | t::tl ->
431                         let ms, tbr, tl = deliftl tbr (j+1) ms tl in
432                         try 
433                           let ms, t = aux (context,k,in_scope) ms t in 
434                           ms, tbr, t::tl
435                         with
436                         | NotInTheList | MetaSubstFailure _ -> ms, j::tbr, tl
437                   in
438                   let (metasenv, subst), to_be_r, lc1' = deliftl [] 1 ms lc1 in
439                   pp (lazy ("TO BE RESTRICTED: " ^ 
440                    (String.concat "," (List.map string_of_int to_be_r))));
441                   let l1 = pack_lc (0, NCic.Ctx lc1') in
442                   pp (lazy ("newmeta:" ^ NCicPp.ppterm
443                    ~metasenv ~subst ~context (NCic.Meta (999,l1))));
444                   pp (lazy (NCicPp.ppmetasenv ~subst metasenv));
445                   if to_be_r = [] then
446                     (metasenv, subst), 
447                     (if lc1' = lc1 then orig else NCic.Meta (i,l1))
448                   else
449                     let metasenv, subst, newmeta = 
450                       restrict metasenv subst i to_be_r in
451                     (metasenv, subst), NCic.Meta(newmeta,l1))
452
453     | t -> 
454         NCicUntrusted.map_term_fold_a 
455           (fun e (c,k,s) -> (e::c,k+1,s)) (context,k,in_scope) aux ms t
456   in
457 (*
458   prerr_endline (
459     "DELIFTO " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^ " w.r.t. " ^
460     String.concat ", " (List.map (NCicPp.ppterm ~metasenv ~subst ~context) ( 
461       let shift, lc = l in
462       (List.map (NCicSubstitution.lift shift) 
463         (NCicUtils.expand_local_context lc))
464   )));
465 *)
466    try aux (context,0,0) (metasenv,subst) t
467    with NotInTheList ->
468       (* This is the case where we fail even first order unification. *)
469       (* The reason is that our delift function is weaker than first  *)
470       (* order (in the sense of alpha-conversion). See comment above  *)
471       (* related to the delift function.                              *)
472       let msg = (lazy (Printf.sprintf
473         ("Error trying to abstract %s over [%s]: the algorithm only tried to "^^
474         "abstract over bound variables") (NCicPp.ppterm ~metasenv ~subst
475         ~context t) (String.concat "; " (List.map (NCicPp.ppterm ~metasenv
476         ~subst ~context) (let shift, lc = l in List.map (NCicSubstitution.lift
477         shift) (NCicUtils.expand_local_context lc))))))
478       in
479       let shift, lc = l in
480       let lc = NCicUtils.expand_local_context lc in
481       let l = List.map (NCicSubstitution.lift shift) lc in
482        if
483         List.exists (fun t-> NCicUntrusted.metas_of_term subst context t <> [])l
484        then
485         raise (Uncertain msg)
486        else
487         raise (MetaSubstFailure msg)
488  (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
489 ;;
490
491 let mk_meta ?(attrs=[]) metasenv context ?with_type kind = 
492   assert(kind <> `IsSort || context = []);
493   let n = newmeta () in
494   let ty= match with_type with None-> NCic.Implicit (`Typeof n)| Some x ->x in
495   let len = List.length context in
496   let attrs = NCicUntrusted.set_kind kind attrs in
497   let menv_entry = (n, (attrs, context, ty)) in
498   menv_entry :: metasenv, n, NCic.Meta (n, (0,NCic.Irl len)), ty
499 ;;
500
501 let extend_meta metasenv n =
502  try
503   let attrs,cc,ty = NCicUtils.lookup_meta n metasenv in 
504   (match ty with 
505   | NCic.Implicit (`Typeof _) -> 
506       let mk_meta context kind =
507         let metasenv, _, ty, _ = mk_meta metasenv context kind in
508         (n, (attrs, cc, ty)) :: List.filter (fun x,_ -> x <> n) metasenv, ty
509       in
510       (match NCicUntrusted.kind_of_meta attrs with
511        | `IsSort 
512        | `IsType -> mk_meta [] `IsSort
513        | `IsTerm -> mk_meta cc `IsType)
514   | ty -> metasenv, ty)
515  with NCicUtils.Meta_not_found _ -> assert false
516 ;;
517
518 let saturate ?(delta=0) metasenv subst context ty goal_arity =
519  assert (goal_arity >= 0);
520   let rec aux metasenv = function
521    | NCic.Prod (name,s,t) as ty ->
522        let metasenv1, _, arg,_ = 
523           mk_meta ~attrs:[`Name name] metasenv context ~with_type:s `IsTerm in
524        let t, metasenv1, args, pno = 
525            aux metasenv1 (NCicSubstitution.subst arg t) 
526        in
527        if pno + 1 = goal_arity then
528          ty, metasenv, [], goal_arity+1
529        else
530          t, metasenv1, arg::args, pno+1
531    | ty ->
532         match NCicReduction.whd ~subst context ty ~delta with
533         | NCic.Prod _ as ty -> aux metasenv ty
534         | ty -> ty, metasenv, [], 0
535   in
536   let res, newmetasenv, arguments, _ = aux metasenv ty in
537   res, newmetasenv, arguments
538 ;;