]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicMetaSubst.ml
ce0021d3d660d322b5cc1cf2466a2a5e93ffe066
[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 purge_restricted restrictions more_restrictions l =
100  if more_restrictions = [] then l
101  else
102   begin
103    pp (lazy ("TO BE RESTRICTED: " ^ 
104     (String.concat "," (List.map string_of_int restrictions))));
105    pp (lazy ("MORE RESTRICTIONS: " ^ 
106     (String.concat "," (List.map string_of_int more_restrictions))));
107    let shift,lc = l in
108    let lc = NCicUtils.expand_local_context lc in
109     let rec aux n lc =
110      match lc with
111         [] -> []
112       | _ when List.mem n restrictions -> aux (n+1) lc
113       | _::tl when List.mem n more_restrictions -> aux (n+1) tl
114       | he::tl -> he::aux (n+1) tl
115     in
116     pack_lc (shift, NCic.Ctx (aux 1 lc))
117   end
118 ;;
119
120 let rec force_does_not_occur metasenv subst restrictions t =
121  let rec aux k ms = function
122     | NCic.Rel r when List.mem (r - k) restrictions -> raise Occur
123     | NCic.Rel r as orig ->
124         let amount = 
125           List.length (List.filter (fun x -> x < r - k) restrictions) 
126         in
127         if amount > 0 then ms, NCic.Rel (r - amount) else ms, orig
128     | NCic.Meta (n, (shift,lc as l)) as orig ->
129        (try
130          let _,_,bo,_ = NCicUtils.lookup_subst n subst in
131           aux k ms (NCicSubstitution.subst_meta l bo)
132         with
133          NCicUtils.Subst_not_found _ ->
134           (* we ignore the subst since restrict will take care of already
135            * instantiated/restricted metavariabels *)
136           let (metasenv,subst as ms), restrictions_for_n, l' =
137             let l = NCicUtils.expand_local_context lc in
138          
139             let ms, _, restrictions_for_n, l =
140              List.fold_right
141                (fun t (ms, i, restrictions_for_n, l) ->
142                  try 
143                    let ms, t = aux (k-shift) ms t in
144                    ms, i-1, restrictions_for_n, t::l
145                  with Occur ->
146                    ms, i-1, i::restrictions_for_n, l)
147                l (ms, List.length l, [], [])
148             in
149                 
150              ms, restrictions_for_n, pack_lc (shift, NCic.Ctx l)
151           in
152           if restrictions_for_n = [] then
153             ms, if l = l' then orig else NCic.Meta (n, l')
154           else
155             let metasenv, subst, newmeta, more_restricted = 
156               restrict metasenv subst n restrictions_for_n in
157             let l' = purge_restricted restrictions more_restricted l' in
158               (metasenv, subst), NCic.Meta (newmeta, l'))
159     | t -> NCicUntrusted.map_term_fold_a (fun _ k -> k+1) k aux ms t
160  in
161    aux 0 (metasenv,subst) t 
162
163 and force_does_not_occur_in_context metasenv subst restrictions = function
164   | name, NCic.Decl t as orig ->
165       let (metasenv, subst), t' =
166         force_does_not_occur metasenv subst restrictions t in
167       metasenv, subst, (if t == t' then orig else (name,NCic.Decl t'))
168   | name, NCic.Def (bo, ty) as orig ->
169       let (metasenv, subst), bo' =
170         force_does_not_occur metasenv subst restrictions bo in
171       let (metasenv, subst), ty' =
172         force_does_not_occur metasenv subst restrictions ty in
173       metasenv, subst, 
174        (if bo == bo' && ty == ty' then orig else (name, NCic.Def (bo', ty')))
175
176 and erase_in_context metasenv subst pos restrictions = function
177   | [] -> metasenv, subst, restrictions, []
178   | hd::tl as orig ->
179       let metasenv, subst, restricted, tl' = 
180         erase_in_context metasenv subst (pos+1) restrictions tl in
181       if List.mem pos restricted then
182         metasenv, subst, restricted, tl'
183       else
184         try
185           let metasenv, subst, hd' =
186             let delifted_restricted = 
187               List.map ((+) ~-pos) (List.filter ((<=) pos) restricted) in
188             force_does_not_occur_in_context 
189               metasenv subst delifted_restricted hd
190           in
191            metasenv, subst, restricted, 
192             (if hd' == hd && tl' == tl then orig else (hd' :: tl'))
193         with Occur ->
194             metasenv, subst, (pos :: restricted), tl'
195
196 and restrict metasenv subst i (restrictions as orig) =
197   assert (restrictions <> []);
198   try 
199     let name, ctx, bo, ty = NCicUtils.lookup_subst i subst in
200       try 
201         let metasenv, subst, restrictions, newctx = 
202           erase_in_context metasenv subst 1 restrictions ctx in
203         let (metasenv, subst), newty =  
204           force_does_not_occur metasenv subst restrictions ty in
205         let (metasenv, subst), newbo =  
206           force_does_not_occur metasenv subst restrictions bo in
207         let j = newmeta () in
208         let subst_entry_j = j, (name, newctx, newbo, newty) in
209         let reloc_irl = mk_perforated_irl 0 (List.length ctx) restrictions in
210         let subst_entry_i = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
211         let new_subst = 
212           subst_entry_j :: List.map 
213             (fun (n,_) as orig -> if i = n then subst_entry_i else orig) subst
214         in
215         let diff = List.filter (fun x -> not (List.mem x orig)) restrictions in
216         metasenv, new_subst, j, diff
217       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
218             ("Cannot restrict the context of the metavariable ?%d over "^^
219             "the hypotheses %s since ?%d is already instantiated "^^
220             "with %s and at least one of the hypotheses occurs in "^^
221             "the substituted term") i  (String.concat ", " 
222             (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)) i
223             (NCicPp.ppterm ~metasenv ~subst ~context:ctx bo))))
224   with NCicUtils.Subst_not_found _ -> 
225     try 
226       let name, ctx, ty = NCicUtils.lookup_meta i metasenv in
227       try
228         let metasenv, subst, restrictions, newctx = 
229           erase_in_context metasenv subst 1 restrictions ctx in
230         let (metasenv, subst), newty =  
231           force_does_not_occur metasenv subst restrictions ty in
232         let j = newmeta () in
233         let metasenv_entry = j, (name, newctx, newty) in
234         let reloc_irl = 
235           mk_perforated_irl 0 (List.length ctx) restrictions in
236         let subst_entry = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
237         let diff = List.filter (fun x -> not (List.mem x orig)) restrictions in
238         List.map 
239           (fun (n,_) as orig -> if i = n then metasenv_entry else orig) 
240           metasenv,
241         subst_entry :: subst, j, diff
242       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
243           ("Cannot restrict the context of the metavariable ?%d "^^
244           "over the hypotheses %s since metavariable's type depends "^^
245           "on at least one of them") i (String.concat ", " 
246           (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)))))
247     with 
248     | NCicUtils.Meta_not_found _ -> assert false
249 ;;
250
251 let rec flexible_arg context subst = function 
252   | NCic.Meta (i,_) ->
253       (try 
254         let _,_,t,_ = List.assoc i subst in
255         flexible_arg context subst t
256       with Not_found -> true)
257   | NCic.Appl (NCic.Meta (i,_) :: args)-> 
258       (try 
259         let _,_,t,_ = List.assoc i subst in
260         flexible_arg context subst 
261           (NCicReduction.head_beta_reduce ~delta:max_int 
262             (NCic.Appl (t :: args)))
263       with Not_found -> true)
264    (* this is a cheap whd, it only performs zeta-reduction.
265     * 
266     * it works when the **omissis** disambiguation algorithm
267     * is run on `let x := K a b in t`, K is substituted for a 
268     * ? and thus in t metavariables have a flexible Rel
269     *)
270   | NCic.Rel i ->
271       (try
272          match List.nth context (i-1)
273          with 
274          | _,NCic.Def (bo,_) ->
275                flexible_arg context subst
276                  (NCicSubstitution.lift i bo)
277          | _ -> false
278       with 
279       | Failure _ -> 
280           prerr_endline (Printf.sprintf "Rel %d inside context:\n%s" i  
281             (NCicPp.ppcontext ~subst ~metasenv:[] context));
282           assert false
283       | Invalid_argument _ -> assert false)
284   | _ -> false
285 ;;
286
287 let is_out_scope = function `OutScope _ -> true | _ -> false;;
288 let is_out_scope_tag = List.exists is_out_scope;;
289 let int_of_out_scope_tag tag = 
290  match List.filter is_out_scope tag with [`OutScope n] -> n | _ -> assert false
291 ;;
292
293
294 exception Found;;
295
296 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
297    otherwise the occur check does not make sense in case of unification
298    of ?n with ?n *)
299 let delift ~unify metasenv subst context n l t =
300   (*D*)  inside 'D'; try let rc =  
301   let is_in_scope_meta subst = function
302     | NCic.Meta (i,_) ->
303         (try 
304            let tag, _, _, _ = NCicUtils.lookup_subst i subst in 
305             List.mem `InScope tag
306         with NCicUtils.Subst_not_found _ -> false)
307     | _ -> false
308   in
309   let contains_in_scope subst t = 
310     let rec aux _ () = function
311       | NCic.Meta _ as t ->
312           if is_in_scope_meta subst t then raise Found
313           else ()
314       | t -> 
315           if is_in_scope_meta subst t then raise Found
316           else NCicUtils.fold (fun _ () -> ()) () aux () t
317     in
318     try aux () () t; false with Found -> true
319   in
320   let unify_list in_scope = 
321     match l with
322     | _, NCic.Irl _ -> fun _ _ _ _ _ -> None
323     | shift, NCic.Ctx l -> fun metasenv subst context k t ->
324        if flexible_arg context subst t || contains_in_scope subst t then None else
325          let lb = 
326            List.map (fun t -> 
327             let t = NCicSubstitution.lift (k+shift) t in
328             t, flexible_arg context subst t) 
329            l 
330          in
331          HExtlib.list_findopt
332           (fun (li,flexible) i ->
333             if flexible || i < in_scope then None else
334              match unify metasenv subst context li t with
335              | Some (metasenv,subst) -> 
336                  Some ((metasenv, subst), NCic.Rel (i+1+k))
337              | None -> None)
338           lb
339   in
340   let rec aux (context,k,in_scope) (metasenv, subst as ms) t = 
341    match unify_list in_scope metasenv subst context k t with
342    | Some x -> x
343    | None -> 
344     match t with 
345     | NCic.Rel n as t when n <= k -> ms, t
346     | NCic.Rel n -> 
347         (try
348           match List.nth context (n-1) with
349           | _,NCic.Def (bo,_) -> 
350                 (try ms, NCic.Rel ((position in_scope (n-k) l) + k)
351                  with NotInTheList ->
352                 (* CSC: This bit of reduction hurts performances since it is
353                  * possible to  have an exponential explosion of the size of the
354                  * proof. required for nat/nth_prime.ma *)
355                   aux (context,k,in_scope) ms (NCicSubstitution.lift n bo))
356           | _,NCic.Decl _ -> ms, NCic.Rel ((position in_scope (n-k) l) + k)
357         with Failure _ -> assert false) (*Unbound variable found in delift*)
358     | NCic.Meta (i,_) when i=n ->
359          raise (MetaSubstFailure (lazy (Printf.sprintf (
360            "Cannot unify the metavariable ?%d with a term that has "^^
361            "as subterm %s in which the same metavariable "^^
362            "occurs (occur check)") i 
363             (NCicPp.ppterm ~context ~metasenv ~subst t))))
364     | NCic.Meta (i,l1) as orig ->
365         (try
366            let tag,c,t,ty = NCicUtils.lookup_subst i subst in
367            let in_scope, clear = 
368             if List.mem `InScope tag then 0, true
369             else if is_out_scope_tag tag then int_of_out_scope_tag tag,true
370             else in_scope, false
371            in
372            let ms = 
373              if not clear then ms
374              else 
375                metasenv, 
376                (i,([],c,t,ty)) :: List.filter (fun j,_ -> i <> j) subst
377            in
378            aux (context,k,in_scope) ms (NCicSubstitution.subst_meta l1 t)
379          with NCicUtils.Subst_not_found _ ->
380            if snd l1 = NCic.Irl 0 || snd l1 = NCic.Ctx [] then ms, orig
381            else
382               let shift1,lc1 = l1 in
383               let shift,lc = l in
384               let shift = shift + k in
385               match lc, lc1 with
386               | NCic.Irl len, NCic.Irl len1 
387                 when shift1 + len1 < shift || shift1 > shift + len ->
388                   let restrictions = HExtlib.list_seq 1 (len1 + 1) in
389                   let metasenv, subst, newmeta, more_restricted = 
390                    restrict metasenv subst i restrictions in
391                   let l' = (0,NCic.Irl (max 0 (k-shift1))) in
392                   let l' = purge_restricted restrictions more_restricted l' in
393                   (metasenv, subst),NCic.Meta (newmeta,l')
394               | NCic.Irl len, NCic.Irl len1 ->
395                   let low_restrictions, new_shift = 
396                     if k <= shift1 && shift1 < shift then 
397                       HExtlib.list_seq 1 (shift - shift1 + 1), k
398                     else if shift1 < k (* <= shift *) then
399                       let save_below = k - shift1 in
400                       HExtlib.list_seq (save_below + 1) (shift - shift1 + 1),
401                       shift1
402                     else [], shift1 - shift + k
403                   in
404                   let high_restrictions = 
405                     let last = shift + len in
406                     let last1 = shift1 + len1 in
407                     if last1 > last then
408                       let high_gap = last1 - last in
409                       HExtlib.list_seq (len1 - high_gap + 1) (len1 + 1)
410                     else []
411                   in
412                   let restrictions = low_restrictions @ high_restrictions in
413                   if restrictions = [] then
414                     if shift = k then ms, orig
415                     else ms, NCic.Meta (i, (new_shift, lc1))
416                   else
417                     let metasenv, subst, newmeta, more_restricted = 
418                      restrict metasenv subst i restrictions in
419                     let newlc_len = len1 - List.length restrictions in 
420                     let l' = new_shift, NCic.Irl newlc_len in
421                     let l' = purge_restricted restrictions more_restricted l' in
422                     (metasenv, subst),NCic.Meta(newmeta,l')
423
424               | _ ->
425                   let lc1 = NCicUtils.expand_local_context lc1 in
426                   let lc1 = List.map (NCicSubstitution.lift shift1) lc1 in
427                   let rec deliftl tbr j ms = function
428                     | [] -> ms, tbr, []
429                     | t::tl ->
430                         let ms, tbr, tl = deliftl tbr (j+1) ms tl in
431                         try 
432                           let ms, t = aux (context,k,in_scope) ms t in 
433                           ms, tbr, t::tl
434                         with
435                         | NotInTheList | MetaSubstFailure _ -> ms, j::tbr, tl
436                   in
437                   let (metasenv, subst), to_be_r, lc1' = deliftl [] 1 ms lc1 in
438                   pp (lazy ("TO BE RESTRICTED: " ^ 
439                    (String.concat "," (List.map string_of_int to_be_r))));
440                   let l1 = pack_lc (0, NCic.Ctx lc1') in
441                   pp (lazy ("newmeta:" ^ NCicPp.ppterm
442                    ~metasenv ~subst ~context (NCic.Meta (999,l1))));
443                   pp (lazy (NCicPp.ppmetasenv ~subst metasenv));
444                   if to_be_r = [] then
445                     (metasenv, subst), 
446                     (if lc1' = lc1 then orig else NCic.Meta (i,l1))
447                   else
448                     let metasenv, subst, newmeta, more_restricted = 
449                      restrict metasenv subst i to_be_r in
450                     let l1 = purge_restricted to_be_r more_restricted l1 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 ;;