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