]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/proofEngineReduction.ml
7d4a799601dad71082943a92b5685480996b60da
[helm.git] / helm / gTopLevel / proofEngineReduction.ml
1 (* Copyright (C) 2000, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (******************************************************************************)
27 (*                                                                            *)
28 (*                               PROJECT HELM                                 *)
29 (*                                                                            *)
30 (*                Claudio Sacerdoti Coen <sacerdot@cs.unibo.it>               *)
31 (*                                 12/04/2002                                 *)
32 (*                                                                            *)
33 (*                                                                            *)
34 (******************************************************************************)
35
36
37 (* The code of this module is derived from the code of CicReduction *)
38
39 exception Impossible of int;;
40 exception ReferenceToDefinition;;
41 exception ReferenceToAxiom;;
42 exception ReferenceToVariable;;
43 exception ReferenceToCurrentProof;;
44 exception ReferenceToInductiveDefinition;;
45 exception WrongUriToInductiveDefinition;;
46 exception RelToHiddenHypothesis;;
47
48 (* "textual" replacement of a subterm with another one *)
49 let replace ~equality ~what ~with_what ~where =
50  let module C = Cic in
51   let rec aux =
52    function
53       t when (equality t what) -> with_what
54     | C.Rel _ as t -> t
55     | C.Var _ as t  -> t
56     | C.Meta _ as t -> t
57     | C.Sort _ as t -> t
58     | C.Implicit as t -> t
59     | C.Cast (te,ty) -> C.Cast (aux te, aux ty)
60     | C.Prod (n,s,t) -> C.Prod (n, aux s, aux t)
61     | C.Lambda (n,s,t) -> C.Lambda (n, aux s, aux t)
62     | C.LetIn (n,s,t) -> C.LetIn (n, aux s, aux t)
63     | C.Appl l ->
64        (* Invariant enforced: no application of an application *)
65        (match List.map aux l with
66            (C.Appl l')::tl -> C.Appl (l'@tl)
67          | l' -> C.Appl l')
68     | C.Const _ as t -> t
69     | C.Abst _ as t -> t
70     | C.MutInd _ as t -> t
71     | C.MutConstruct _ as t -> t
72     | C.MutCase (sp,cookingsno,i,outt,t,pl) ->
73        C.MutCase (sp,cookingsno,i,aux outt, aux t,
74         List.map aux pl)
75     | C.Fix (i,fl) ->
76        let substitutedfl =
77         List.map
78          (fun (name,i,ty,bo) -> (name, i, aux ty, aux bo))
79           fl
80        in
81         C.Fix (i, substitutedfl)
82     | C.CoFix (i,fl) ->
83        let substitutedfl =
84         List.map
85          (fun (name,ty,bo) -> (name, aux ty, aux bo))
86           fl
87        in
88         C.CoFix (i, substitutedfl)
89   in
90    aux where
91 ;;
92
93 (* Takes a well-typed term and fully reduces it. *)
94 (*CSC: It does not perform reduction in a Case *)
95 let reduce context =
96  let rec reduceaux context l =
97   let module C = Cic in
98   let module S = CicSubstitution in
99    function
100       C.Rel n as t ->
101        (match List.nth context (n-1) with
102            Some (_,C.Decl _) -> if l = [] then t else C.Appl (t::l)
103          | Some (_,C.Def bo) -> reduceaux context l (S.lift n bo)
104          | None -> raise RelToHiddenHypothesis
105        )
106     | C.Var uri as t ->
107        (match CicEnvironment.get_cooked_obj uri 0 with
108            C.Definition _ -> raise ReferenceToDefinition
109          | C.Axiom _ -> raise ReferenceToAxiom
110          | C.CurrentProof _ -> raise ReferenceToCurrentProof
111          | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
112          | C.Variable (_,None,_) -> if l = [] then t else C.Appl (t::l)
113          | C.Variable (_,Some body,_) -> reduceaux context l body
114        )
115     | C.Meta _ as t -> if l = [] then t else C.Appl (t::l)
116     | C.Sort _ as t -> t (* l should be empty *)
117     | C.Implicit as t -> t
118     | C.Cast (te,ty) ->
119        C.Cast (reduceaux context l te, reduceaux context l ty)
120     | C.Prod (name,s,t) ->
121        assert (l = []) ;
122        C.Prod (name,
123         reduceaux context [] s,
124         reduceaux ((Some (name,C.Decl s))::context) [] t)
125     | C.Lambda (name,s,t) ->
126        (match l with
127            [] ->
128             C.Lambda (name,
129              reduceaux context [] s,
130              reduceaux ((Some (name,C.Decl s))::context) [] t)
131          | he::tl -> reduceaux context tl (S.subst he t)
132            (* when name is Anonimous the substitution should be superfluous *)
133        )
134     | C.LetIn (n,s,t) ->
135        reduceaux context l (S.subst (reduceaux context [] s) t)
136     | C.Appl (he::tl) ->
137        let tl' = List.map (reduceaux context []) tl in
138         reduceaux context (tl'@l) he
139     | C.Appl [] -> raise (Impossible 1)
140     | C.Const (uri,cookingsno) as t ->
141        (match CicEnvironment.get_cooked_obj uri cookingsno with
142            C.Definition (_,body,_,_) -> reduceaux context l body
143          | C.Axiom _ -> if l = [] then t else C.Appl (t::l)
144          | C.Variable _ -> raise ReferenceToVariable
145          | C.CurrentProof (_,_,body,_) -> reduceaux context l body
146          | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
147        )
148     | C.Abst _ as t -> t (*CSC l should be empty ????? *)
149     | C.MutInd (uri,_,_) as t -> if l = [] then t else C.Appl (t::l)
150     | C.MutConstruct (uri,_,_,_) as t -> if l = [] then t else C.Appl (t::l)
151     | C.MutCase (mutind,cookingsno,i,outtype,term,pl) ->
152        let decofix =
153         function
154            C.CoFix (i,fl) as t ->
155             let tys =
156              List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl
157             in
158              let (_,_,body) = List.nth fl i in
159               let body' =
160                let counter = ref (List.length fl) in
161                 List.fold_right
162                  (fun _ -> decr counter ; S.subst (C.CoFix (!counter,fl)))
163                  fl
164                  body
165               in
166                reduceaux (tys@context) [] body'
167          | C.Appl (C.CoFix (i,fl) :: tl) ->
168             let tys =
169              List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl
170             in
171              let (_,_,body) = List.nth fl i in
172               let body' =
173                let counter = ref (List.length fl) in
174                 List.fold_right
175                  (fun _ -> decr counter ; S.subst (C.CoFix (!counter,fl)))
176                  fl
177                  body
178               in
179                let tl' = List.map (reduceaux context []) tl in
180                 reduceaux (tys@context) tl' body'
181          | t -> t
182        in
183         (match decofix (reduceaux context [] term) with
184             C.MutConstruct (_,_,_,j) -> reduceaux context l (List.nth pl (j-1))
185           | C.Appl (C.MutConstruct (_,_,_,j) :: tl) ->
186              let (arity, r, num_ingredients) =
187               match CicEnvironment.get_obj mutind with
188                  C.InductiveDefinition (tl,ingredients,r) ->
189                    let (_,_,arity,_) = List.nth tl i
190                    and num_ingredients =
191                     List.fold_right
192                      (fun (k,l) i ->
193                        if k < cookingsno then i + List.length l else i
194                      ) ingredients 0
195                    in
196                     (arity,r,num_ingredients)
197                | _ -> raise WrongUriToInductiveDefinition
198              in
199               let ts =
200                let num_to_eat = r + num_ingredients in
201                 let rec eat_first =
202                  function
203                     (0,l) -> l
204                   | (n,he::tl) when n > 0 -> eat_first (n - 1, tl)
205                   | _ -> raise (Impossible 5)
206                 in
207                  eat_first (num_to_eat,tl)
208               in
209                reduceaux context (ts@l) (List.nth pl (j-1))
210          | C.Abst _ | C.Cast _ | C.Implicit ->
211             raise (Impossible 2) (* we don't trust our whd ;-) *)
212          | _ ->
213            let outtype' = reduceaux context [] outtype in
214            let term' = reduceaux context [] term in
215            let pl' = List.map (reduceaux context []) pl in
216             let res =
217              C.MutCase (mutind,cookingsno,i,outtype',term',pl')
218             in
219              if l = [] then res else C.Appl (res::l)
220        )
221     | C.Fix (i,fl) ->
222        let tys =
223         List.map (function (name,_,ty,_) -> Some (C.Name name, C.Decl ty)) fl
224        in
225         let t' () =
226          let fl' =
227           List.map
228            (function (n,recindex,ty,bo) ->
229              (n,recindex,reduceaux context [] ty, reduceaux (tys@context) [] bo)
230            ) fl
231          in
232           C.Fix (i, fl')
233         in
234          let (_,recindex,_,body) = List.nth fl i in
235           let recparam =
236            try
237             Some (List.nth l recindex)
238            with
239             _ -> None
240           in
241            (match recparam with
242                Some recparam ->
243                 (match reduceaux context [] recparam with
244                     C.MutConstruct _
245                   | C.Appl ((C.MutConstruct _)::_) ->
246                      let body' =
247                       let counter = ref (List.length fl) in
248                        List.fold_right
249                         (fun _ -> decr counter ; S.subst (C.Fix (!counter,fl)))
250                         fl
251                         body
252                      in
253                       (* Possible optimization: substituting whd recparam in l*)
254                       reduceaux context l body'
255                   | _ -> if l = [] then t' () else C.Appl ((t' ())::l)
256                 )
257              | None -> if l = [] then t' () else C.Appl ((t' ())::l)
258            )
259     | C.CoFix (i,fl) ->
260        let tys =
261         List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl
262        in
263         let t' =
264          let fl' =
265           List.map
266            (function (n,ty,bo) ->
267              (n,reduceaux context [] ty, reduceaux (tys@context) [] bo)
268            ) fl
269          in
270           C.CoFix (i, fl')
271         in
272          if l = [] then t' else C.Appl (t'::l)
273  in
274   reduceaux context []
275 ;;
276
277 exception WrongShape;;
278 exception AlreadySimplified;;
279 exception WhatShouldIDo;;
280
281 (*CSC: I fear it is still weaker than Coq's one. For example, Coq is *)
282 (*CSCS: able to simpl (foo (S n) (S n)) to (foo (S O) n) where       *)
283 (*CSC:  Fix foo                                                      *)
284 (*CSC:   {foo [n,m:nat]:nat :=                                       *)
285 (*CSC:     Cases m of O => n | (S p) => (foo (S O) p) end            *)
286 (*CSC:   }                                                           *)
287 (* Takes a well-typed term and                                               *)
288 (*  1) Performs beta-iota-zeta reduction until delta reduction is needed     *)
289 (*  2) Attempts delta-reduction. If the residual is a Fix lambda-abstracted  *)
290 (*     w.r.t. zero or more variables and if the Fix can be reduced, than it  *)
291 (*     is reduced, the delta-reduction is succesfull and the whole algorithm *)
292 (*     is applied again to the new redex; Step 3) is applied to the result   *)
293 (*     of the recursive simplification. Otherwise, if the Fix can not be     *)
294 (*     reduced, than the delta-reductions fails and the delta-redex is       *)
295 (*     not reduced. Otherwise, if the delta-residual is not the              *)
296 (*     lambda-abstraction of a Fix, then it is reduced and the result is     *)
297 (*     directly returned, without performing step 3).                        *) 
298 (*  3) Folds the application of the constant to the arguments that did not   *)
299 (*     change in every iteration, i.e. to the actual arguments for the       *)
300 (*     lambda-abstractions that precede the Fix.                             *)
301 (*CSC: It does not perform simplification in a Case *)
302 let simpl context =
303  (* reduceaux is equal to the reduceaux locally defined inside *)
304  (*reduce, but for the const case.                             *) 
305  (**** Step 1 ****)
306  let rec reduceaux context l =
307   let module C = Cic in
308   let module S = CicSubstitution in
309    function
310       C.Rel n as t ->
311        (match List.nth context (n-1) with
312            Some (_,C.Decl _) -> if l = [] then t else C.Appl (t::l)
313          | Some (_,C.Def bo) -> reduceaux context l (S.lift n bo)
314          | None -> raise RelToHiddenHypothesis
315        )
316     | C.Var uri as t ->
317        (match CicEnvironment.get_cooked_obj uri 0 with
318            C.Definition _ -> raise ReferenceToDefinition
319          | C.Axiom _ -> raise ReferenceToAxiom
320          | C.CurrentProof _ -> raise ReferenceToCurrentProof
321          | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
322          | C.Variable (_,None,_) -> if l = [] then t else C.Appl (t::l)
323          | C.Variable (_,Some body,_) -> reduceaux context l body
324        )
325     | C.Meta _ as t -> if l = [] then t else C.Appl (t::l)
326     | C.Sort _ as t -> t (* l should be empty *)
327     | C.Implicit as t -> t
328     | C.Cast (te,ty) ->
329        C.Cast (reduceaux context l te, reduceaux context l ty)
330     | C.Prod (name,s,t) ->
331        assert (l = []) ;
332        C.Prod (name,
333         reduceaux context [] s,
334         reduceaux ((Some (name,C.Decl s))::context) [] t)
335     | C.Lambda (name,s,t) ->
336        (match l with
337            [] ->
338             C.Lambda (name,
339              reduceaux context [] s,
340              reduceaux ((Some (name,C.Decl s))::context) [] t)
341          | he::tl -> reduceaux context tl (S.subst he t)
342            (* when name is Anonimous the substitution should be superfluous *)
343        )
344     | C.LetIn (n,s,t) ->
345        reduceaux context l (S.subst (reduceaux context [] s) t)
346     | C.Appl (he::tl) ->
347        let tl' = List.map (reduceaux context []) tl in
348         reduceaux context (tl'@l) he
349     | C.Appl [] -> raise (Impossible 1)
350     | C.Const (uri,cookingsno) as t ->
351        (match CicEnvironment.get_cooked_obj uri cookingsno with
352            C.Definition (_,body,_,_) ->
353             begin
354              try
355               (**** Step 2 ****)
356               let res,constant_args =
357                let rec aux rev_constant_args l =
358                 function
359                    C.Lambda (name,s,t) as t' ->
360                     begin
361                      match l with
362                         [] -> raise WrongShape
363                       | he::tl ->
364                          (* when name is Anonimous the substitution should be *)
365                          (* superfluous                                       *)
366                          aux (he::rev_constant_args) tl (S.subst he t)
367                     end
368                  | C.LetIn (_,_,_) -> raise WhatShouldIDo (*CSC: ?????????? *)
369                  | C.Fix (i,fl) as t ->
370                     let tys =
371                      List.map (function (name,_,ty,_) ->
372                       Some (C.Name name, C.Decl ty)) fl
373                     in
374                      let (_,recindex,_,body) = List.nth fl i in
375                       let recparam =
376                        try
377                         List.nth l recindex
378                        with
379                         _ -> raise AlreadySimplified
380                       in
381                        (match CicReduction.whd context recparam with
382                            C.MutConstruct _
383                          | C.Appl ((C.MutConstruct _)::_) ->
384                             let body' =
385                              let counter = ref (List.length fl) in
386                               List.fold_right
387                                (function _ ->
388                                  decr counter ; S.subst (C.Fix (!counter,fl))
389                                ) fl body
390                             in
391                              (* Possible optimization: substituting whd *)
392                              (* recparam in l                           *)
393                              reduceaux (tys@context) l body',
394                               List.rev rev_constant_args
395                          | _ -> raise AlreadySimplified
396                        )
397                  | _ -> raise WrongShape
398                in
399                 aux [] l body
400               in
401                (**** Step 3 ****)
402                let term_to_fold =
403                 match constant_args with
404                    [] -> C.Const (uri,cookingsno)
405                  | _ -> C.Appl ((C.Const (uri,cookingsno))::constant_args)
406                in
407                 let reduced_term_to_fold = reduce context term_to_fold in
408                  replace (=) reduced_term_to_fold term_to_fold res
409              with
410                 WrongShape ->
411                  (* The constant does not unfold to a Fix lambda-abstracted   *)
412                  (* w.r.t. zero or more variables. We just perform reduction. *)
413                  reduceaux context l body
414               | AlreadySimplified ->
415                  (* If we performed delta-reduction, we would find a Fix   *)
416                  (* not applied to a constructor. So, we refuse to perform *)
417                  (* delta-reduction.                                       *)
418                  if l = [] then
419                     t
420                  else
421                   C.Appl (t::l)
422             end
423          | C.Axiom _ -> if l = [] then t else C.Appl (t::l)
424          | C.Variable _ -> raise ReferenceToVariable
425          | C.CurrentProof (_,_,body,_) -> reduceaux context l body
426          | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
427        )
428     | C.Abst _ as t -> t (*CSC l should be empty ????? *)
429     | C.MutInd (uri,_,_) as t -> if l = [] then t else C.Appl (t::l)
430     | C.MutConstruct (uri,_,_,_) as t -> if l = [] then t else C.Appl (t::l)
431     | C.MutCase (mutind,cookingsno,i,outtype,term,pl) ->
432        let decofix =
433         function
434            C.CoFix (i,fl) as t ->
435             let tys =
436              List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl            in
437              let (_,_,body) = List.nth fl i in
438               let body' =
439                let counter = ref (List.length fl) in
440                 List.fold_right
441                  (fun _ -> decr counter ; S.subst (C.CoFix (!counter,fl)))
442                  fl
443                  body
444               in
445                reduceaux (tys@context) [] body'
446          | C.Appl (C.CoFix (i,fl) :: tl) ->
447             let tys =
448              List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl            in
449              let (_,_,body) = List.nth fl i in
450               let body' =
451                let counter = ref (List.length fl) in
452                 List.fold_right
453                  (fun _ -> decr counter ; S.subst (C.CoFix (!counter,fl)))
454                  fl
455                  body
456               in
457                let tl' = List.map (reduceaux context []) tl in
458                 reduceaux (tys@context) tl body'
459          | t -> t
460        in
461         (match decofix (reduceaux context [] term) with
462             C.MutConstruct (_,_,_,j) -> reduceaux context l (List.nth pl (j-1))
463           | C.Appl (C.MutConstruct (_,_,_,j) :: tl) ->
464              let (arity, r, num_ingredients) =
465               match CicEnvironment.get_obj mutind with
466                  C.InductiveDefinition (tl,ingredients,r) ->
467                    let (_,_,arity,_) = List.nth tl i
468                    and num_ingredients =
469                     List.fold_right
470                      (fun (k,l) i ->
471                        if k < cookingsno then i + List.length l else i
472                      ) ingredients 0
473                    in
474                     (arity,r,num_ingredients)
475                | _ -> raise WrongUriToInductiveDefinition
476              in
477               let ts =
478                let num_to_eat = r + num_ingredients in
479                 let rec eat_first =
480                  function
481                     (0,l) -> l
482                   | (n,he::tl) when n > 0 -> eat_first (n - 1, tl)
483                   | _ -> raise (Impossible 5)
484                 in
485                  eat_first (num_to_eat,tl)
486               in
487                reduceaux context (ts@l) (List.nth pl (j-1))
488          | C.Abst _ | C.Cast _ | C.Implicit ->
489             raise (Impossible 2) (* we don't trust our whd ;-) *)
490          | _ ->
491            let outtype' = reduceaux context [] outtype in
492            let term' = reduceaux context [] term in
493            let pl' = List.map (reduceaux context []) pl in
494             let res =
495              C.MutCase (mutind,cookingsno,i,outtype',term',pl')
496             in
497              if l = [] then res else C.Appl (res::l)
498        )
499     | C.Fix (i,fl) ->
500        let tys =
501         List.map (function (name,_,ty,_) -> Some (C.Name name, C.Decl ty)) fl
502        in
503         let t' () =
504          let fl' =
505           List.map
506            (function (n,recindex,ty,bo) ->
507              (n,recindex,reduceaux context [] ty, reduceaux (tys@context) [] bo)
508            ) fl
509          in
510           C.Fix (i, fl')
511         in
512          let (_,recindex,_,body) = List.nth fl i in
513           let recparam =
514            try
515             Some (List.nth l recindex)
516            with
517             _ -> None
518           in
519            (match recparam with
520                Some recparam ->
521                 (match reduceaux context [] recparam with
522                     C.MutConstruct _
523                   | C.Appl ((C.MutConstruct _)::_) ->
524                      let body' =
525                       let counter = ref (List.length fl) in
526                        List.fold_right
527                         (fun _ -> decr counter ; S.subst (C.Fix (!counter,fl)))
528                         fl
529                         body
530                      in
531                       (* Possible optimization: substituting whd recparam in l*)
532                       reduceaux context l body'
533                   | _ -> if l = [] then t' () else C.Appl ((t' ())::l)
534                 )
535              | None -> if l = [] then t' () else C.Appl ((t' ())::l)
536            )
537     | C.CoFix (i,fl) ->
538        let tys =
539         List.map (function (name,ty,_) -> Some (C.Name name, C.Decl ty)) fl
540        in
541         let t' =
542          let fl' =
543           List.map
544            (function (n,ty,bo) ->
545              (n,reduceaux context [] ty, reduceaux (tys@context) [] bo)
546            ) fl
547          in
548          C.CoFix (i, fl')
549        in
550          if l = [] then t' else C.Appl (t'::l)
551  in
552   reduceaux context []
553 ;;