]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicReduction.ml
added auto_cache in the dupable status after an
[helm.git] / helm / software / components / ng_kernel / nCicReduction.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 module C = NCic
15 module Ref = NReference
16 module E = NCicEnvironment
17
18 exception AssertFailure of string Lazy.t;;
19
20 module type Strategy = sig
21   type stack_term
22   type env_term
23   type config = int * env_term list * C.term * stack_term list
24   val to_env :
25    reduce: (delta:int -> config -> config * bool) -> 
26    unwind: (config -> C.term) ->
27     config -> env_term
28   val from_stack : delta:int -> stack_term -> config
29   val from_stack_list_for_unwind :
30     unwind: (config -> C.term) -> stack_term list -> C.term list
31   val from_env : delta:int -> env_term -> config
32   val from_env_for_unwind :
33     unwind: (config -> C.term) -> env_term -> C.term
34   val stack_to_env :
35    reduce: (delta:int -> config -> config * bool) -> 
36    unwind: (config -> C.term) ->
37     stack_term -> env_term
38   val compute_to_env :
39    reduce: (delta:int -> config -> config * bool) -> 
40    unwind: (config -> C.term) ->
41     int -> env_term list -> C.term -> env_term
42   val compute_to_stack :
43    reduce: (delta:int -> config -> config * bool) -> 
44    unwind: (config -> C.term) ->
45     config -> stack_term
46  end
47 ;;
48
49 module CallByValueByNameForUnwind' : Strategy = struct
50   type config = int * env_term list * C.term * stack_term list
51   and stack_term = 
52        config Lazy.t * (int -> config) * C.term Lazy.t
53   and env_term = 
54         config Lazy.t    (* cbneed   ~delta:0       *)
55       * (int -> config)  (* cbvalue  ~delta         *)
56       * C.term Lazy.t    (* cbname   ~delta:max_int *)
57   let to_env ~reduce ~unwind c = 
58    lazy (fst (reduce ~delta:0 c)), 
59    (fun delta -> fst (reduce ~delta c)),
60    lazy (unwind c)
61   let from_stack ~delta (c0,c,_) = if delta = 0 then Lazy.force c0 else c delta 
62   let from_stack_list_for_unwind ~unwind:_ l = 
63    List.map (fun (_,_,c) -> Lazy.force c) l
64   let from_env ~delta (c0,c,_) = if delta = 0 then Lazy.force c0 else c delta
65   let from_env_for_unwind ~unwind:_ (_,_,c) = Lazy.force c
66   let stack_to_env ~reduce:_ ~unwind:_ config = config
67   let compute_to_env ~reduce ~unwind k e t =
68    lazy (fst (reduce ~delta:0 (k,e,t,[]))), 
69    (fun delta -> fst (reduce ~delta (k,e,t,[]))), 
70    lazy (unwind (k,e,t,[]))
71   let compute_to_stack ~reduce ~unwind config = 
72    lazy (fst (reduce ~delta:0 config)), 
73    (fun delta -> fst (reduce ~delta config)), 
74    lazy (unwind config)
75  end
76 ;;
77
78 module Reduction(RS : Strategy) = struct
79   type env = RS.env_term list
80   type stack = RS.stack_term list
81   type config = int * env * C.term * stack
82
83   let rec unwind (k,e,t,s) =
84     let t = 
85       if k = 0 then t 
86       else 
87         NCicSubstitution.psubst ~avoid_beta_redexes:true  
88           (RS.from_env_for_unwind ~unwind) e t
89     in
90     if s = [] then t 
91     else C.Appl(t::(RS.from_stack_list_for_unwind ~unwind s))
92   ;;
93
94   let list_nth l n = try List.nth l n with Failure _ -> assert false;;
95   let rec replace i s t =
96     match i,s with
97     |  0,_::tl -> t::tl
98     | n,he::tl -> he::(replace (n - 1) tl t)
99     | _,_ -> assert false
100   ;;
101
102   let rec reduce ~delta ?(subst = []) context : config -> config * bool = 
103    let rec aux = function
104      | k, e, C.Rel n, s when n <= k ->
105         let k',e',t',s' = RS.from_env ~delta (list_nth e (n-1)) in
106         aux (k',e',t',s'@s)
107      | k, _, C.Rel n, s as config (* when n > k *) ->
108         let x= try Some (List.nth context (n - 1 - k)) with Failure _ -> None in
109          (match x with
110          | Some(_,C.Def(x,_)) -> aux (0,[],NCicSubstitution.lift (n - k) x,s)
111          | _ -> config, true)
112      | (k, e, C.Meta (n,l), s) as config ->
113         (try 
114            let _,_, term,_ = NCicUtils.lookup_subst n subst in
115            aux (k, e, NCicSubstitution.subst_meta l term,s)
116          with  NCicUtils.Subst_not_found _ -> config, true)
117      | (_, _, C.Implicit _, _) -> assert false
118      | (_, _, C.Sort _, _)
119      | (_, _, C.Prod _, _)
120      | (_, _, C.Lambda _, []) as config -> config, true
121      | (k, e, C.Lambda (_,_,t), p::s) ->
122          aux (k+1, (RS.stack_to_env ~reduce:(reduce ~subst context) ~unwind p)::e, t,s)
123      | (k, e, C.LetIn (_,_,m,t), s) ->
124         let m' = RS.compute_to_env ~reduce:(reduce ~subst context) ~unwind k e m in
125          aux (k+1, m'::e, t, s)
126      | (_, _, C.Appl ([]|[_]), _) -> assert false
127      | (k, e, C.Appl (he::tl), s) ->
128         let tl' =
129          List.map (fun t->RS.compute_to_stack 
130            ~reduce:(reduce ~subst context) ~unwind (k,e,t,[])) tl
131         in
132          aux (k, e, he, tl' @ s)
133      | (_, _, C.Const
134             (Ref.Ref (_,Ref.Def height) as refer), s) as config ->
135          if delta >= height then 
136            config, false
137          else 
138            let _,_,body,_,_,_ = NCicEnvironment.get_checked_def refer in
139            aux (0, [], body, s) 
140      | (_, _, C.Const (Ref.Ref (_,
141          (Ref.Decl|Ref.Ind _|Ref.Con _|Ref.CoFix _))), _) as config -> 
142            config, true
143      | (_, _, (C.Const (Ref.Ref 
144           (_,Ref.Fix (fixno,recindex,height)) as refer) as head),s) as config ->
145         (match
146           try 
147             let recarg = RS.from_stack ~delta:max_int (List.nth s recindex) in
148             let fixes,(_,_,pragma),_ = 
149               NCicEnvironment.get_checked_fixes_or_cofixes refer in
150             Some (recarg, fixes, pragma)
151           with Failure _ -> None
152         with 
153         | None -> config, true
154         | Some((_,_,C.Const(Ref.Ref(_,Ref.Con _)),_::_ as c),fs,`Projection) ->
155             let new_s = 
156               replace recindex s (RS.compute_to_stack ~reduce:(reduce ~subst
157               context) ~unwind c)
158             in
159             let _,_,_,_,body = List.nth fs fixno in
160             aux (0, [], body, new_s)
161         | Some (recparam, fixes, pragma) ->
162            match reduce ~delta:0 ~subst context recparam with
163            | (_,_,C.Const (Ref.Ref (_,Ref.Con _)), _) as c, _ 
164               when delta >= height ->
165                let new_s =
166                        (* FIXME, we should push on the stack
167                         * c for CBV and recparam for CBN *)
168                  if pragma = `Projection then
169                   replace recindex s (RS.compute_to_stack ~reduce:(reduce ~subst
170                   context) ~unwind recparam)
171                  else
172                   replace recindex s (RS.compute_to_stack ~reduce:(reduce ~subst
173                   context) ~unwind c)
174                in
175                (0, [], head, new_s), false
176            | (_,_,C.Const (Ref.Ref (_,Ref.Con _)), _) as c, _ ->
177                let new_s =
178                  replace recindex s (RS.compute_to_stack ~reduce:(reduce ~subst
179                  context) ~unwind c)
180                in
181                let _,_,_,_,body = List.nth fixes fixno in
182                aux (0, [], body, new_s)
183            | _ -> config, true)
184      | (k, e, C.Match (_,_,term,pl),s) as config ->
185         let decofix = function
186           | (_,_,C.Const(Ref.Ref(_,Ref.CoFix c)as refer),s)->
187              let cofixes,_,_ = 
188                NCicEnvironment.get_checked_fixes_or_cofixes refer in
189              let _,_,_,_,body = List.nth cofixes c in
190              let c,_ = reduce ~delta:0 ~subst context (0,[],body,s) in 
191              c
192           | config -> config
193         in
194         let match_head = k,e,term,[] in
195         let reduced,_ = reduce ~delta:0 ~subst context match_head in
196         (match decofix reduced with
197         | (_, _, C.Const (Ref.Ref (_,Ref.Con (_,j,_))),[]) ->
198             aux (k, e, List.nth pl (j-1), s)
199         | (_, _, C.Const (Ref.Ref (_,Ref.Con (_,j,lno))), s')->
200           let _,params = HExtlib.split_nth lno s' in
201           aux (k, e, List.nth pl (j-1), params@s)
202         | _ -> config, true)
203    in
204     aux
205   ;;
206
207   let whd ?(delta=0) ~subst context t = 
208    unwind (fst (reduce ~delta ~subst context (0, [], t, [])))
209   ;;
210
211  end
212 ;;
213
214
215 module RS = CallByValueByNameForUnwind';;
216 module R = Reduction(RS);;
217
218 let whd = R.whd
219
220 let (===) x y = Pervasives.compare x y = 0 ;;
221
222 let get_relevance = ref (fun ~metasenv:_ ~subst:_ _ _ -> assert false);;
223
224 let set_get_relevance f = get_relevance := f;;
225
226 let alpha_eq ~test_lambda_source aux test_eq_only metasenv subst context t1 t2 =
227  if t1 === t2 then
228    true
229  else
230    match (t1,t2) with
231    | C.Sort s1, C.Sort s2 -> 
232        NCicEnvironment.are_sorts_convertible ~test_eq_only s1 s2 
233
234    | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
235        aux true context s1 s2 &&
236        aux test_eq_only ((name1, C.Decl s1)::context) t1 t2
237    | (C.Lambda (name1,s1,t1), C.Lambda(_,_,t2)) ->
238       if test_lambda_source then
239        aux test_eq_only context t1 t2
240       else
241        (* thanks to inversion of well typedness, the source 
242         * of these lambdas must be already convertible *)
243        aux test_eq_only ((name1, C.Decl s1)::context) t1 t2
244    | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
245       aux test_eq_only context ty1 ty2 &&
246       aux test_eq_only context s1 s2 &&
247       aux test_eq_only ((name1, C.Def (s1,ty1))::context) t1 t2
248
249    | (C.Meta (n1,(s1, C.Irl _)), C.Meta (n2,(s2, C.Irl _))) 
250       when n1 = n2 && s1 = s2 -> true
251    | (C.Meta (n1,(s1, l1)), C.Meta (n2,(s2, l2))) when n1 = n2 &&
252       let l1 = NCicUtils.expand_local_context l1 in
253       let l2 = NCicUtils.expand_local_context l2 in
254       (try List.for_all2 
255         (fun t1 t2 -> aux test_eq_only context 
256           (NCicSubstitution.lift s1 t1) 
257           (NCicSubstitution.lift s2 t2))  
258         l1 l2
259       with Invalid_argument "List.for_all2" -> 
260         prerr_endline ("Meta " ^ string_of_int n1 ^ 
261           " occurrs with local contexts of different lenght\n"^
262           NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " === " ^
263           NCicPp.ppterm ~metasenv ~subst ~context t2);
264         assert false) -> true
265
266    | C.Meta (n1,l1), _ ->
267       (try 
268          let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
269          let term = NCicSubstitution.subst_meta l1 term in
270           aux test_eq_only context term t2
271        with NCicUtils.Subst_not_found _ -> false)
272    | _, C.Meta (n2,l2) ->
273       (try 
274          let _,_,term,_ = NCicUtils.lookup_subst n2 subst in
275          let term = NCicSubstitution.subst_meta l2 term in
276           aux test_eq_only context t1 term
277        with NCicUtils.Subst_not_found _ -> false)
278    
279    | (C.Appl ((C.Const r1) as hd1::tl1), C.Appl (C.Const r2::tl2)) 
280        when (Ref.eq r1 r2 && 
281          List.length (E.get_relevance r1) >= List.length tl1) ->
282      let relevance = E.get_relevance r1 in
283      let relevance = match r1 with
284          | Ref.Ref (_,Ref.Con (_,_,lno)) ->
285              let _,relevance = HExtlib.split_nth lno relevance in
286                HExtlib.mk_list false lno @ relevance
287          | _ -> relevance
288      in
289      (try
290          HExtlib.list_forall_default3_var
291           (fun t1 t2 b -> not b || aux true context t1 t2 )
292           tl1 tl2 true relevance
293         with Invalid_argument _ -> false
294            | HExtlib.FailureAt fail ->
295              let relevance = 
296                !get_relevance ~metasenv ~subst context hd1 tl1 in
297              let _,relevance = HExtlib.split_nth fail relevance in
298              let b,relevance = (match relevance with
299                | [] -> assert false
300                | b::tl -> b,tl) in
301              if (not b) then
302                let _,tl1 = HExtlib.split_nth (fail+1) tl1 in
303                let _,tl2 = HExtlib.split_nth (fail+1) tl2 in
304                  try
305                     HExtlib.list_forall_default3
306                     (fun t1 t2 b -> not b || aux true context t1 t2)
307                     tl1 tl2 true relevance
308                  with Invalid_argument _ -> false
309              else false)
310
311    | (C.Appl (hd1::tl1),  C.Appl (hd2::tl2)) ->
312        aux test_eq_only context hd1 hd2 &&
313         let relevance = !get_relevance ~metasenv ~subst context hd1 tl1 in
314         (try
315          HExtlib.list_forall_default3
316           (fun t1 t2 b -> not b || aux true context t1 t2)
317           tl1 tl2 true relevance
318         with Invalid_argument _ -> false)
319
320    | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
321       C.Match (ref2,outtype2,term2,pl2)) ->
322        let _,_,itl,_,_ = E.get_checked_indtys ref1 in
323        let _,_,ty,_ = List.nth itl tyno in
324        let rec remove_prods ~subst context ty = 
325          let ty = whd ~subst context ty in
326          match ty with
327          | C.Sort _ -> ty
328          | C.Prod (name,so,ta) -> remove_prods ~subst ((name,(C.Decl so))::context) ta
329          | _ -> assert false
330        in
331        let is_prop = 
332          match remove_prods ~subst [] ty with
333          | C.Sort C.Prop -> true
334          | _ -> false
335        in
336        Ref.eq ref1 ref2 &&
337        aux test_eq_only context outtype1 outtype2 &&
338        (is_prop || aux test_eq_only context term1 term2) &&
339        (try List.for_all2 (aux test_eq_only context) pl1 pl2
340         with Invalid_argument _ -> false)
341    | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
342    | (_,_) -> false
343 ;;
344
345 (* t1, t2 must be well-typed *)
346 let are_convertible ~metasenv ~subst =
347  let rec aux test_eq_only context t1 t2 =
348   let alpha_eq test_eq_only =
349    alpha_eq ~test_lambda_source:false aux test_eq_only metasenv subst context
350   in
351    if alpha_eq test_eq_only t1 t2 then 
352      true
353    else
354      let height_of = function
355       | C.Const (Ref.Ref (_,Ref.Def h)) 
356       | C.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
357       | C.Appl(C.Const(Ref.Ref(_,Ref.Def h))::_) 
358       | C.Appl(C.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
359       | _ -> 0
360      in
361      let put_in_whd m1 m2 =
362        R.reduce ~delta:max_int ~subst context m1,
363        R.reduce ~delta:max_int ~subst context m2
364      in
365      let small_delta_step 
366        ((_,_,t1,_ as m1), norm1 as x1) ((_,_,t2,_ as m2), norm2 as x2) 
367      = 
368        assert(not (norm1 && norm2));
369        if norm1 then
370          x1, R.reduce ~delta:(height_of t2 -1) ~subst context m2
371        else if norm2 then
372          R.reduce ~delta:(height_of t1 -1) ~subst context m1, x2
373        else
374         let h1 = height_of t1 in 
375         let h2 = height_of t2 in
376         let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
377         R.reduce ~delta ~subst context m1,
378         R.reduce ~delta ~subst context m2
379      in
380      let rec convert_machines test_eq_only
381        ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2), norm2 as m2) 
382      =
383        (alpha_eq test_eq_only
384          (R.unwind (k1,e1,t1,[])) (R.unwind (k2,e2,t2,[])) &&
385         let relevance =
386           match t1 with
387               C.Const r -> NCicEnvironment.get_relevance r
388             | _ -> [] in
389         try
390          HExtlib.list_forall_default3
391            (fun t1 t2 b  ->
392              not b ||
393              let t1 = RS.from_stack ~delta:max_int t1 in
394              let t2 = RS.from_stack ~delta:max_int t2 in
395              convert_machines true (put_in_whd t1 t2)) s1 s2 true relevance
396         with Invalid_argument _ -> false) || 
397        (not (norm1 && norm2) && convert_machines test_eq_only (small_delta_step m1 m2))
398      in
399      convert_machines test_eq_only (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
400  in
401   aux false 
402 ;;
403
404 let alpha_eq metasenv subst =
405  let rec aux test_lambda_source context t1 t2 =
406   alpha_eq ~test_lambda_source aux true metasenv subst context t1 t2
407  in
408   aux true
409 ;;
410
411 let rec head_beta_reduce ~delta ~upto ~subst t l =
412  match upto, t, l with
413   | 0, C.Appl l1, _ -> C.Appl (l1 @ l)
414   | 0, t, [] -> t
415   | 0, t, _ -> C.Appl (t::l)
416   | _, C.Meta (n,ctx), _ ->
417      (try
418        let _,_, term,_ = NCicUtils.lookup_subst n subst in
419        head_beta_reduce ~delta ~upto ~subst 
420          (NCicSubstitution.subst_meta ctx term) l
421      with NCicUtils.Subst_not_found _ -> if l = [] then t else C.Appl (t::l))
422   | _, C.Appl (hd::tl), _ -> head_beta_reduce ~delta ~upto ~subst hd (tl @ l)
423   | _, C.Lambda(_,_,bo), arg::tl ->
424      let bo = NCicSubstitution.subst arg bo in
425      head_beta_reduce ~delta ~upto:(upto - 1) ~subst bo tl
426   | _, C.Const (Ref.Ref (_, Ref.Def height) as re), _ 
427     when delta <= height ->
428       let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def re in
429       head_beta_reduce ~upto ~delta ~subst bo l
430   | _, t, [] -> t
431   | _, t, _ -> C.Appl (t::l)
432 ;;
433
434 let head_beta_reduce ?(delta=max_int) ?(upto= -1) ?(subst=[]) t = 
435   head_beta_reduce ~delta ~upto ~subst t []
436 ;;
437
438 type stack_item = RS.stack_term
439 type environment_item = RS.env_term
440
441 type machine = int * environment_item list * NCic.term * stack_item list
442
443 let reduce_machine = R.reduce
444 let from_stack = RS.from_stack
445 let unwind = R.unwind
446
447 let _ = 
448   NCicUtils.set_head_beta_reduce (fun ~upto t -> head_beta_reduce ~upto t);
449   NCicPp.set_head_beta_reduce (fun ~upto t -> head_beta_reduce ~upto t);
450 ;;
451
452 (* if n < 0, then splits all prods from an arity, returning a sort *)
453 let rec split_prods ~subst context n te =
454   match (n, R.whd ~subst context te) with
455    | (0, _) -> context,te
456    | (n, C.Sort _) when n <= 0 -> context,te
457    | (n, C.Prod (name,so,ta)) ->
458        split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
459    | (_, _) -> raise (AssertFailure (lazy "split_prods"))
460 ;;
461
462 (* vim:set foldmethod=marker: *)