]> matita.cs.unibo.it Git - helm.git/blob - components/ng_kernel/nCicReduction.ml
matita 0.5.1 tagged
[helm.git] / 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
17 module type Strategy = sig
18   type stack_term
19   type env_term
20   type config = int * env_term list * C.term * stack_term list
21   val to_env :
22    reduce: (config -> config) -> unwind: (config -> C.term) ->
23     config -> env_term
24   val from_stack : stack_term -> config
25   val from_stack_list_for_unwind :
26    unwind: (config -> C.term) -> stack_term list -> C.term list
27   val from_env : env_term -> config
28   val from_env_for_unwind :
29    unwind: (config -> C.term) -> env_term -> C.term
30   val stack_to_env :
31    reduce: (config -> config) -> unwind: (config -> C.term) ->
32     stack_term -> env_term
33   val compute_to_env :
34    reduce: (config -> config) -> unwind: (config -> C.term) ->
35     int -> env_term list -> C.term -> env_term
36   val compute_to_stack :
37    reduce: (config -> config) -> unwind: (config -> C.term) ->
38     config -> stack_term
39  end
40 ;;
41
42 module CallByValueByNameForUnwind' = struct
43   type config = int * env_term list * C.term * stack_term list
44   and stack_term = config lazy_t * C.term lazy_t (* cbv, cbn *)
45   and env_term = config lazy_t * C.term lazy_t (* cbv, cbn *)
46   let to_env ~reduce ~unwind c = lazy (reduce c),lazy (unwind c)
47   let from_stack (c,_) = Lazy.force c
48   let from_stack_list_for_unwind ~unwind:_ l = 
49    List.map (function (_,c) -> Lazy.force c) l
50   let from_env (c,_) = Lazy.force c
51   let from_env_for_unwind ~unwind:_ (_,c) = Lazy.force c
52   let stack_to_env ~reduce:_ ~unwind:_ config = config
53   let compute_to_env ~reduce ~unwind k e t =
54    lazy (reduce (k,e,t,[])), lazy (unwind (k,e,t,[]))
55   let compute_to_stack ~reduce ~unwind config = 
56    lazy (reduce config), lazy (unwind config)
57  end
58 ;;
59
60 module Reduction(RS : Strategy) = struct
61   type env = RS.env_term list
62   type stack = RS.stack_term list
63   type config = int * env * C.term * stack
64
65   let rec unwind (k,e,t,s) =
66     let t = 
67       if k = 0 then t 
68       else 
69         NCicSubstitution.psubst ~avoid_beta_redexes:true  
70           (RS.from_env_for_unwind ~unwind) e t
71     in
72     if s = [] then t 
73     else C.Appl(t::(RS.from_stack_list_for_unwind ~unwind s))
74   ;;
75
76   let list_nth l n = try List.nth l n with Failure _ -> assert false;;
77   let rec replace i s t =
78     match i,s with
79     |  0,_::tl -> t::tl
80     | n,he::tl -> he::(replace (n - 1) tl t)
81     | _,_ -> assert false
82   ;;
83
84   let rec reduce ~delta ?(subst = []) context : config -> config = 
85    let rec aux = function
86      | k, e, C.Rel n, s when n <= k ->
87         let k',e',t',s' = RS.from_env (list_nth e (n-1)) in
88         aux (k',e',t',s'@s)
89      | k, _, C.Rel n, s as config (* when n > k *) ->
90         let x= try Some (List.nth context (n - 1 - k)) with Failure _ -> None in
91          (match x with
92          | Some(_,C.Def(x,_)) -> aux (0,[],NCicSubstitution.lift (n - k) x,s)
93          | _ -> config)
94      | (k, e, C.Meta (n,l), s) as config ->
95         (try 
96            let _,_, term,_ = NCicUtils.lookup_subst n subst in
97            aux (k, e, NCicSubstitution.subst_meta l term,s)
98          with  NCicUtils.Subst_not_found _ -> config)
99      | (_, _, C.Implicit _, _) -> assert false
100      | (_, _, C.Sort _, _)
101      | (_, _, C.Prod _, _)
102      | (_, _, C.Lambda _, []) as config -> config
103      | (k, e, C.Lambda (_,_,t), p::s) ->
104          aux (k+1, (RS.stack_to_env ~reduce:aux ~unwind p)::e, t,s)
105      | (k, e, C.LetIn (_,_,m,t), s) ->
106         let m' = RS.compute_to_env ~reduce:aux ~unwind k e m in
107          aux (k+1, m'::e, t, s)
108      | (_, _, C.Appl ([]|[_]), _) -> assert false
109      | (k, e, C.Appl (he::tl), s) ->
110         let tl' =
111          List.map (fun t->RS.compute_to_stack ~reduce:aux ~unwind (k,e,t,[])) tl
112         in
113          aux (k, e, he, tl' @ s)
114      | (_, _, C.Const
115             (Ref.Ref (_,Ref.Def height) as refer), s) as config ->
116          if delta >= height then config else 
117            let _,_,body,_,_,_ = NCicEnvironment.get_checked_def refer in
118            aux (0, [], body, s) 
119      | (_, _, C.Const (Ref.Ref (_,
120             (Ref.Decl|Ref.Ind _|Ref.Con _|Ref.CoFix _))), _) as config -> config
121      | (_, _, C.Const (Ref.Ref 
122            (_,Ref.Fix (fixno,recindex,height)) as refer),s) as config ->
123         if delta >= height then config else
124         (match
125           try Some (RS.from_stack (List.nth s recindex))
126           with Failure _ -> None
127         with 
128         | None -> config
129         | Some recparam ->
130            let fixes,_,_ = NCicEnvironment.get_checked_fixes_or_cofixes refer in
131            match reduce ~delta:0 ~subst context recparam with
132            | (_,_,C.Const (Ref.Ref (_,Ref.Con _)), _) as c ->
133                let new_s =
134                  replace recindex s (RS.compute_to_stack ~reduce:aux ~unwind c)
135                in
136                let _,_,_,_,body = List.nth fixes fixno in
137                aux (0, [], body, new_s)
138            | _ -> config)
139      | (k, e, C.Match (_,_,term,pl),s) as config ->
140         let decofix = function
141           | (_,_,C.Const(Ref.Ref(_,Ref.CoFix c)as refer),s)->
142              let cofixes,_,_ = NCicEnvironment.get_checked_fixes_or_cofixes refer in
143              let _,_,_,_,body = List.nth cofixes c in
144              reduce ~delta:0 ~subst context (0,[],body,s)
145           | config -> config
146         in
147         (match decofix (reduce ~delta:0 ~subst context (k,e,term,[])) with
148         | (_, _, C.Const (Ref.Ref (_,Ref.Con (_,j,_))),[]) ->
149             aux (k, e, List.nth pl (j-1), s)
150         | (_, _, C.Const (Ref.Ref (_,Ref.Con (_,j,lno))), s')->
151           let _,params = HExtlib.split_nth lno s' in
152           aux (k, e, List.nth pl (j-1), params@s)
153         | _ -> config)
154    in
155     aux
156   ;;
157
158   let whd ?(delta=0) ?(subst=[]) context t = 
159    unwind (reduce ~delta ~subst context (0, [], t, []))
160   ;;
161
162  end
163 ;;
164
165
166 module RS = CallByValueByNameForUnwind';;
167 module R = Reduction(RS);;
168
169 let whd = R.whd
170
171 let (===) x y = Pervasives.compare x y = 0 ;;
172
173 (* t1, t2 must be well-typed *)
174 let are_convertible whd ?(subst=[])  =
175  let rec aux test_eq_only context t1 t2 =
176    let rec alpha_eq test_eq_only t1 t2 =
177      if t1 === t2 then
178        true
179      else
180        match (t1,t2) with
181        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
182            NCicEnvironment.universe_leq a b
183        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
184            NCicEnvironment.universe_eq a b
185        | (C.Sort s1,C.Sort (C.Type _)) -> (not test_eq_only)
186        | (C.Sort s1, C.Sort s2) -> s1 = s2
187
188        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
189            aux true context s1 s2 &&
190            aux test_eq_only ((name1, C.Decl s1)::context) t1 t2
191        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) ->
192           aux true context s1 s2 && 
193           aux test_eq_only ((name1, C.Decl s1)::context) t1 t2
194        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
195           aux test_eq_only context ty1 ty2 &&
196           aux test_eq_only context s1 s2 &&
197           aux test_eq_only ((name1, C.Def (s1,ty1))::context) t1 t2
198
199        | (C.Meta (n1,(s1, C.Irl i1)), C.Meta (n2,(s2, C.Irl i2))) 
200           when n1 = n2 && s1 = s2 -> true
201        | (C.Meta (n1,(s1, l1)), C.Meta (n2,(s2, l2))) when n1 = n2 &&
202           let l1 = NCicUtils.expand_local_context l1 in
203           let l2 = NCicUtils.expand_local_context l2 in
204           (try List.for_all2 
205             (fun t1 t2 -> aux test_eq_only context 
206               (NCicSubstitution.lift s1 t1) 
207               (NCicSubstitution.lift s2 t2))  
208             l1 l2
209           with Invalid_argument _ -> assert false) -> true
210
211        | C.Meta (n1,l1), _ ->
212           (try 
213              let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
214              let term = NCicSubstitution.subst_meta l1 term in
215               aux test_eq_only context term t2
216            with NCicUtils.Subst_not_found _ -> false)
217        | _, C.Meta (n2,l2) ->
218           (try 
219              let _,_,term,_ = NCicUtils.lookup_subst n2 subst in
220              let term = NCicSubstitution.subst_meta l2 term in
221               aux test_eq_only context t1 term
222            with NCicUtils.Subst_not_found _ -> false)
223
224        | (C.Appl (C.Const r1::tl1), C.Appl (C.Const r2::tl2)) ->
225           r1 = r2 &&
226            let relevance = NCicEnvironment.get_relevance r1 in
227            (try
228              HExtlib.list_forall_default3
229               (fun t1 t2 b -> not b || aux test_eq_only context t1 t2)
230               tl1 tl2 true relevance
231             with Invalid_argument _ -> false)
232
233        | (C.Appl l1, C.Appl l2) ->
234           (try List.for_all2 (aux test_eq_only context) l1 l2
235            with Invalid_argument _ -> false)
236
237        | (C.Match (ref1,outtype1,term1,pl1),
238           C.Match (ref2,outtype2,term2,pl2)) -> 
239            Ref.eq ref1 ref2 &&
240            aux test_eq_only context outtype1 outtype2 &&
241            aux test_eq_only context term1 term2 &&
242            (try List.for_all2 (aux test_eq_only context) pl1 pl2
243             with Invalid_argument _ -> false)
244
245        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
246        | (_,_) -> false
247   in
248    if alpha_eq test_eq_only t1 t2 then 
249      true
250    else
251      let height_of = function
252       | C.Const (Ref.Ref (_,Ref.Def h)) 
253       | C.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
254       | C.Appl(C.Const(Ref.Ref(_,Ref.Def h))::_) 
255       | C.Appl(C.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
256       | _ -> 0
257      in
258      let small_delta_step (_,_,t1,_ as m1) (_,_,t2,_ as m2) = 
259        let h1 = height_of t1 in 
260        let h2 = height_of t2 in
261        let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
262        R.reduce ~delta ~subst context m1,
263        R.reduce ~delta ~subst context m2,
264        delta
265      in
266      let rec convert_machines ((k1,e1,t1,s1 as m1),(k2,e2,t2,s2 as m2),delta) =
267        (alpha_eq test_eq_only
268          (R.unwind (k1,e1,t1,[])) (R.unwind (k2,e2,t2,[])) &&
269         let relevance =
270           match t1 with
271               C.Const r -> NCicEnvironment.get_relevance r
272             | _ -> [] in
273         try
274          HExtlib.list_forall_default3
275            (fun t1 t2 b  ->
276              not b ||
277              let t1 = RS.from_stack t1 in
278              let t2 = RS.from_stack t2 in
279              convert_machines (small_delta_step t1 t2)) s1 s2 true relevance
280         with Invalid_argument _ -> false) || 
281        (delta > 0 &&
282           let delta = delta - 1 in 
283           let red = R.reduce ~delta ~subst context in
284           convert_machines (red m1,red m2,delta))
285      in
286      convert_machines (small_delta_step (0,[],t1,[]) (0,[],t2,[]))
287  in
288   aux false 
289 ;;
290
291 let are_convertible = are_convertible whd
292
293 let rec head_beta_reduce ?(delta=max_int) ?(upto=(-1)) t l =
294  match upto, t, l with
295   | 0, C.Appl l1, _ -> C.Appl (l1 @ l)
296   | 0, t, [] -> t
297   | 0, t, _ -> C.Appl (t::l)
298   | _, C.Appl (hd::tl), _ -> head_beta_reduce ~delta ~upto hd (tl @ l)
299   | _, C.Lambda(_,_,bo), arg::tl ->
300      let bo = NCicSubstitution.subst arg bo in
301      head_beta_reduce ~delta ~upto:(upto - 1) bo tl
302   | _, C.Const (Ref.Ref (_, Ref.Def height) as re), _ 
303     when delta <= height ->
304       let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def re in
305       head_beta_reduce ~upto ~delta bo l
306   | _, t, [] -> t
307   | _, t, _ -> C.Appl (t::l)
308 ;;
309
310 let head_beta_reduce ?delta ?upto t = head_beta_reduce ?delta ?upto t [];;
311
312 (* vim:set foldmethod=marker: *)