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