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