]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_proof_checking/cicReduction.ml
532d0dc1ec374f20a0b135cbedc8495e4767f827
[helm.git] / helm / software / components / cic_proof_checking / cicReduction.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 (* $Id$ *)
27
28 (* TODO unify exceptions *)
29
30 exception WrongUriToInductiveDefinition;;
31 exception Impossible of int;;
32 exception ReferenceToConstant;;
33 exception ReferenceToVariable;;
34 exception ReferenceToCurrentProof;;
35 exception ReferenceToInductiveDefinition;;
36
37 let debug = false
38 let profile = false
39 let debug_print s = if debug then prerr_endline (Lazy.force s)
40
41 let fdebug = ref 1;;
42 let debug t env s =
43  let rec debug_aux t i =
44   let module C = Cic in
45   let module U = UriManager in
46    CicPp.ppobj (C.Variable ("DEBUG", None, t, [], [])) ^ "\n" ^ i
47  in
48   if !fdebug = 0 then
49    debug_print (lazy (s ^ "\n" ^ List.fold_right debug_aux (t::env) ""))
50 ;;
51
52 module type Strategy =
53  sig
54   type stack_term
55   type env_term
56   type ens_term
57   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
58   val to_env :
59    reduce: (config -> config) ->
60    unwind: (config -> Cic.term) ->
61    config -> env_term
62   val to_ens :
63    reduce: (config -> config) ->
64    unwind: (config -> Cic.term) ->
65    config -> ens_term
66   val from_stack : stack_term -> config
67   val from_stack_list_for_unwind :
68    unwind: (config -> Cic.term) ->
69    stack_term list -> Cic.term list
70   val from_env : env_term -> config
71   val from_env_for_unwind :
72    unwind: (config -> Cic.term) ->
73    env_term -> Cic.term
74   val from_ens : ens_term -> config
75   val from_ens_for_unwind :
76    unwind: (config -> Cic.term) ->
77    ens_term -> Cic.term
78   val stack_to_env :
79    reduce: (config -> config) ->
80    unwind: (config -> Cic.term) ->
81    stack_term -> env_term
82   val compute_to_env :
83    reduce: (config -> config) ->
84    unwind: (config -> Cic.term) ->
85    int -> env_term list -> ens_term Cic.explicit_named_substitution ->
86     Cic.term -> env_term
87   val compute_to_stack :
88    reduce: (config -> config) ->
89    unwind: (config -> Cic.term) ->
90    config -> stack_term
91  end
92 ;;
93
94 module CallByValueByNameForUnwind =
95  struct
96   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
97   and stack_term = config
98   and env_term = config * config (* cbv, cbn *)
99   and ens_term = config * config (* cbv, cbn *)
100
101   let to_env c = c,c
102   let to_ens c = c,c
103   let from_stack config = config
104   let from_stack_list_for_unwind ~unwind l = List.map unwind l
105   let from_env (c,_) = c
106   let from_ens (c,_) = c
107   let from_env_for_unwind ~unwind (_,c) = unwind c
108   let from_ens_for_unwind ~unwind (_,c) = unwind c
109   let stack_to_env ~reduce ~unwind config = reduce config, (0,[],[],unwind config,[])
110   let compute_to_env ~reduce ~unwind k e ens t = (k,e,ens,t,[]), (k,e,ens,t,[])
111   let compute_to_stack ~reduce ~unwind config = config
112  end
113 ;;
114
115 module CallByValueByNameForUnwind' =
116  struct
117   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
118   and stack_term = config lazy_t * Cic.term lazy_t (* cbv, cbn *)
119   and env_term = config lazy_t * Cic.term lazy_t (* cbv, cbn *)
120   and ens_term = config lazy_t * Cic.term lazy_t (* cbv, cbn *)
121
122   let to_env ~reduce ~unwind c = lazy (reduce c),lazy (unwind c)
123   let to_ens ~reduce ~unwind c = lazy (reduce c),lazy (unwind c)
124   let from_stack (c,_) = Lazy.force c
125   let from_stack_list_for_unwind ~unwind l = List.map (function (_,c) -> Lazy.force c) l
126   let from_env (c,_) = Lazy.force c
127   let from_ens (c,_) = Lazy.force c
128   let from_env_for_unwind ~unwind (_,c) = Lazy.force c
129   let from_ens_for_unwind ~unwind (_,c) = Lazy.force c
130   let stack_to_env ~reduce ~unwind config = config
131   let compute_to_env ~reduce ~unwind k e ens t =
132    lazy (reduce (k,e,ens,t,[])), lazy (unwind (k,e,ens,t,[]))
133   let compute_to_stack ~reduce ~unwind config = lazy (reduce config), lazy (unwind config)
134  end
135 ;;
136
137
138 (* Old Machine
139 module CallByNameStrategy =
140  struct
141   type stack_term = Cic.term
142   type env_term = Cic.term
143   type ens_term = Cic.term
144   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
145   let to_env v = v
146   let to_ens v = v
147   let from_stack ~unwind v = v
148   let from_stack_list ~unwind l = l
149   let from_env v = v
150   let from_ens v = v
151   let from_env_for_unwind ~unwind v = v
152   let from_ens_for_unwind ~unwind v = v
153   let stack_to_env ~reduce ~unwind v = v
154   let compute_to_stack ~reduce ~unwind k e ens t = unwind k e ens t
155   let compute_to_env ~reduce ~unwind k e ens t = unwind k e ens t
156  end
157 ;;
158 *)
159
160 module CallByNameStrategy =
161  struct
162   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
163   and stack_term = config
164   and env_term = config
165   and ens_term = config
166
167   let to_env c = c
168   let to_ens c = c
169   let from_stack config = config
170   let from_stack_list_for_unwind ~unwind l = List.map unwind l
171   let from_env c = c
172   let from_ens c = c
173   let from_env_for_unwind ~unwind c = unwind c
174   let from_ens_for_unwind ~unwind c = unwind c
175   let stack_to_env ~reduce ~unwind config = 0,[],[],unwind config,[]
176   let compute_to_env ~reduce ~unwind k e ens t = k,e,ens,t,[]
177   let compute_to_stack ~reduce ~unwind config = config
178  end
179 ;;
180
181 module CallByValueStrategy =
182  struct
183   type stack_term = Cic.term
184   type env_term = Cic.term
185   type ens_term = Cic.term
186   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
187   let to_env v = v
188   let to_ens v = v
189   let from_stack ~unwind v = v
190   let from_stack_list ~unwind l = l
191   let from_env v = v
192   let from_ens v = v
193   let from_env_for_unwind ~unwind v = v
194   let from_ens_for_unwind ~unwind v = v
195   let stack_to_env ~reduce ~unwind v = v
196   let compute_to_stack ~reduce ~unwind k e ens t = reduce (k,e,ens,t,[])
197   let compute_to_env ~reduce ~unwind k e ens t = reduce (k,e,ens,t,[])
198  end
199 ;;
200
201 module CallByValueStrategyByNameOnConstants =
202  struct
203   type stack_term = Cic.term
204   type env_term = Cic.term
205   type ens_term = Cic.term
206   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
207   let to_env v = v
208   let to_ens v = v
209   let from_stack ~unwind v = v
210   let from_stack_list ~unwind l = l
211   let from_env v = v
212   let from_ens v = v
213   let from_env_for_unwind ~unwind v = v
214   let from_ens_for_unwind ~unwind v = v
215   let stack_to_env ~reduce ~unwind v = v
216   let compute_to_stack ~reduce ~unwind k e ens =
217    function
218       Cic.Const _ as t -> unwind k e ens t    
219     | t -> reduce (k,e,ens,t,[])
220   let compute_to_env ~reduce ~unwind k e ens =
221    function
222       Cic.Const _ as t -> unwind k e ens t    
223     | t -> reduce (k,e,ens,t,[])
224  end
225 ;;
226
227 module LazyCallByValueStrategy =
228  struct
229   type stack_term = Cic.term lazy_t
230   type env_term = Cic.term lazy_t
231   type ens_term = Cic.term lazy_t
232   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
233   let to_env v = lazy v
234   let to_ens v = lazy v
235   let from_stack ~unwind v = Lazy.force v
236   let from_stack_list ~unwind l = List.map (from_stack ~unwind) l
237   let from_env v = Lazy.force v
238   let from_ens v = Lazy.force v
239   let from_env_for_unwind ~unwind v = Lazy.force v
240   let from_ens_for_unwind ~unwind v = Lazy.force v
241   let stack_to_env ~reduce ~unwind v = v
242   let compute_to_stack ~reduce ~unwind k e ens t = lazy (reduce (k,e,ens,t,[]))
243   let compute_to_env ~reduce ~unwind k e ens t = lazy (reduce (k,e,ens,t,[]))
244  end
245 ;;
246
247 module LazyCallByValueStrategyByNameOnConstants =
248  struct
249   type stack_term = Cic.term lazy_t
250   type env_term = Cic.term lazy_t
251   type ens_term = Cic.term lazy_t
252   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
253   let to_env v = lazy v
254   let to_ens v = lazy v
255   let from_stack ~unwind v = Lazy.force v
256   let from_stack_list ~unwind l = List.map (from_stack ~unwind) l
257   let from_env v = Lazy.force v
258   let from_ens v = Lazy.force v
259   let from_env_for_unwind ~unwind v = Lazy.force v
260   let from_ens_for_unwind ~unwind v = Lazy.force v
261   let stack_to_env ~reduce ~unwind v = v
262   let compute_to_stack ~reduce ~unwind k e ens t =
263    lazy (
264     match t with
265        Cic.Const _ as t -> unwind k e ens t    
266      | t -> reduce (k,e,ens,t,[]))
267   let compute_to_env ~reduce ~unwind k e ens t =
268    lazy (
269     match t with
270        Cic.Const _ as t -> unwind k e ens t    
271      | t -> reduce (k,e,ens,t,[]))
272  end
273 ;;
274
275 module LazyCallByNameStrategy =
276  struct
277   type stack_term = Cic.term lazy_t
278   type env_term = Cic.term lazy_t
279   type ens_term = Cic.term lazy_t
280   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
281   let to_env v = lazy v
282   let to_ens v = lazy v
283   let from_stack ~unwind v = Lazy.force v
284   let from_stack_list ~unwind l = List.map (from_stack ~unwind) l
285   let from_env v = Lazy.force v
286   let from_ens v = Lazy.force v
287   let from_env_for_unwind ~unwind v = Lazy.force v
288   let from_ens_for_unwind ~unwind v = Lazy.force v
289   let stack_to_env ~reduce ~unwind v = v
290   let compute_to_stack ~reduce ~unwind k e ens t = lazy (unwind k e ens t)
291   let compute_to_env ~reduce ~unwind k e ens t = lazy (unwind k e ens t)
292  end
293 ;;
294
295 module
296  LazyCallByValueByNameOnConstantsWhenFromStack_ByNameStrategyWhenFromEnvOrEns
297 =
298  struct
299   type stack_term = reduce:bool -> Cic.term
300   type env_term = reduce:bool -> Cic.term
301   type ens_term = reduce:bool -> Cic.term
302   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
303   let to_env v =
304    let value = lazy v in
305     fun ~reduce -> Lazy.force value
306   let to_ens v =
307    let value = lazy v in
308     fun ~reduce -> Lazy.force value
309   let from_stack ~unwind v = (v ~reduce:false)
310   let from_stack_list ~unwind l = List.map (from_stack ~unwind) l
311   let from_env v = (v ~reduce:true)
312   let from_ens v = (v ~reduce:true)
313   let from_env_for_unwind ~unwind v = (v ~reduce:true)
314   let from_ens_for_unwind ~unwind v = (v ~reduce:true)
315   let stack_to_env ~reduce ~unwind v = v
316   let compute_to_stack ~reduce ~unwind k e ens t =
317    let svalue =
318      lazy (
319       match t with
320          Cic.Const _ as t -> unwind k e ens t    
321        | t -> reduce (k,e,ens,t,[])
322      ) in
323    let lvalue =
324     lazy (unwind k e ens t)
325    in
326     fun ~reduce ->
327      if reduce then Lazy.force svalue else Lazy.force lvalue
328   let compute_to_env ~reduce ~unwind k e ens t =
329    let svalue =
330      lazy (
331       match t with
332          Cic.Const _ as t -> unwind k e ens t    
333        | t -> reduce (k,e,ens,t,[])
334      ) in
335    let lvalue =
336     lazy (unwind k e ens t)
337    in
338     fun ~reduce ->
339      if reduce then Lazy.force svalue else Lazy.force lvalue
340  end
341 ;;
342
343 module ClosuresOnStackByValueFromEnvOrEnsStrategy =
344  struct
345   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
346   and stack_term = config
347   and env_term = config
348   and ens_term = config
349
350   let to_env config = config
351   let to_ens config = config
352   let from_stack config = config
353   let from_stack_list_for_unwind ~unwind l = List.map unwind l
354   let from_env v = v
355   let from_ens v = v
356   let from_env_for_unwind ~unwind config = unwind config
357   let from_ens_for_unwind ~unwind config = unwind config
358   let stack_to_env ~reduce ~unwind config = reduce config
359   let compute_to_env ~reduce ~unwind k e ens t = (k,e,ens,t,[])
360   let compute_to_stack ~reduce ~unwind config = config
361  end
362 ;;
363
364 module ClosuresOnStackByValueFromEnvOrEnsByNameOnConstantsStrategy =
365  struct
366   type stack_term =
367    int * Cic.term list * Cic.term Cic.explicit_named_substitution * Cic.term
368   type env_term = Cic.term
369   type ens_term = Cic.term
370   type config = int * env_term list * ens_term Cic.explicit_named_substitution * Cic.term * stack_term list
371   let to_env v = v
372   let to_ens v = v
373   let from_stack ~unwind (k,e,ens,t) = unwind k e ens t
374   let from_stack_list ~unwind l = List.map (from_stack ~unwind) l
375   let from_env v = v
376   let from_ens v = v
377   let from_env_for_unwind ~unwind v = v
378   let from_ens_for_unwind ~unwind v = v
379   let stack_to_env ~reduce ~unwind (k,e,ens,t) =
380    match t with
381       Cic.Const _ as t -> unwind k e ens t    
382     | t -> reduce (k,e,ens,t,[])
383   let compute_to_env ~reduce ~unwind k e ens t =
384    unwind k e ens t
385   let compute_to_stack ~reduce ~unwind k e ens t = (k,e,ens,t)
386  end
387 ;;
388
389 module Reduction(RS : Strategy) =
390  struct
391   type env = RS.env_term list
392   type ens = RS.ens_term Cic.explicit_named_substitution
393   type stack = RS.stack_term list
394   type config = int * env * ens * Cic.term * stack
395
396   (* k is the length of the environment e *)
397   (* m is the current depth inside the term *)
398   let rec unwind' m k e ens t = 
399    let module C = Cic in
400    let module S = CicSubstitution in
401     if k = 0 && ens = [] then
402      t
403     else 
404      let rec unwind_aux m =
405       function
406          C.Rel n as t ->
407           if n <= m then t else
408            let d =
409             try
410              Some (RS.from_env_for_unwind ~unwind (List.nth e (n-m-1)))
411             with Failure _ -> None
412            in
413             (match d with 
414                 Some t' ->
415                  if m = 0 then t' else S.lift m t'
416               | None -> C.Rel (n-k)
417             )
418        | C.Var (uri,exp_named_subst) ->
419 (*
420 debug_print (lazy ("%%%%%UWVAR " ^ String.concat " ; " (List.map (function (uri,t) -> UriManager.string_of_uri uri ^ " := " ^ CicPp.ppterm t) ens))) ;
421 *)
422          if List.exists (function (uri',_) -> UriManager.eq uri' uri) ens then
423           CicSubstitution.lift m (RS.from_ens_for_unwind ~unwind (List.assq uri ens))
424          else
425           let params =
426             let o,_ = 
427               CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
428             in
429            (match o with
430                C.Constant _ -> raise ReferenceToConstant
431              | C.Variable (_,_,_,params,_) -> params
432              | C.CurrentProof _ -> raise ReferenceToCurrentProof
433              | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
434            )
435           in
436            let exp_named_subst' =
437             substaux_in_exp_named_subst params exp_named_subst m 
438            in
439             C.Var (uri,exp_named_subst')
440        | C.Meta (i,l) ->
441           let l' =
442            List.map
443             (function
444                 None -> None
445               | Some t -> Some (unwind_aux m t)
446             ) l
447           in
448            C.Meta (i, l')
449        | C.Sort _ as t -> t
450        | C.Implicit _ as t -> t
451        | C.Cast (te,ty) -> C.Cast (unwind_aux m te, unwind_aux m ty) (*CSC ???*)
452        | C.Prod (n,s,t) -> C.Prod (n, unwind_aux m s, unwind_aux (m + 1) t)
453        | C.Lambda (n,s,t) -> C.Lambda (n, unwind_aux m s, unwind_aux (m + 1) t)
454        | C.LetIn (n,s,t) -> C.LetIn (n, unwind_aux m s, unwind_aux (m + 1) t)
455        | C.Appl l -> C.Appl (List.map (unwind_aux m) l)
456        | C.Const (uri,exp_named_subst) ->
457           let params =
458             let o,_ = 
459               CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
460             in
461            (match o with
462                C.Constant (_,_,_,params,_) -> params
463              | C.Variable _ -> raise ReferenceToVariable
464              | C.CurrentProof (_,_,_,_,params,_) -> params
465              | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
466            )
467           in
468            let exp_named_subst' =
469             substaux_in_exp_named_subst params exp_named_subst m 
470            in
471             C.Const (uri,exp_named_subst')
472        | C.MutInd (uri,i,exp_named_subst) ->
473           let params =
474             let o,_ = 
475               CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
476             in
477            (match o with
478                C.Constant _ -> raise ReferenceToConstant
479              | C.Variable _ -> raise ReferenceToVariable
480              | C.CurrentProof _ -> raise ReferenceToCurrentProof
481              | C.InductiveDefinition (_,params,_,_) -> params
482            )
483           in
484            let exp_named_subst' =
485             substaux_in_exp_named_subst params exp_named_subst m 
486            in
487             C.MutInd (uri,i,exp_named_subst')
488        | C.MutConstruct (uri,i,j,exp_named_subst) ->
489           let params =
490             let o,_ = 
491               CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
492             in
493            (match o with
494                C.Constant _ -> raise ReferenceToConstant
495              | C.Variable _ -> raise ReferenceToVariable
496              | C.CurrentProof _ -> raise ReferenceToCurrentProof
497              | C.InductiveDefinition (_,params,_,_) -> params
498            )
499           in
500            let exp_named_subst' =
501             substaux_in_exp_named_subst params exp_named_subst m 
502            in
503             C.MutConstruct (uri,i,j,exp_named_subst')
504        | C.MutCase (sp,i,outt,t,pl) ->
505           C.MutCase (sp,i,unwind_aux m outt, unwind_aux m t,
506            List.map (unwind_aux m) pl)
507        | C.Fix (i,fl) ->
508           let len = List.length fl in
509           let substitutedfl =
510            List.map
511             (fun (name,i,ty,bo) ->
512               (name, i, unwind_aux m ty, unwind_aux (m+len) bo))
513              fl
514           in
515            C.Fix (i, substitutedfl)
516        | C.CoFix (i,fl) ->
517           let len = List.length fl in
518           let substitutedfl =
519            List.map
520             (fun (name,ty,bo) -> (name, unwind_aux m ty, unwind_aux (m+len) bo))
521              fl
522           in
523            C.CoFix (i, substitutedfl)
524      and substaux_in_exp_named_subst params exp_named_subst' m  =
525   (*CSC: Idea di Andrea di ordinare compatibilmente con l'ordine dei params
526       let ens' =
527        List.map (function (uri,t) -> uri, unwind_aux m t) exp_named_subst' @
528   (*CSC: qui liftiamo tutti gli ens anche se magari me ne servono la meta'!!! *)
529         List.map (function (uri,t) -> uri, CicSubstitution.lift m t) ens
530       in
531       let rec filter_and_lift =
532        function
533           [] -> []
534         | uri::tl ->
535            let r = filter_and_lift tl in
536             (try
537               (uri,(List.assq uri ens'))::r
538              with
539               Not_found -> r
540             )
541       in
542        filter_and_lift params
543   *)
544   
545   (*CSC: invece di concatenare sarebbe meglio rispettare l'ordine dei params *)
546   (*CSC: e' vero???? una veloce prova non sembra confermare la teoria        *)
547   
548   (*CSC: codice copiato e modificato dalla cicSubstitution.subst_vars *)
549   (*CSC: codice altamente inefficiente *)
550       let rec filter_and_lift already_instantiated =
551        function
552           [] -> []
553         | (uri,t)::tl when
554             List.for_all
555              (function (uri',_)-> not (UriManager.eq uri uri')) exp_named_subst'
556             &&
557              not (List.mem uri already_instantiated)
558             &&
559              List.mem uri params
560            ->
561             (uri,CicSubstitution.lift m (RS.from_ens_for_unwind ~unwind t)) ::
562              (filter_and_lift (uri::already_instantiated) tl)
563         | _::tl -> filter_and_lift already_instantiated tl
564 (*
565         | (uri,_)::tl ->
566 debug_print (lazy ("---- SKIPPO " ^ UriManager.string_of_uri uri)) ;
567 if List.for_all (function (uri',_) -> not (UriManager.eq uri uri'))
568 exp_named_subst' then debug_print (lazy "---- OK1") ;
569 debug_print (lazy ("++++ uri " ^ UriManager.string_of_uri uri ^ " not in " ^ String.concat " ; " (List.map UriManager.string_of_uri params))) ;
570 if List.mem uri params then debug_print (lazy "---- OK2") ;
571         filter_and_lift tl
572 *)
573       in
574        List.map (function (uri,t) -> uri, unwind_aux m t) exp_named_subst' @
575         (filter_and_lift [] (List.rev ens))
576      in
577       unwind_aux m t          
578   
579   and unwind (k,e,ens,t,s) =
580    let t' = unwind' 0 k e ens t in
581     if s = [] then t' else Cic.Appl (t'::(RS.from_stack_list_for_unwind ~unwind s))
582   ;;
583
584 (*
585   let unwind =
586    let profiler_unwind = HExtlib.profile ~enable:profile "are_convertible.unwind" in
587     fun k e ens t ->
588      profiler_unwind.HExtlib.profile (unwind k e ens) t
589   ;;
590 *)
591   
592   let reduce ~delta ?(subst = []) context : config -> config = 
593    let module C = Cic in
594    let module S = CicSubstitution in 
595    let rec reduce =
596     function
597        (k, e, _, C.Rel n, s) as config ->
598         let config' =
599          if not delta then None
600          else
601           try
602            Some (RS.from_env (List.nth e (n-1)))
603           with
604            Failure _ ->
605             try
606              begin
607               match List.nth context (n - 1 - k) with
608                  None -> assert false
609                | Some (_,C.Decl _) -> None
610                | Some (_,C.Def (x,_)) -> Some (0,[],[],S.lift (n - k) x,[])
611              end
612             with
613              Failure _ -> None
614         in
615          (match config' with 
616              Some (k',e',ens',t',s') -> reduce (k',e',ens',t',s'@s)
617            | None -> config)
618      | (k, e, ens, C.Var (uri,exp_named_subst), s) as config -> 
619          if List.exists (function (uri',_) -> UriManager.eq uri' uri) ens then
620           let (k',e',ens',t',s') = RS.from_ens (List.assq uri ens) in
621            reduce (k',e',ens',t',s'@s)
622          else
623           ( let o,_ = 
624               CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
625             in
626             match o with
627               C.Constant _ -> raise ReferenceToConstant
628             | C.CurrentProof _ -> raise ReferenceToCurrentProof
629             | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
630             | C.Variable (_,None,_,_,_) -> config
631             | C.Variable (_,Some body,_,_,_) ->
632                let ens' = push_exp_named_subst k e ens exp_named_subst in
633                 reduce (0, [], ens', body, s)
634           )
635      | (k, e, ens, C.Meta (n,l), s) as config ->
636         (try 
637            let (_, term,_) = CicUtil.lookup_subst n subst in
638            reduce (k, e, ens,CicSubstitution.subst_meta l term,s)
639          with  CicUtil.Subst_not_found _ -> config)
640      | (_, _, _, C.Sort _, _)
641      | (_, _, _, C.Implicit _, _) as config -> config
642      | (k, e, ens, C.Cast (te,ty), s) ->
643         reduce (k, e, ens, te, s)
644      | (_, _, _, C.Prod _, _) as config -> config
645      | (_, _, _, C.Lambda _, []) as config -> config
646      | (k, e, ens, C.Lambda (_,_,t), p::s) ->
647          reduce (k+1, (RS.stack_to_env ~reduce ~unwind p)::e, ens, t,s)
648      | (k, e, ens, C.LetIn (_,m,t), s) ->
649         let m' = RS.compute_to_env ~reduce ~unwind k e ens m in
650          reduce (k+1, m'::e, ens, t, s)
651      | (_, _, _, C.Appl [], _) -> assert false
652      | (k, e, ens, C.Appl (he::tl), s) ->
653         let tl' =
654          List.map
655           (function t -> RS.compute_to_stack ~reduce ~unwind (k,e,ens,t,[])) tl
656         in
657          reduce (k, e, ens, he, (List.append tl') s)
658      | (_, _, _, C.Const _, _) as config when delta=false-> config
659      | (k, e, ens, C.Const (uri,exp_named_subst), s) as config ->
660         (let o,_ = 
661            CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
662          in
663           match o with
664             C.Constant (_,Some body,_,_,_) ->
665              let ens' = push_exp_named_subst k e ens exp_named_subst in
666               (* constants are closed *)
667               reduce (0, [], ens', body, s) 
668           | C.Constant (_,None,_,_,_) -> config
669           | C.Variable _ -> raise ReferenceToVariable
670           | C.CurrentProof (_,_,body,_,_,_) ->
671              let ens' = push_exp_named_subst k e ens exp_named_subst in
672               (* constants are closed *)
673               reduce (0, [], ens', body, s)
674           | C.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
675         )
676      | (_, _, _, C.MutInd _, _)
677      | (_, _, _, C.MutConstruct _, _) as config -> config 
678      | (k, e, ens, C.MutCase (mutind,i,outty,term,pl),s) as config ->
679         let decofix =
680          function
681             (k, e, ens, C.CoFix (i,fl), s) ->
682              let (_,_,body) = List.nth fl i in
683               let body' =
684                let counter = ref (List.length fl) in
685                 List.fold_right
686                  (fun _ -> decr counter ; S.subst (C.CoFix (!counter,fl)))
687                  fl
688                  body
689               in
690                reduce (k,e,ens,body',s)
691           | config -> config
692         in
693          (match decofix (reduce (k,e,ens,term,[])) with
694              (k', e', ens', C.MutConstruct (_,_,j,_), []) ->
695               reduce (k, e, ens, (List.nth pl (j-1)), s)
696            | (k', e', ens', C.MutConstruct (_,_,j,_), s') ->
697               let r =
698                 let o,_ = 
699                   CicEnvironment.get_cooked_obj CicUniv.empty_ugraph mutind 
700                 in
701                   match o with
702                       C.InductiveDefinition (_,_,r,_) -> r
703                     | _ -> raise WrongUriToInductiveDefinition
704               in
705                let ts =
706                 let num_to_eat = r in
707                  let rec eat_first =
708                   function
709                      (0,l) -> l
710                    | (n,he::s) when n > 0 -> eat_first (n - 1, s)
711                    | _ -> raise (Impossible 5)
712                  in
713                   eat_first (num_to_eat,s')
714                in
715                 reduce (k, e, ens, (List.nth pl (j-1)), ts@s)
716            | (_, _, _, C.Cast _, _)
717            | (_, _, _, C.Implicit _, _) ->
718               raise (Impossible 2) (* we don't trust our whd ;-) *)
719            | config' ->
720               (*CSC: here I am unwinding the configuration and for sure I
721                 will do it twice; to avoid this unwinding I should push the
722                 "match [] with _" continuation on the stack;
723                 another possibility is to just return the original configuration,
724                 partially undoing the weak-head computation *)
725               (*this code is uncorrect since term' lives in e' <> e
726               let term' = unwind config' in
727                (k, e, ens, C.MutCase (mutind,i,outty,term',pl),s)
728               *)
729               config)
730      | (k, e, ens, C.Fix (i,fl), s) as config ->
731         let (_,recindex,_,body) = List.nth fl i in
732          let recparam =
733           try
734            Some (RS.from_stack (List.nth s recindex))
735           with
736            Failure _ -> None
737          in
738           (match recparam with
739               Some recparam ->
740                (match reduce recparam with
741                    (_,_,_,C.MutConstruct _,_) as config ->
742                     let leng = List.length fl in
743                     let new_env =
744                      let counter = ref 0 in
745                      let rec build_env e' =
746                       if !counter = leng then e'
747                       else
748                        (incr counter ;
749                         build_env
750                          ((RS.to_env ~reduce ~unwind (k,e,ens,C.Fix (!counter -1, fl),[]))::e'))
751                      in
752                       build_env e
753                     in
754                     let rec replace i s t =
755                      match i,s with
756                         0,_::tl -> t::tl
757                       | n,he::tl -> he::(replace (n - 1) tl t)
758                       | _,_ -> assert false in
759                     let new_s =
760                      replace recindex s (RS.compute_to_stack ~reduce ~unwind config)
761                     in
762                      reduce (k+leng, new_env, ens, body, new_s)
763                  | _ -> config)
764             | None -> config
765           )
766      | (_,_,_,C.CoFix _,_) as config -> config
767    and push_exp_named_subst k e ens =
768     function
769        [] -> ens
770      | (uri,t)::tl ->
771          push_exp_named_subst k e ((uri,RS.to_ens ~reduce ~unwind (k,e,ens,t,[]))::ens) tl
772    in
773     reduce
774   ;;
775
776   let whd ?(delta=true) ?(subst=[]) context t = 
777    unwind (reduce ~delta ~subst context (0, [], [], t, []))
778   ;;
779
780  end
781 ;;
782
783
784 (* ROTTO = rompe l'unificazione poiche' riduce gli argomenti di un'applicazione
785            senza ridurre la testa
786 module R = Reduction CallByNameStrategy;; OK 56.368s
787 module R = Reduction CallByValueStrategy;; ROTTO
788 module R = Reduction CallByValueStrategyByNameOnConstants;; ROTTO
789 module R = Reduction LazyCallByValueStrategy;; ROTTO
790 module R = Reduction LazyCallByValueStrategyByNameOnConstants;; ROTTO
791 module R = Reduction LazyCallByNameStrategy;; OK 0m56.398s
792 module R = Reduction
793  LazyCallByValueByNameOnConstantsWhenFromStack_ByNameStrategyWhenFromEnvOrEns;;
794  OK 59.058s
795 module R = Reduction ClosuresOnStackByValueFromEnvOrEnsStrategy;; OK 58.583s
796 module R = Reduction
797  ClosuresOnStackByValueFromEnvOrEnsByNameOnConstantsStrategy;; OK 58.094s
798 module R = Reduction(ClosuresOnStackByValueFromEnvOrEnsStrategy);; OK 58.127s
799 *)
800 (*module R = Reduction(CallByValueByNameForUnwind);;*)
801 module RS = CallByValueByNameForUnwind';;
802 (*module R = Reduction(CallByNameStrategy);;*)
803 (*module R = Reduction(ClosuresOnStackByValueFromEnvOrEnsStrategy);;*)
804 module R = Reduction(RS);;
805 module U = UriManager;;
806
807 let whd = R.whd
808
809 (*
810 let whd =
811  let profiler_whd = HExtlib.profile ~enable:profile "are_convertible.whd" in
812   fun ?(delta=true) ?(subst=[]) context t ->
813    profiler_whd.HExtlib.profile (whd ~delta ~subst context) t
814 *)
815
816   (* mimic ocaml (<< 3.08) "=" behaviour. Tests physical equality first then
817     * fallbacks to structural equality *)
818 let (===) x y =
819   Pervasives.compare x y = 0
820
821 (* t1, t2 must be well-typed *)
822 let are_convertible whd ?(subst=[]) ?(metasenv=[])  =
823  let heuristic = ref true in
824  let rec aux test_equality_only context t1 t2 ugraph =
825   let rec aux2 test_equality_only t1 t2 ugraph =
826
827    (* this trivial euristic cuts down the total time of about five times ;-) *)
828    (* this because most of the time t1 and t2 are "sintactically" the same   *)
829    if t1 === t2 then
830      true,ugraph
831    else
832     begin
833      let module C = Cic in
834        match (t1,t2) with
835           (C.Rel n1, C.Rel n2) -> (n1 = n2),ugraph
836         | (C.Var (uri1,exp_named_subst1), C.Var (uri2,exp_named_subst2)) ->
837             if U.eq uri1 uri2 then
838              (try
839                List.fold_right2
840                 (fun (uri1,x) (uri2,y) (b,ugraph) ->
841                   let b',ugraph' = aux test_equality_only context x y ugraph in
842                   (U.eq uri1 uri2 && b' && b),ugraph'
843                 ) exp_named_subst1 exp_named_subst2 (true,ugraph) 
844               with
845                Invalid_argument _ -> false,ugraph
846              )
847             else
848               false,ugraph
849         | (C.Meta (n1,l1), C.Meta (n2,l2)) ->
850             if n1 = n2 then
851               let b2, ugraph1 = 
852                 let l1 = CicUtil.clean_up_local_context subst metasenv n1 l1 in
853                 let l2 = CicUtil.clean_up_local_context subst metasenv n2 l2 in
854                   List.fold_left2
855                     (fun (b,ugraph) t1 t2 ->
856                        if b then 
857                          match t1,t2 with
858                              None,_
859                            | _,None  -> true,ugraph
860                            | Some t1',Some t2' -> 
861                                aux test_equality_only context t1' t2' ugraph
862                        else
863                          false,ugraph
864                     ) (true,ugraph) l1 l2
865               in
866                 if b2 then true,ugraph1 else false,ugraph 
867             else
868               false,ugraph
869         | C.Meta (n1,l1), _ ->
870            (try 
871               let _,term,_ = CicUtil.lookup_subst n1 subst in
872               let term' = CicSubstitution.subst_meta l1 term in
873 (*
874 prerr_endline ("%?: " ^ CicPp.ppterm t1 ^ " <==> " ^ CicPp.ppterm t2);
875 prerr_endline ("%%%%%%: " ^ CicPp.ppterm term' ^ " <==> " ^ CicPp.ppterm t2);
876 *)
877                aux test_equality_only context term' t2 ugraph
878             with  CicUtil.Subst_not_found _ -> false,ugraph)
879         | _, C.Meta (n2,l2) ->
880            (try 
881               let _,term,_ = CicUtil.lookup_subst n2 subst in
882               let term' = CicSubstitution.subst_meta l2 term in
883 (*
884 prerr_endline ("%?: " ^ CicPp.ppterm t1 ^ " <==> " ^ CicPp.ppterm t2);
885 prerr_endline ("%%%%%%: " ^ CicPp.ppterm term' ^ " <==> " ^ CicPp.ppterm t1);
886 *)
887                aux test_equality_only context t1 term' ugraph
888             with  CicUtil.Subst_not_found _ -> false,ugraph)
889           (* TASSI: CONSTRAINTS *)
890         | (C.Sort (C.Type t1), C.Sort (C.Type t2)) when test_equality_only ->
891             (try
892               true,(CicUniv.add_eq t2 t1 ugraph)
893              with CicUniv.UniverseInconsistency _ -> false,ugraph)
894           (* TASSI: CONSTRAINTS *)
895         | (C.Sort (C.Type t1), C.Sort (C.Type t2)) ->
896             (try
897               true,(CicUniv.add_ge t2 t1 ugraph)
898              with CicUniv.UniverseInconsistency _ -> false,ugraph)
899           (* TASSI: CONSTRAINTS *)
900         | (C.Sort s1, C.Sort (C.Type _)) -> (not test_equality_only),ugraph
901           (* TASSI: CONSTRAINTS *)
902         | (C.Sort s1, C.Sort s2) -> (s1 = s2),ugraph
903         | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
904             let b',ugraph' = aux true context s1 s2 ugraph in
905             if b' then 
906               aux test_equality_only ((Some (name1, (C.Decl s1)))::context) 
907                 t1 t2 ugraph'
908             else
909               false,ugraph
910         | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) ->
911            let b',ugraph' = aux test_equality_only context s1 s2 ugraph in
912            if b' then
913              aux test_equality_only ((Some (name1, (C.Decl s1)))::context) 
914                t1 t2 ugraph'
915            else
916              false,ugraph
917         | (C.LetIn (name1,s1,t1), C.LetIn(_,s2,t2)) ->
918            let b',ugraph' = aux test_equality_only context s1 s2 ugraph in
919            if b' then
920             aux test_equality_only
921              ((Some (name1, (C.Def (s1,None))))::context) t1 t2 ugraph'
922            else
923              false,ugraph
924         | (C.Appl l1, C.Appl l2) ->
925            (try
926              List.fold_right2
927                (fun  x y (b,ugraph) -> 
928                  if b then
929                    aux test_equality_only context x y ugraph
930                  else
931                    false,ugraph) l1 l2 (true,ugraph)
932             with
933              Invalid_argument _ -> false,ugraph
934            )
935         | (C.Const (uri1,exp_named_subst1), C.Const (uri2,exp_named_subst2)) ->
936             let b' = U.eq uri1 uri2 in
937             if b' then
938              (try
939                List.fold_right2
940                 (fun (uri1,x) (uri2,y) (b,ugraph) ->
941                   if b && U.eq uri1 uri2 then
942                     aux test_equality_only context x y ugraph 
943                   else
944                     false,ugraph
945                 ) exp_named_subst1 exp_named_subst2 (true,ugraph)
946               with
947                Invalid_argument _ -> false,ugraph
948              )
949             else
950               false,ugraph
951         | (C.MutInd (uri1,i1,exp_named_subst1),
952            C.MutInd (uri2,i2,exp_named_subst2)
953           ) ->
954             let b' = U.eq uri1 uri2 && i1 = i2 in
955             if b' then
956              (try
957                List.fold_right2
958                 (fun (uri1,x) (uri2,y) (b,ugraph) ->
959                   if b && U.eq uri1 uri2 then
960                     aux test_equality_only context x y ugraph
961                   else
962                    false,ugraph
963                 ) exp_named_subst1 exp_named_subst2 (true,ugraph)
964               with
965                Invalid_argument _ -> false,ugraph
966              )
967             else 
968               false,ugraph
969         | (C.MutConstruct (uri1,i1,j1,exp_named_subst1),
970            C.MutConstruct (uri2,i2,j2,exp_named_subst2)
971           ) ->
972             let b' = U.eq uri1 uri2 && i1 = i2 && j1 = j2 in
973             if b' then
974              (try
975                List.fold_right2
976                 (fun (uri1,x) (uri2,y) (b,ugraph) ->
977                   if b && U.eq uri1 uri2 then
978                     aux test_equality_only context x y ugraph
979                   else
980                     false,ugraph
981                 ) exp_named_subst1 exp_named_subst2 (true,ugraph)
982               with
983                Invalid_argument _ -> false,ugraph
984              )
985             else
986               false,ugraph
987         | (C.MutCase (uri1,i1,outtype1,term1,pl1),
988            C.MutCase (uri2,i2,outtype2,term2,pl2)) -> 
989             let b' = U.eq uri1 uri2 && i1 = i2 in
990             if b' then
991              let b'',ugraph''=aux test_equality_only context 
992                  outtype1 outtype2 ugraph in
993              if b'' then 
994                let b''',ugraph'''= aux test_equality_only context 
995                    term1 term2 ugraph'' in
996                List.fold_right2
997                  (fun x y (b,ugraph) -> 
998                    if b then
999                      aux test_equality_only context x y ugraph 
1000                    else 
1001                      false,ugraph)
1002                  pl1 pl2 (b''',ugraph''')
1003              else
1004                false,ugraph
1005             else
1006               false,ugraph
1007         | (C.Fix (i1,fl1), C.Fix (i2,fl2)) ->
1008             let tys,_ =
1009               List.fold_left
1010                 (fun (types,len) (n,_,ty,_) ->
1011                    (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1012                     len+1)
1013                 ) ([],0) fl1
1014             in
1015             if i1 = i2 then
1016              List.fold_right2
1017               (fun (_,recindex1,ty1,bo1) (_,recindex2,ty2,bo2) (b,ugraph) ->
1018                 if b && recindex1 = recindex2 then
1019                   let b',ugraph' = aux test_equality_only context ty1 ty2 
1020                       ugraph in
1021                   if b' then
1022                     aux test_equality_only (tys@context) bo1 bo2 ugraph'
1023                   else
1024                     false,ugraph
1025                 else
1026                   false,ugraph)
1027              fl1 fl2 (true,ugraph)
1028             else
1029               false,ugraph
1030         | (C.CoFix (i1,fl1), C.CoFix (i2,fl2)) ->
1031             let tys,_ =
1032               List.fold_left
1033                 (fun (types,len) (n,ty,_) ->
1034                    (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1035                     len+1)
1036                 ) ([],0) fl1
1037             in
1038             if i1 = i2 then
1039               List.fold_right2
1040               (fun (_,ty1,bo1) (_,ty2,bo2) (b,ugraph) ->
1041                 if b then
1042                   let b',ugraph' = aux test_equality_only context ty1 ty2 
1043                       ugraph in
1044                   if b' then
1045                     aux test_equality_only (tys@context) bo1 bo2 ugraph'
1046                   else
1047                     false,ugraph
1048                 else
1049                   false,ugraph)
1050              fl1 fl2 (true,ugraph)
1051             else
1052               false,ugraph
1053         | C.Cast (bo,_),t -> aux2 test_equality_only bo t ugraph
1054         | t,C.Cast (bo,_) -> aux2 test_equality_only t bo ugraph
1055         | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
1056         | (_,_) -> false,ugraph
1057     end
1058   in
1059    let res =
1060     if !heuristic then
1061      aux2 test_equality_only t1 t2 ugraph
1062     else
1063      false,ugraph
1064    in
1065     if fst res = true then
1066      res
1067     else
1068 begin
1069 (*if !heuristic then prerr_endline ("NON FACILE: " ^ CicPp.ppterm t1 ^ " <===> " ^ CicPp.ppterm t2);*)
1070    (* heuristic := false; *)
1071    debug t1 [t2] "PREWHD";
1072 (*prerr_endline ("PREWHD: " ^ CicPp.ppterm t1 ^ " <===> " ^ CicPp.ppterm t2);*)
1073 (*
1074 prerr_endline ("PREWHD: " ^ CicPp.ppterm t1 ^ " <===> " ^ CicPp.ppterm t2);
1075    let t1' = whd ?delta:(Some true) ?subst:(Some subst) context t1 in
1076    let t2' = whd ?delta:(Some true) ?subst:(Some subst) context t2 in
1077     debug t1' [t2'] "POSTWHD";
1078 *)
1079 let rec convert_machines ugraph =
1080  function
1081     [] -> true,ugraph
1082   | ((k1,env1,ens1,h1,s1),(k2,env2,ens2,h2,s2))::tl ->
1083      let (b,ugraph) as res =
1084       aux2 test_equality_only
1085        (R.unwind (k1,env1,ens1,h1,[])) (R.unwind (k2,env2,ens2,h2,[])) ugraph
1086      in
1087       if b then
1088        let problems =
1089         try
1090          Some
1091           (List.combine
1092             (List.map
1093               (fun si-> R.reduce ~delta:false ~subst context(RS.from_stack si))
1094               s1)
1095             (List.map
1096               (fun si-> R.reduce ~delta:false ~subst context(RS.from_stack si))
1097               s2)
1098           @ tl)
1099         with
1100          Invalid_argument _ -> None
1101        in
1102         match problems with
1103            None -> false,ugraph
1104          | Some problems -> convert_machines ugraph problems
1105       else
1106        res
1107 in
1108  convert_machines ugraph
1109   [R.reduce ~delta:true ~subst context (0,[],[],t1,[]),
1110    R.reduce ~delta:true ~subst context (0,[],[],t2,[])]
1111 (*prerr_endline ("POSTWH: " ^ CicPp.ppterm t1' ^ " <===> " ^ CicPp.ppterm t2');*)
1112 (*
1113     aux2 test_equality_only t1' t2' ugraph
1114 *)
1115 end
1116  in
1117   aux false (*c t1 t2 ugraph *)
1118 ;;
1119
1120 (* DEBUGGING ONLY
1121 let whd ?(delta=true) ?(subst=[]) context t = 
1122  let res = whd ~delta ~subst context t in
1123  let rescsc = CicReductionNaif.whd ~delta ~subst context t in
1124   if not (fst (are_convertible CicReductionNaif.whd ~subst context res rescsc CicUniv.empty_ugraph)) then
1125    begin
1126     debug_print (lazy ("PRIMA: " ^ CicPp.ppterm t)) ;
1127     flush stderr ;
1128     debug_print (lazy ("DOPO: " ^ CicPp.ppterm res)) ;
1129     flush stderr ;
1130     debug_print (lazy ("CSC: " ^ CicPp.ppterm rescsc)) ;
1131     flush stderr ;
1132 fdebug := 0 ;
1133 let _ =  are_convertible CicReductionNaif.whd ~subst context res rescsc CicUniv.empty_ugraph in
1134     assert false ;
1135    end
1136   else 
1137    res
1138 ;;
1139 *)
1140
1141 let are_convertible = are_convertible whd
1142
1143 let whd = R.whd
1144
1145 (*
1146 let profiler_other_whd = HExtlib.profile ~enable:profile "~are_convertible.whd"
1147 let whd ?(delta=true) ?(subst=[]) context t = 
1148  let foo () =
1149   whd ~delta ~subst context t
1150  in
1151   profiler_other_whd.HExtlib.profile foo ()
1152 *)
1153
1154 let rec normalize ?(delta=true) ?(subst=[]) ctx term =
1155   let module C = Cic in
1156   let t = whd ~delta ~subst ctx term in
1157   let aux = normalize ~delta ~subst in
1158   let decl name t = Some (name, C.Decl t) in
1159   match t with
1160   | C.Rel n -> t
1161   | C.Var (uri,exp_named_subst) ->
1162       C.Var (uri, List.map (fun (n,t) -> n,aux ctx t) exp_named_subst)
1163   | C.Meta (i,l) -> 
1164       C.Meta (i,List.map (function Some t -> Some (aux ctx t) | None -> None) l)
1165   | C.Sort _ -> t
1166   | C.Implicit _ -> t
1167   | C.Cast (te,ty) -> C.Cast (aux ctx te, aux ctx ty)
1168   | C.Prod (n,s,t) -> 
1169       let s' = aux ctx s in
1170       C.Prod (n, s', aux ((decl n s')::ctx) t)
1171   | C.Lambda (n,s,t) -> 
1172       let s' = aux ctx s in
1173       C.Lambda (n, s', aux ((decl n s')::ctx) t)
1174   | C.LetIn (n,s,t) ->
1175       (* the term is already in weak head normal form *)
1176       assert false
1177   | C.Appl (h::l) -> C.Appl (h::(List.map (aux ctx) l))
1178   | C.Appl [] -> assert false
1179   | C.Const (uri,exp_named_subst) ->
1180       C.Const (uri, List.map (fun (n,t) -> n,aux ctx t) exp_named_subst)
1181   | C.MutInd (uri,typeno,exp_named_subst) ->
1182       C.MutInd (uri,typeno, List.map (fun (n,t) -> n,aux ctx t) exp_named_subst)
1183   | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
1184       C.MutConstruct (uri, typeno, consno, 
1185         List.map (fun (n,t) -> n,aux ctx t) exp_named_subst)
1186   | C.MutCase (sp,i,outt,t,pl) ->
1187       C.MutCase (sp,i, aux ctx outt, aux ctx t, List.map (aux ctx) pl)
1188 (*CSC: to be completed, I suppose *)
1189   | C.Fix _ -> t 
1190   | C.CoFix _ -> t
1191
1192 let normalize ?delta ?subst ctx term =  
1193 (*  prerr_endline ("NORMALIZE:" ^ CicPp.ppterm term); *)
1194   let t = normalize ?delta ?subst ctx term in
1195 (*  prerr_endline ("NORMALIZED:" ^ CicPp.ppterm t); *)
1196   t
1197   
1198   
1199 (* performs an head beta/cast reduction *)
1200 let rec head_beta_reduce ?(delta=false) ?(upto=(-1)) t =
1201  match upto with
1202     0 -> t
1203   | n ->
1204     match t with
1205        (Cic.Appl (Cic.Lambda (_,_,t)::he'::tl')) ->
1206          let he'' = CicSubstitution.subst he' t in
1207           if tl' = [] then
1208            he''
1209           else
1210            let he''' =
1211             match he'' with
1212                Cic.Appl l -> Cic.Appl (l@tl')
1213              | _ -> Cic.Appl (he''::tl')
1214            in
1215             head_beta_reduce ~delta ~upto:(upto - 1) he'''
1216      | Cic.Cast (te,_) -> head_beta_reduce ~delta ~upto te
1217      | Cic.Appl (Cic.Const (uri,ens)::tl) as t when delta=true ->
1218         let bo =
1219          match fst (CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri) with
1220             Cic.Constant (_,bo,_,_,_) -> bo
1221           | Cic.Variable _ -> raise ReferenceToVariable
1222           | Cic.CurrentProof (_,_,bo,_,_,_) -> Some bo
1223           | Cic.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
1224         in
1225          (match bo with
1226              None -> t
1227            | Some bo ->
1228               head_beta_reduce ~upto
1229                ~delta (Cic.Appl ((CicSubstitution.subst_vars ens bo)::tl)))
1230      | Cic.Const (uri,ens) as t when delta=true ->
1231         let bo =
1232          match fst (CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri) with
1233             Cic.Constant (_,bo,_,_,_) -> bo
1234           | Cic.Variable _ -> raise ReferenceToVariable
1235           | Cic.CurrentProof (_,_,bo,_,_,_) -> Some bo
1236           | Cic.InductiveDefinition _ -> raise ReferenceToInductiveDefinition
1237         in
1238          (match bo with
1239              None -> t
1240            | Some bo ->
1241               head_beta_reduce ~delta ~upto (CicSubstitution.subst_vars ens bo))
1242      | t -> t
1243
1244 (*
1245 let are_convertible ?subst ?metasenv context t1 t2 ugraph =
1246  let before = Unix.gettimeofday () in
1247  let res = are_convertible ?subst ?metasenv context t1 t2 ugraph in
1248  let after = Unix.gettimeofday () in
1249  let diff = after -. before in
1250   if diff > 0.1 then
1251    begin
1252     let nc = List.map (function None -> None | Some (n,_) -> Some n) context in
1253      prerr_endline
1254       ("\n#(" ^ string_of_float diff ^ "):\n" ^ CicPp.pp t1 nc ^ "\n<=>\n" ^ CicPp.pp t2 nc);
1255    end;
1256   res
1257 *)