]> matita.cs.unibo.it Git - helm.git/blob - components/cic_unification/cicRefine.ml
7f5ab6883c975609e1ec6336f5fdb98198a30ba5
[helm.git] / components / cic_unification / cicRefine.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 open Printf
29
30 exception RefineFailure of string Lazy.t;;
31 exception Uncertain of string Lazy.t;;
32 exception AssertFailure of string Lazy.t;;
33
34 (* for internal use only; the integer is the number of surplus arguments *)
35 exception MoreArgsThanExpected of int * exn;;
36
37 let insert_coercions = ref true
38 let pack_coercions = ref true
39
40 let debug = false;;
41
42 let debug_print = 
43   if debug then (fun x -> prerr_endline (Lazy.force x)) else (fun _ -> ());;
44
45 let profiler_eat_prods2 = HExtlib.profile "CicRefine.fo_unif_eat_prods2"
46
47 let fo_unif_subst_eat_prods2 subst context metasenv t1 t2 ugraph =
48   try
49 let foo () =
50     CicUnification.fo_unif_subst subst context metasenv t1 t2 ugraph
51 in profiler_eat_prods2.HExtlib.profile foo ()
52   with
53       (CicUnification.UnificationFailure msg) -> raise (RefineFailure msg)
54     | (CicUnification.Uncertain msg) -> raise (Uncertain msg)
55 ;;
56
57 let profiler_eat_prods = HExtlib.profile "CicRefine.fo_unif_eat_prods"
58
59 let fo_unif_subst_eat_prods subst context metasenv t1 t2 ugraph =
60   try
61 let foo () =
62     CicUnification.fo_unif_subst subst context metasenv t1 t2 ugraph
63 in profiler_eat_prods.HExtlib.profile foo ()
64   with
65       (CicUnification.UnificationFailure msg) -> raise (RefineFailure msg)
66     | (CicUnification.Uncertain msg) -> raise (Uncertain msg)
67 ;;
68
69 let profiler = HExtlib.profile "CicRefine.fo_unif"
70
71 let fo_unif_subst subst context metasenv t1 t2 ugraph =
72   try
73 let foo () =
74     CicUnification.fo_unif_subst subst context metasenv t1 t2 ugraph
75 in profiler.HExtlib.profile foo ()
76   with
77       (CicUnification.UnificationFailure msg) -> raise (RefineFailure msg)
78     | (CicUnification.Uncertain msg) -> raise (Uncertain msg)
79 ;;
80
81 let enrich localization_tbl t ?(f = fun msg -> msg) exn =
82  let exn' =
83   match exn with
84      RefineFailure msg -> RefineFailure (f msg)
85    | Uncertain msg -> Uncertain (f msg)
86    | AssertFailure msg -> prerr_endline (Lazy.force msg); AssertFailure (f msg)
87    | Sys.Break -> raise exn
88    | _ -> prerr_endline (Printexc.to_string exn); assert false 
89  in
90  let loc =
91   try
92    Cic.CicHash.find localization_tbl t
93   with Not_found ->
94    prerr_endline ("!!! NOT LOCALIZED: " ^ CicPp.ppterm t);
95    raise exn'
96  in
97   raise (HExtlib.Localized (loc,exn'))
98
99 let relocalize localization_tbl oldt newt =
100  try
101   let infos = Cic.CicHash.find localization_tbl oldt in
102    Cic.CicHash.remove localization_tbl oldt;
103    Cic.CicHash.add localization_tbl newt infos;
104  with
105   Not_found -> ()
106 ;;
107                        
108 let rec split l n =
109  match (l,n) with
110     (l,0) -> ([], l)
111   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
112   | (_,_) -> raise (AssertFailure (lazy "split: list too short"))
113 ;;
114
115 let exp_impl metasenv subst context =
116  function
117   | Some `Type ->
118       let (metasenv', idx) = 
119         CicMkImplicit.mk_implicit_type metasenv subst context in
120       let irl = 
121         CicMkImplicit.identity_relocation_list_for_metavariable context in
122       metasenv', Cic.Meta (idx, irl)
123   | Some `Closed ->
124       let (metasenv', idx) = CicMkImplicit.mk_implicit metasenv subst [] in
125       metasenv', Cic.Meta (idx, [])
126   | None ->
127       let (metasenv', idx) = CicMkImplicit.mk_implicit metasenv subst context in
128       let irl = 
129         CicMkImplicit.identity_relocation_list_for_metavariable context in
130       metasenv', Cic.Meta (idx, irl)
131   | _ -> assert false
132 ;;
133
134 let is_a_double_coercion t =
135   let last_of l = 
136     let rec aux acc = function
137       | x::[] -> acc,x
138       | x::tl -> aux (acc@[x]) tl
139       | [] -> assert false
140     in
141     aux [] l
142   in
143   let imp = Cic.Implicit None in
144   let dummyres = false,imp, imp,imp,imp in
145   match t with
146   | Cic.Appl (c1::tl) when CoercDb.is_a_coercion' c1 ->
147       (match last_of tl with
148       | sib1,Cic.Appl (c2::tl2) when CoercDb.is_a_coercion' c2 ->
149           let sib2,head = last_of tl2 in
150           true, c1, c2, head,Cic.Appl (c1::sib1@[Cic.Appl
151             (c2::sib2@[imp])]) 
152       | _ -> dummyres)
153   | _ -> dummyres
154
155 let more_args_than_expected localization_tbl metasenv subst he context hetype' residuals tlbody_and_type exn
156 =
157   let len = List.length tlbody_and_type in
158   let msg = 
159     lazy ("The term " ^
160       CicMetaSubst.ppterm_in_context ~metasenv subst he context ^ 
161       " (that has type "^ CicMetaSubst.ppterm_in_context ~metasenv subst hetype' context ^
162       ") is here applied to " ^ string_of_int len ^
163       " arguments but here it can handle only up to " ^
164       string_of_int (len - residuals) ^ " arguments")
165   in
166   enrich localization_tbl he ~f:(fun _-> msg) exn
167 ;; 
168
169 let mk_prod_of_metas metasenv context' subst args = 
170   let rec mk_prod metasenv context' = function
171     | [] ->
172         let (metasenv, idx) = 
173           CicMkImplicit.mk_implicit_type metasenv subst context'
174         in
175         let irl =
176           CicMkImplicit.identity_relocation_list_for_metavariable context'
177         in
178           metasenv,Cic.Meta (idx, irl)
179     | (_,argty)::tl ->
180         let (metasenv, idx) = 
181           CicMkImplicit.mk_implicit_type metasenv subst context' 
182         in
183         let irl =
184           CicMkImplicit.identity_relocation_list_for_metavariable context'
185         in
186         let meta = Cic.Meta (idx,irl) in
187         let name =
188           (* The name must be fresh for context.                 *)
189           (* Nevertheless, argty is well-typed only in context.  *)
190           (* Thus I generate a name (name_hint) in context and   *)
191           (* then I generate a name --- using the hint name_hint *)
192           (* --- that is fresh in context'.                      *)
193           let name_hint = 
194             (* Cic.Name "pippo" *)
195             FreshNamesGenerator.mk_fresh_name ~subst metasenv 
196               (* (CicMetaSubst.apply_subst_metasenv subst metasenv) *)
197               (CicMetaSubst.apply_subst_context subst context')
198               Cic.Anonymous
199               ~typ:(CicMetaSubst.apply_subst subst argty) 
200           in
201             (* [] and (Cic.Sort Cic.prop) are dummy: they will not be used *)
202             FreshNamesGenerator.mk_fresh_name ~subst
203               [] context' name_hint ~typ:(Cic.Sort Cic.Prop)
204         in
205         let metasenv,target =
206           mk_prod metasenv ((Some (name, Cic.Decl meta))::context') tl
207         in
208           metasenv,Cic.Prod (name,meta,target)
209   in
210   mk_prod metasenv context' args
211 ;;
212   
213 let rec type_of_constant uri ugraph =
214  let module C = Cic in
215  let module R = CicReduction in
216  let module U = UriManager in
217   let _ = CicTypeChecker.typecheck uri in
218   let obj,u =
219    try
220     CicEnvironment.get_cooked_obj ugraph uri
221    with Not_found -> assert false
222   in
223    match obj with
224       C.Constant (_,_,ty,_,_) -> ty,u
225     | C.CurrentProof (_,_,_,ty,_,_) -> ty,u
226     | _ ->
227        raise
228         (RefineFailure 
229           (lazy ("Unknown constant definition " ^  U.string_of_uri uri)))
230
231 and type_of_variable uri ugraph =
232   let module C = Cic in
233   let module R = CicReduction in
234   let module U = UriManager in
235   let _ = CicTypeChecker.typecheck uri in
236   let obj,u =
237    try
238     CicEnvironment.get_cooked_obj ugraph uri
239     with Not_found -> assert false
240   in
241    match obj with
242       C.Variable (_,_,ty,_,_) -> ty,u
243     | _ ->
244         raise
245          (RefineFailure
246           (lazy ("Unknown variable definition " ^ UriManager.string_of_uri uri)))
247
248 and type_of_mutual_inductive_defs uri i ugraph =
249   let module C = Cic in
250   let module R = CicReduction in
251   let module U = UriManager in
252   let _ = CicTypeChecker.typecheck uri in
253   let obj,u =
254    try
255     CicEnvironment.get_cooked_obj ugraph uri
256    with Not_found -> assert false
257   in
258    match obj with
259       C.InductiveDefinition (dl,_,_,_) ->
260         let (_,_,arity,_) = List.nth dl i in
261          arity,u
262     | _ ->
263        raise
264         (RefineFailure
265          (lazy ("Unknown mutual inductive definition " ^ U.string_of_uri uri)))
266
267 and type_of_mutual_inductive_constr uri i j ugraph =
268   let module C = Cic in
269   let module R = CicReduction in
270   let module U = UriManager in
271   let _ = CicTypeChecker.typecheck uri in
272    let obj,u =
273     try
274      CicEnvironment.get_cooked_obj ugraph uri
275     with Not_found -> assert false
276    in
277     match obj with
278         C.InductiveDefinition (dl,_,_,_) ->
279           let (_,_,_,cl) = List.nth dl i in
280           let (_,ty) = List.nth cl (j-1) in
281             ty,u
282       | _ -> 
283           raise
284                   (RefineFailure
285               (lazy 
286                 ("Unkown mutual inductive definition " ^ U.string_of_uri uri)))
287
288
289 (* type_of_aux' is just another name (with a different scope) for type_of_aux *)
290
291 (* the check_branch function checks if a branch of a case is refinable. 
292    It returns a pair (outype_instance,args), a subst and a metasenv.
293    outype_instance is the expected result of applying the case outtype 
294    to args. 
295    The problem is that outype is in general unknown, and we should
296    try to synthesize it from the above information, that is in general
297    a second order unification problem. *)
298  
299 and check_branch n context metasenv subst left_args_no actualtype term expectedtype ugraph =
300   let module C = Cic in
301     (* let module R = CicMetaSubst in *)
302   let module R = CicReduction in
303     match R.whd ~subst context expectedtype with
304         C.MutInd (_,_,_) ->
305           (n,context,actualtype, [term]), subst, metasenv, ugraph
306       | C.Appl (C.MutInd (_,_,_)::tl) ->
307           let (_,arguments) = split tl left_args_no in
308             (n,context,actualtype, arguments@[term]), subst, metasenv, ugraph 
309       | C.Prod (name,so,de) ->
310           (* we expect that the actual type of the branch has the due 
311              number of Prod *)
312           (match R.whd ~subst context actualtype with
313                C.Prod (name',so',de') ->
314                  let subst, metasenv, ugraph1 = 
315                    fo_unif_subst subst context metasenv so so' ugraph in
316                  let term' =
317                    (match CicSubstitution.lift 1 term with
318                         C.Appl l -> C.Appl (l@[C.Rel 1])
319                       | t -> C.Appl [t ; C.Rel 1]) in
320                    (* we should also check that the name variable is anonymous in
321                       the actual type de' ?? *)
322                    check_branch (n+1) 
323                      ((Some (name,(C.Decl so)))::context) 
324                        metasenv subst left_args_no de' term' de ugraph1
325              | _ -> raise (AssertFailure (lazy "Wrong number of arguments")))
326       | _ -> raise (AssertFailure (lazy "Prod or MutInd expected"))
327
328 and type_of_aux' ?(localization_tbl = Cic.CicHash.create 1) metasenv context t
329      ugraph
330 =
331   let rec type_of_aux subst metasenv context t ugraph =
332     let module C = Cic in
333     let module S = CicSubstitution in
334     let module U = UriManager in
335      let (t',_,_,_,_) as res =
336       match t with
337           (*    function *)
338           C.Rel n ->
339             (try
340                match List.nth context (n - 1) with
341                    Some (_,C.Decl ty) -> 
342                      t,S.lift n ty,subst,metasenv, ugraph
343                  | Some (_,C.Def (_,Some ty)) -> 
344                      t,S.lift n ty,subst,metasenv, ugraph
345                  | Some (_,C.Def (bo,None)) ->
346                      let ty,ugraph =
347                       (* if it is in the context it must be already well-typed*)
348                       CicTypeChecker.type_of_aux' ~subst metasenv context
349                        (S.lift n bo) ugraph 
350                      in
351                       t,ty,subst,metasenv,ugraph
352                  | None ->
353                     enrich localization_tbl t
354                      (RefineFailure (lazy "Rel to hidden hypothesis"))
355              with
356               Failure _ ->
357                enrich localization_tbl t
358                 (RefineFailure (lazy "Not a closed term")))
359         | C.Var (uri,exp_named_subst) ->
360             let exp_named_subst',subst',metasenv',ugraph1 =
361               check_exp_named_subst 
362                 subst metasenv context exp_named_subst ugraph 
363             in
364             let ty_uri,ugraph1 = type_of_variable uri ugraph in
365             let ty =
366               CicSubstitution.subst_vars exp_named_subst' ty_uri
367             in
368               C.Var (uri,exp_named_subst'),ty,subst',metasenv',ugraph1
369         | C.Meta (n,l) -> 
370             (try
371                let (canonical_context, term,ty) = 
372                  CicUtil.lookup_subst n subst 
373                in
374                let l',subst',metasenv',ugraph1 =
375                  check_metasenv_consistency n subst metasenv context
376                    canonical_context l ugraph 
377                in
378                  (* trust or check ??? *)
379                  C.Meta (n,l'),CicSubstitution.subst_meta l' ty, 
380                    subst', metasenv', ugraph1
381                    (* type_of_aux subst metasenv 
382                       context (CicSubstitution.subst_meta l term) *)
383              with CicUtil.Subst_not_found _ ->
384                let (_,canonical_context,ty) = CicUtil.lookup_meta n metasenv in
385                let l',subst',metasenv', ugraph1 =
386                  check_metasenv_consistency n subst metasenv context
387                    canonical_context l ugraph
388                in
389                  C.Meta (n,l'),CicSubstitution.subst_meta l' ty, 
390                    subst', metasenv',ugraph1)
391         | C.Sort (C.Type tno) -> 
392             let tno' = CicUniv.fresh() in 
393              (try
394                let ugraph1 = CicUniv.add_gt tno' tno ugraph in
395                  t,(C.Sort (C.Type tno')),subst,metasenv,ugraph1
396               with
397                CicUniv.UniverseInconsistency msg -> raise (RefineFailure msg))
398         | C.Sort _ -> 
399             t,C.Sort (C.Type (CicUniv.fresh())),subst,metasenv,ugraph
400         | C.Implicit infos ->
401            let metasenv',t' = exp_impl metasenv subst context infos in
402             type_of_aux subst metasenv' context t' ugraph
403         | C.Cast (te,ty) ->
404             let ty',_,subst',metasenv',ugraph1 =
405               type_of_aux subst metasenv context ty ugraph 
406             in
407             let te',inferredty,subst'',metasenv'',ugraph2 =
408               type_of_aux subst' metasenv' context te ugraph1
409             in
410             let (te', ty'), subst''',metasenv''',ugraph3 =
411               coerce_to_something true localization_tbl te' inferredty ty'
412                 subst'' metasenv'' context ugraph2
413             in
414              C.Cast (te',ty'),ty',subst''',metasenv''',ugraph3
415         | C.Prod (name,s,t) ->
416             let s',sort1,subst',metasenv',ugraph1 = 
417               type_of_aux subst metasenv context s ugraph 
418             in
419             let s',sort1,subst', metasenv',ugraph1 = 
420               coerce_to_sort localization_tbl 
421               s' sort1 subst' context metasenv' ugraph1
422             in
423             let context_for_t = ((Some (name,(C.Decl s')))::context) in
424             let t',sort2,subst'',metasenv'',ugraph2 =
425               type_of_aux subst' metasenv' 
426                 context_for_t t ugraph1
427             in
428             let t',sort2,subst'',metasenv'',ugraph2 = 
429               coerce_to_sort localization_tbl 
430               t' sort2 subst'' context_for_t metasenv'' ugraph2
431             in
432               let sop,subst''',metasenv''',ugraph3 =
433                 sort_of_prod localization_tbl subst'' metasenv'' 
434                   context (name,s') t' (sort1,sort2) ugraph2
435               in
436                 C.Prod (name,s',t'),sop,subst''',metasenv''',ugraph3
437         | C.Lambda (n,s,t) ->
438             let s',sort1,subst',metasenv',ugraph1 = 
439               type_of_aux subst metasenv context s ugraph 
440             in
441             let s',sort1,subst',metasenv',ugraph1 =
442               coerce_to_sort localization_tbl 
443               s' sort1 subst' context metasenv' ugraph1
444             in
445             let context_for_t = ((Some (n,(C.Decl s')))::context) in 
446             let t',type2,subst'',metasenv'',ugraph2 =
447               type_of_aux subst' metasenv' context_for_t t ugraph1
448             in
449               C.Lambda (n,s',t'),C.Prod (n,s',type2),
450                 subst'',metasenv'',ugraph2
451         | C.LetIn (n,s,t) ->
452             (* only to check if s is well-typed *)
453             let s',ty,subst',metasenv',ugraph1 = 
454               type_of_aux subst metasenv context s ugraph
455             in
456            let context_for_t = ((Some (n,(C.Def (s',Some ty))))::context) in
457            
458             let t',inferredty,subst'',metasenv'',ugraph2 =
459               type_of_aux subst' metasenv' 
460                 context_for_t t ugraph1
461             in
462               (* One-step LetIn reduction. 
463                * Even faster than the previous solution.
464                * Moreover the inferred type is closer to the expected one. 
465                *)
466               C.LetIn (n,s',t'),
467                CicSubstitution.subst ~avoid_beta_redexes:true s' inferredty,
468                subst'',metasenv'',ugraph2
469         | C.Appl (he::((_::_) as tl)) ->
470             let he',hetype,subst',metasenv',ugraph1 = 
471               type_of_aux subst metasenv context he ugraph 
472             in
473             let tlbody_and_type,subst'',metasenv'',ugraph2 =
474                typeof_list subst' metasenv' context ugraph1 tl
475             in
476             let coerced_he,coerced_args,applty,subst''',metasenv''',ugraph3 =
477               eat_prods true subst'' metasenv'' context 
478                 he' hetype tlbody_and_type ugraph2
479             in
480             let newappl = (C.Appl (coerced_he::coerced_args)) in
481             avoid_double_coercion 
482               context subst''' metasenv''' ugraph3 newappl applty
483         | C.Appl _ -> assert false
484         | C.Const (uri,exp_named_subst) ->
485             let exp_named_subst',subst',metasenv',ugraph1 =
486               check_exp_named_subst subst metasenv context 
487                 exp_named_subst ugraph in
488             let ty_uri,ugraph2 = type_of_constant uri ugraph1 in
489             let cty =
490               CicSubstitution.subst_vars exp_named_subst' ty_uri
491             in
492               C.Const (uri,exp_named_subst'),cty,subst',metasenv',ugraph2
493         | C.MutInd (uri,i,exp_named_subst) ->
494             let exp_named_subst',subst',metasenv',ugraph1 =
495               check_exp_named_subst subst metasenv context 
496                 exp_named_subst ugraph 
497             in
498             let ty_uri,ugraph2 = type_of_mutual_inductive_defs uri i ugraph1 in
499             let cty =
500               CicSubstitution.subst_vars exp_named_subst' ty_uri in
501               C.MutInd (uri,i,exp_named_subst'),cty,subst',metasenv',ugraph2
502         | C.MutConstruct (uri,i,j,exp_named_subst) ->
503             let exp_named_subst',subst',metasenv',ugraph1 =
504               check_exp_named_subst subst metasenv context 
505                 exp_named_subst ugraph 
506             in
507             let ty_uri,ugraph2 = 
508               type_of_mutual_inductive_constr uri i j ugraph1 
509             in
510             let cty =
511               CicSubstitution.subst_vars exp_named_subst' ty_uri 
512             in
513               C.MutConstruct (uri,i,j,exp_named_subst'),cty,subst',
514                 metasenv',ugraph2
515         | C.MutCase (uri, i, outtype, term, pl) ->
516             (* first, get the inductive type (and noparams) 
517              * in the environment  *)
518             let (_,b,arity,constructors), expl_params, no_left_params,ugraph =
519               let _ = CicTypeChecker.typecheck uri in
520               let obj,u = CicEnvironment.get_cooked_obj ugraph uri in
521               match obj with
522                   C.InductiveDefinition (l,expl_params,parsno,_) -> 
523                     List.nth l i , expl_params, parsno, u
524                 | _ ->
525                     enrich localization_tbl t
526                      (RefineFailure
527                        (lazy ("Unkown mutual inductive definition " ^ 
528                          U.string_of_uri uri)))
529            in
530            if List.length constructors <> List.length pl then
531             enrich localization_tbl t
532              (RefineFailure
533                (lazy "Wrong number of cases")) ;
534            let rec count_prod t =
535              match CicReduction.whd ~subst context t with
536                  C.Prod (_, _, t) -> 1 + (count_prod t)
537                | _ -> 0 
538            in 
539            let no_args = count_prod arity in
540              (* now, create a "generic" MutInd *)
541            let metasenv,left_args = 
542              CicMkImplicit.n_fresh_metas metasenv subst context no_left_params
543            in
544            let metasenv,right_args = 
545              let no_right_params = no_args - no_left_params in
546                if no_right_params < 0 then assert false
547                else CicMkImplicit.n_fresh_metas 
548                       metasenv subst context no_right_params 
549            in
550            let metasenv,exp_named_subst = 
551              CicMkImplicit.fresh_subst metasenv subst context expl_params in
552            let expected_type = 
553              if no_args = 0 then 
554                C.MutInd (uri,i,exp_named_subst)
555              else
556                C.Appl 
557                  (C.MutInd (uri,i,exp_named_subst)::(left_args @ right_args))
558            in
559              (* check consistency with the actual type of term *)
560            let term',actual_type,subst,metasenv,ugraph1 = 
561              type_of_aux subst metasenv context term ugraph in
562            let expected_type',_, subst, metasenv,ugraph2 =
563              type_of_aux subst metasenv context expected_type ugraph1
564            in
565            let actual_type = CicReduction.whd ~subst context actual_type in
566            let subst,metasenv,ugraph3 =
567             try
568              fo_unif_subst subst context metasenv 
569                expected_type' actual_type ugraph2
570             with
571              exn ->
572               enrich localization_tbl term' exn
573                ~f:(function _ ->
574                  lazy ("(10)The term " ^
575                   CicMetaSubst.ppterm_in_context ~metasenv subst term'
576                    context ^ " has type " ^
577                   CicMetaSubst.ppterm_in_context ~metasenv subst actual_type
578                    context ^ " but is here used with type " ^
579                   CicMetaSubst.ppterm_in_context ~metasenv subst expected_type' context))
580            in
581            let rec instantiate_prod t =
582             function
583                [] -> t
584              | he::tl ->
585                 match CicReduction.whd ~subst context t with
586                    C.Prod (_,_,t') ->
587                     instantiate_prod (CicSubstitution.subst he t') tl
588                  | _ -> assert false
589            in
590            let arity_instantiated_with_left_args =
591             instantiate_prod arity left_args in
592              (* TODO: check if the sort elimination 
593               * is allowed: [(I q1 ... qr)|B] *)
594            let (pl',_,outtypeinstances,subst,metasenv,ugraph4) =
595              List.fold_right
596                (fun p (pl,j,outtypeinstances,subst,metasenv,ugraph) ->
597                   let constructor =
598                     if left_args = [] then
599                       (C.MutConstruct (uri,i,j,exp_named_subst))
600                     else
601                       (C.Appl 
602                         (C.MutConstruct (uri,i,j,exp_named_subst)::left_args))
603                   in
604                   let p',actual_type,subst,metasenv,ugraph1 = 
605                     type_of_aux subst metasenv context p ugraph 
606                   in
607                   let constructor',expected_type, subst, metasenv,ugraph2 = 
608                     type_of_aux subst metasenv context constructor ugraph1 
609                   in
610                   let outtypeinstance,subst,metasenv,ugraph3 =
611                    try
612                     check_branch 0 context metasenv subst
613                      no_left_params actual_type constructor' expected_type
614                      ugraph2 
615                    with
616                     exn ->
617                      enrich localization_tbl constructor'
618                       ~f:(fun _ ->
619                         lazy ("(11)The term " ^
620                          CicMetaSubst.ppterm_in_context metasenv subst p'
621                           context ^ " has type " ^
622                          CicMetaSubst.ppterm_in_context metasenv subst actual_type
623                           context ^ " but is here used with type " ^
624                          CicMetaSubst.ppterm_in_context metasenv subst expected_type
625                           context)) exn
626                   in
627                     (p'::pl,j-1,
628                      outtypeinstances@[outtypeinstance],subst,metasenv,ugraph3))
629                pl ([],List.length pl,[],subst,metasenv,ugraph3)
630            in
631            
632              (* we are left to check that the outype matches his instances.
633                 The easy case is when the outype is specified, that amount
634                 to a trivial check. Otherwise, we should guess a type from
635                 its instances 
636              *)
637              
638            let outtype,outtypety, subst, metasenv,ugraph4 =
639              type_of_aux subst metasenv context outtype ugraph4 in
640            (match outtype with
641            | C.Meta (n,l) ->
642                (let candidate,ugraph5,metasenv,subst = 
643                  let exp_name_subst, metasenv = 
644                     let o,_ = 
645                       CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri 
646                     in
647                     let uris = CicUtil.params_of_obj o in
648                     List.fold_right (
649                       fun uri (acc,metasenv) -> 
650                         let metasenv',new_meta = 
651                            CicMkImplicit.mk_implicit metasenv subst context
652                         in
653                         let irl =
654                           CicMkImplicit.identity_relocation_list_for_metavariable 
655                             context
656                         in
657                         (uri, Cic.Meta(new_meta,irl))::acc, metasenv'
658                     ) uris ([],metasenv)
659                  in
660                  let ty =
661                   match left_args,right_args with
662                      [],[] -> Cic.MutInd(uri, i, exp_name_subst)
663                    | _,_ ->
664                       let rec mk_right_args =
665                        function
666                           0 -> []
667                         | n -> (Cic.Rel n)::(mk_right_args (n - 1))
668                       in
669                       let right_args_no = List.length right_args in
670                       let lifted_left_args =
671                        List.map (CicSubstitution.lift right_args_no) left_args
672                       in
673                        Cic.Appl (Cic.MutInd(uri,i,exp_name_subst)::
674                         (lifted_left_args @ mk_right_args right_args_no))
675                  in
676                  let fresh_name = 
677                    FreshNamesGenerator.mk_fresh_name ~subst metasenv 
678                      context Cic.Anonymous ~typ:ty
679                  in
680                  match outtypeinstances with
681                  | [] -> 
682                      let extended_context = 
683                       let rec add_right_args =
684                        function
685                           Cic.Prod (name,ty,t) ->
686                            Some (name,Cic.Decl ty)::(add_right_args t)
687                         | _ -> []
688                       in
689                        (Some (fresh_name,Cic.Decl ty))::
690                        (List.rev
691                         (add_right_args arity_instantiated_with_left_args))@
692                        context
693                      in
694                      let metasenv,new_meta = 
695                        CicMkImplicit.mk_implicit metasenv subst extended_context
696                      in
697                        let irl =
698                        CicMkImplicit.identity_relocation_list_for_metavariable 
699                          extended_context
700                      in
701                      let rec add_lambdas b =
702                       function
703                          Cic.Prod (name,ty,t) ->
704                           Cic.Lambda (name,ty,(add_lambdas b t))
705                        | _ -> Cic.Lambda (fresh_name, ty, b)
706                      in
707                      let candidate = 
708                       add_lambdas (Cic.Meta (new_meta,irl))
709                        arity_instantiated_with_left_args
710                      in
711                      (Some candidate),ugraph4,metasenv,subst
712                  | (constructor_args_no,_,instance,_)::tl -> 
713                      try
714                        let instance',subst,metasenv = 
715                          CicMetaSubst.delift_rels subst metasenv
716                           constructor_args_no instance
717                        in
718                        let candidate,ugraph,metasenv,subst =
719                          List.fold_left (
720                            fun (candidate_oty,ugraph,metasenv,subst) 
721                              (constructor_args_no,_,instance,_) ->
722                                match candidate_oty with
723                                | None -> None,ugraph,metasenv,subst
724                                | Some ty ->
725                                  try 
726                                    let instance',subst,metasenv = 
727                                      CicMetaSubst.delift_rels subst metasenv
728                                       constructor_args_no instance
729                                    in
730                                    let subst,metasenv,ugraph =
731                                     fo_unif_subst subst context metasenv 
732                                       instance' ty ugraph
733                                    in
734                                     candidate_oty,ugraph,metasenv,subst
735                                  with
736                                     CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable
737                                   | RefineFailure _ | Uncertain _ ->
738                                      None,ugraph,metasenv,subst
739                          ) (Some instance',ugraph4,metasenv,subst) tl
740                        in
741                        match candidate with
742                        | None -> None, ugraph,metasenv,subst
743                        | Some t -> 
744                           let rec add_lambdas n b =
745                            function
746                               Cic.Prod (name,ty,t) ->
747                                Cic.Lambda (name,ty,(add_lambdas (n + 1) b t))
748                             | _ ->
749                               Cic.Lambda (fresh_name, ty,
750                                CicSubstitution.lift (n + 1) t)
751                           in
752                            Some
753                             (add_lambdas 0 t arity_instantiated_with_left_args),
754                            ugraph,metasenv,subst
755                      with CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
756                        None,ugraph4,metasenv,subst
757                in
758                match candidate with
759                | None -> raise (Uncertain (lazy "can't solve an higher order unification problem"))
760                | Some candidate ->
761                    let subst,metasenv,ugraph = 
762                     try
763                      fo_unif_subst subst context metasenv 
764                        candidate outtype ugraph5
765                     with
766                      exn -> assert false(* unification against a metavariable *)
767                    in
768                      C.MutCase (uri, i, outtype, term', pl'),
769                       CicReduction.head_beta_reduce
770                        (CicMetaSubst.apply_subst subst
771                         (Cic.Appl (outtype::right_args@[term']))),
772                      subst,metasenv,ugraph)
773            | _ ->    (* easy case *)
774              let tlbody_and_type,subst,metasenv,ugraph4 =
775                typeof_list subst metasenv context ugraph4 (right_args @ [term'])
776              in
777              let _,_,_,subst,metasenv,ugraph4 =
778                eat_prods false subst metasenv context 
779                  outtype outtypety tlbody_and_type ugraph4
780              in
781              let _,_, subst, metasenv,ugraph5 =
782                type_of_aux subst metasenv context
783                  (C.Appl ((outtype :: right_args) @ [term'])) ugraph4
784              in
785              let (subst,metasenv,ugraph6) = 
786                List.fold_left2
787                  (fun (subst,metasenv,ugraph) 
788                    p (constructor_args_no,context,instance,args)
789                   ->
790                     let instance' = 
791                       let appl =
792                         let outtype' =
793                           CicSubstitution.lift constructor_args_no outtype
794                         in
795                           C.Appl (outtype'::args)
796                       in
797                         CicReduction.whd ~subst context appl
798                     in
799                      try
800                       fo_unif_subst subst context metasenv instance instance'
801                        ugraph
802                      with
803                       exn ->
804                        enrich localization_tbl p exn
805                         ~f:(function _ ->
806                           lazy ("(12)The term " ^
807                            CicMetaSubst.ppterm_in_context ~metasenv subst p
808                             context ^ " has type " ^
809                            CicMetaSubst.ppterm_in_context ~metasenv subst instance'
810                             context ^ " but is here used with type " ^
811                            CicMetaSubst.ppterm_in_context ~metasenv subst instance
812                             context)))
813                  (subst,metasenv,ugraph5) pl' outtypeinstances 
814              in
815                C.MutCase (uri, i, outtype, term', pl'),
816                  CicReduction.head_beta_reduce
817                   (CicMetaSubst.apply_subst subst
818                    (C.Appl(outtype::right_args@[term]))),
819                  subst,metasenv,ugraph6)
820         | C.Fix (i,fl) ->
821             let fl_ty',subst,metasenv,types,ugraph1,len =
822               List.fold_left
823                 (fun (fl,subst,metasenv,types,ugraph,len) (n,_,ty,_) ->
824                    let ty',_,subst',metasenv',ugraph1 = 
825                       type_of_aux subst metasenv context ty ugraph 
826                    in
827                      fl @ [ty'],subst',metasenv', 
828                        Some (C.Name n,(C.Decl (CicSubstitution.lift len ty')))
829                         :: types, ugraph, len+1
830                 ) ([],subst,metasenv,[],ugraph,0) fl
831             in
832             let context' = types@context in
833             let fl_bo',subst,metasenv,ugraph2 =
834               List.fold_left
835                 (fun (fl,subst,metasenv,ugraph) ((name,x,_,bo),ty) ->
836                    let bo',ty_of_bo,subst,metasenv,ugraph1 =
837                      type_of_aux subst metasenv context' bo ugraph in
838                    let expected_ty = CicSubstitution.lift len ty in
839                    let subst',metasenv',ugraph' =
840                     try
841                      fo_unif_subst subst context' metasenv
842                        ty_of_bo expected_ty ugraph1
843                     with
844                      exn ->
845                       enrich localization_tbl bo exn
846                        ~f:(function _ ->
847                          lazy ("(13)The term " ^
848                           CicMetaSubst.ppterm_in_context ~metasenv subst bo
849                            context' ^ " has type " ^
850                           CicMetaSubst.ppterm_in_context ~metasenv subst ty_of_bo
851                            context' ^ " but is here used with type " ^
852                           CicMetaSubst.ppterm_in_context ~metasenv subst expected_ty
853                            context))
854                    in 
855                      fl @ [bo'] , subst',metasenv',ugraph'
856                 ) ([],subst,metasenv,ugraph1) (List.combine fl fl_ty') 
857             in
858             let ty = List.nth fl_ty' i in
859             (* now we have the new ty in fl_ty', the new bo in fl_bo',
860              * and we want the new fl with bo' and ty' injected in the right
861              * place.
862              *) 
863             let rec map3 f l1 l2 l3 =
864               match l1,l2,l3 with
865               | [],[],[] -> []
866               | h1::tl1,h2::tl2,h3::tl3 -> (f h1 h2 h3) :: (map3 f tl1 tl2 tl3)
867               | _ -> assert false 
868             in
869             let fl'' = map3 (fun ty' bo' (name,x,ty,bo) -> (name,x,ty',bo') ) 
870               fl_ty' fl_bo' fl 
871             in
872               C.Fix (i,fl''),ty,subst,metasenv,ugraph2
873         | C.CoFix (i,fl) ->
874             let fl_ty',subst,metasenv,types,ugraph1,len =
875               List.fold_left
876                 (fun (fl,subst,metasenv,types,ugraph,len) (n,ty,_) ->
877                    let ty',_,subst',metasenv',ugraph1 = 
878                      type_of_aux subst metasenv context ty ugraph 
879                    in
880                      fl @ [ty'],subst',metasenv', 
881                       Some (C.Name n,(C.Decl (CicSubstitution.lift len ty'))) ::
882                         types, ugraph1, len+1
883                 ) ([],subst,metasenv,[],ugraph,0) fl
884             in
885             let context' = types@context in
886             let fl_bo',subst,metasenv,ugraph2 =
887               List.fold_left
888                 (fun (fl,subst,metasenv,ugraph) ((name,_,bo),ty) ->
889                    let bo',ty_of_bo,subst,metasenv,ugraph1 =
890                      type_of_aux subst metasenv context' bo ugraph in
891                    let expected_ty = CicSubstitution.lift len ty in
892                    let subst',metasenv',ugraph' = 
893                     try
894                      fo_unif_subst subst context' metasenv
895                        ty_of_bo expected_ty ugraph1
896                     with
897                      exn ->
898                       enrich localization_tbl bo exn
899                        ~f:(function _ ->
900                          lazy ("(14)The term " ^
901                           CicMetaSubst.ppterm_in_context ~metasenv subst bo
902                            context' ^ " has type " ^
903                           CicMetaSubst.ppterm_in_context ~metasenv subst ty_of_bo
904                            context' ^ " but is here used with type " ^
905                           CicMetaSubst.ppterm_in_context ~metasenv subst expected_ty
906                            context))
907                    in
908                      fl @ [bo'],subst',metasenv',ugraph'
909                 ) ([],subst,metasenv,ugraph1) (List.combine fl fl_ty')
910             in
911             let ty = List.nth fl_ty' i in
912             (* now we have the new ty in fl_ty', the new bo in fl_bo',
913              * and we want the new fl with bo' and ty' injected in the right
914              * place.
915              *) 
916             let rec map3 f l1 l2 l3 =
917               match l1,l2,l3 with
918               | [],[],[] -> []
919               | h1::tl1,h2::tl2,h3::tl3 -> (f h1 h2 h3) :: (map3 f tl1 tl2 tl3)
920               | _ -> assert false
921             in
922             let fl'' = map3 (fun ty' bo' (name,ty,bo) -> (name,ty',bo') ) 
923               fl_ty' fl_bo' fl 
924             in
925               C.CoFix (i,fl''),ty,subst,metasenv,ugraph2
926      in
927       relocalize localization_tbl t t';
928       res
929
930   (* check_metasenv_consistency checks that the "canonical" context of a
931      metavariable is consitent - up to relocation via the relocation list l -
932      with the actual context *)
933   and check_metasenv_consistency
934     metano subst metasenv context canonical_context l ugraph
935     =
936     let module C = Cic in
937     let module R = CicReduction in
938     let module S = CicSubstitution in
939     let lifted_canonical_context = 
940       let rec aux i =
941         function
942             [] -> []
943           | (Some (n,C.Decl t))::tl ->
944               (Some (n,C.Decl (S.subst_meta l (S.lift i t))))::(aux (i+1) tl)
945           | (Some (n,C.Def (t,None)))::tl ->
946               (Some (n,C.Def ((S.subst_meta l (S.lift i t)),None)))::(aux (i+1) tl)
947           | None::tl -> None::(aux (i+1) tl)
948           | (Some (n,C.Def (t,Some ty)))::tl ->
949               (Some (n,
950                      C.Def ((S.subst_meta l (S.lift i t)),
951                             Some (S.subst_meta l (S.lift i ty))))) :: (aux (i+1) tl)
952       in
953         aux 1 canonical_context 
954     in
955       try
956         List.fold_left2 
957           (fun (l,subst,metasenv,ugraph) t ct -> 
958              match (t,ct) with
959                  _,None ->
960                    l @ [None],subst,metasenv,ugraph
961                | Some t,Some (_,C.Def (ct,_)) ->
962                    let subst',metasenv',ugraph' = 
963                    (try
964 prerr_endline ("poco geniale: nel caso di IRL basterebbe sapere che questo e' il Rel corrispondente. Si puo' ottimizzare il caso t = rel.");
965                       fo_unif_subst subst context metasenv t ct ugraph
966                     with e -> raise (RefineFailure (lazy (sprintf "The local context is not consistent with the canonical context, since %s cannot be unified with %s. Reason: %s" (CicMetaSubst.ppterm ~metasenv subst t) (CicMetaSubst.ppterm ~metasenv subst ct) (match e with AssertFailure msg -> Lazy.force msg | _ -> (Printexc.to_string e))))))
967                    in
968                      l @ [Some t],subst',metasenv',ugraph'
969                | Some t,Some (_,C.Decl ct) ->
970                    let t',inferredty,subst',metasenv',ugraph1 =
971                      type_of_aux subst metasenv context t ugraph
972                    in
973                    let subst'',metasenv'',ugraph2 = 
974                      (try
975                         fo_unif_subst
976                           subst' context metasenv' inferredty ct ugraph1
977                       with e -> raise (RefineFailure (lazy (sprintf "The local context is not consistent with the canonical context, since the type %s of %s cannot be unified with the expected type %s. Reason: %s" (CicMetaSubst.ppterm metasenv' subst' inferredty) (CicMetaSubst.ppterm metasenv' subst' t) (CicMetaSubst.ppterm metasenv' subst' ct) (match e with AssertFailure msg -> Lazy.force msg | RefineFailure msg -> Lazy.force msg | _ -> (Printexc.to_string e))))))
978                    in
979                      l @ [Some t'], subst'',metasenv'',ugraph2
980                | None, Some _  ->
981                    raise (RefineFailure (lazy (sprintf "Not well typed metavariable instance %s: the local context does not instantiate an hypothesis even if the hypothesis is not restricted in the canonical context %s" (CicMetaSubst.ppterm ~metasenv subst (Cic.Meta (metano, l))) (CicMetaSubst.ppcontext ~metasenv subst canonical_context))))) ([],subst,metasenv,ugraph) l lifted_canonical_context 
982       with
983           Invalid_argument _ ->
984             raise
985             (RefineFailure
986                (lazy (sprintf
987                   "Not well typed metavariable instance %s: the length of the local context does not match the length of the canonical context %s"
988                   (CicMetaSubst.ppterm ~metasenv subst (Cic.Meta (metano, l)))
989                   (CicMetaSubst.ppcontext ~metasenv subst canonical_context))))
990
991   and check_exp_named_subst metasubst metasenv context tl ugraph =
992     let rec check_exp_named_subst_aux metasubst metasenv substs tl ugraph  =
993       match tl with
994           [] -> [],metasubst,metasenv,ugraph
995         | (uri,t)::tl ->
996             let ty_uri,ugraph1 =  type_of_variable uri ugraph in
997             let typeofvar =
998               CicSubstitution.subst_vars substs ty_uri in
999               (* CSC: why was this code here? it is wrong
1000                  (match CicEnvironment.get_cooked_obj ~trust:false uri with
1001                  Cic.Variable (_,Some bo,_,_) ->
1002                  raise
1003                  (RefineFailure (lazy
1004                  "A variable with a body can not be explicit substituted"))
1005                  | Cic.Variable (_,None,_,_) -> ()
1006                  | _ ->
1007                  raise
1008                  (RefineFailure (lazy
1009                  ("Unkown variable definition " ^ UriManager.string_of_uri uri)))
1010                  ) ;
1011               *)
1012             let t',typeoft,metasubst',metasenv',ugraph2 =
1013               type_of_aux metasubst metasenv context t ugraph1 in
1014             let subst = uri,t' in
1015             let metasubst'',metasenv'',ugraph3 =
1016               try
1017                 fo_unif_subst 
1018                   metasubst' context metasenv' typeoft typeofvar ugraph2
1019               with _ ->
1020                 raise (RefineFailure (lazy
1021                          ("Wrong Explicit Named Substitution: " ^ 
1022                            CicMetaSubst.ppterm metasenv' metasubst' typeoft ^
1023                           " not unifiable with " ^ 
1024                           CicMetaSubst.ppterm metasenv' metasubst' typeofvar)))
1025             in
1026             (* FIXME: no mere tail recursive! *)
1027             let exp_name_subst, metasubst''', metasenv''', ugraph4 = 
1028               check_exp_named_subst_aux 
1029                 metasubst'' metasenv'' (substs@[subst]) tl ugraph3
1030             in
1031               ((uri,t')::exp_name_subst), metasubst''', metasenv''', ugraph4
1032     in
1033       check_exp_named_subst_aux metasubst metasenv [] tl ugraph
1034
1035
1036   and sort_of_prod localization_tbl subst metasenv context (name,s) t (t1, t2)
1037    ugraph
1038   =
1039     let module C = Cic in
1040     let context_for_t2 = (Some (name,C.Decl s))::context in
1041     let t1'' = CicReduction.whd ~subst context t1 in
1042     let t2'' = CicReduction.whd ~subst context_for_t2 t2 in
1043       match (t1'', t2'') with
1044           (C.Sort s1, C.Sort s2)
1045             when (s2 = C.Prop or s2 = C.Set or s2 = C.CProp) -> 
1046               (* different than Coq manual!!! *)
1047               C.Sort s2,subst,metasenv,ugraph
1048         | (C.Sort (C.Type t1), C.Sort (C.Type t2)) -> 
1049             let t' = CicUniv.fresh() in 
1050              (try
1051               let ugraph1 = CicUniv.add_ge t' t1 ugraph in
1052               let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
1053                 C.Sort (C.Type t'),subst,metasenv,ugraph2
1054               with
1055                CicUniv.UniverseInconsistency msg -> raise (RefineFailure msg))
1056         | (C.Sort _,C.Sort (C.Type t1)) -> 
1057             C.Sort (C.Type t1),subst,metasenv,ugraph
1058         | (C.Meta _, C.Sort _) -> t2'',subst,metasenv,ugraph
1059         | (C.Sort _,C.Meta _) | (C.Meta _,C.Meta _) ->
1060             (* TODO how can we force the meta to become a sort? If we don't we
1061              * break the invariant that refine produce only well typed terms *)
1062             (* TODO if we check the non meta term and if it is a sort then we
1063              * are likely to know the exact value of the result e.g. if the rhs
1064              * is a Sort (Prop | Set | CProp) then the result is the rhs *)
1065             let (metasenv,idx) =
1066               CicMkImplicit.mk_implicit_sort metasenv subst in
1067             let (subst, metasenv,ugraph1) =
1068              try
1069               fo_unif_subst subst context_for_t2 metasenv 
1070                 (C.Meta (idx,[])) t2'' ugraph
1071              with _ -> assert false (* unification against a metavariable *)
1072             in
1073               t2'',subst,metasenv,ugraph1
1074         | (C.Sort _,_)
1075         | (C.Meta _,_) -> 
1076             enrich localization_tbl s
1077              (RefineFailure 
1078                (lazy 
1079                  (sprintf
1080                    "%s is supposed to be a type, but its type is %s"
1081                (CicMetaSubst.ppterm_in_context ~metasenv subst t context)
1082                (CicMetaSubst.ppterm_in_context ~metasenv subst t2 context))))
1083         | _,_ -> 
1084             enrich localization_tbl t
1085              (RefineFailure 
1086                (lazy 
1087                  (sprintf
1088                    "%s is supposed to be a type, but its type is %s"
1089                (CicMetaSubst.ppterm_in_context ~metasenv subst s context)
1090                (CicMetaSubst.ppterm_in_context ~metasenv subst t1 context))))
1091
1092   and avoid_double_coercion context subst metasenv ugraph t ty = 
1093    if not !pack_coercions then
1094     t,ty,subst,metasenv,ugraph
1095    else
1096     let b, c1, c2, head, c1_c2_implicit = is_a_double_coercion t in
1097     if b then
1098       let source_carr = CoercGraph.source_of c2 in
1099       let tgt_carr = CicMetaSubst.apply_subst subst ty in
1100       (match CoercGraph.look_for_coercion metasenv subst context source_carr tgt_carr 
1101       with
1102       | CoercGraph.SomeCoercion candidates -> 
1103          let selected =
1104            HExtlib.list_findopt
1105              (function (metasenv,last,c) ->
1106                match c with 
1107                | c when not (CoercGraph.is_composite c) -> 
1108                    debug_print (lazy ("\nNot a composite.."^CicPp.ppterm c));
1109                    None
1110                | c ->
1111                let subst,metasenv,ugraph =
1112                 fo_unif_subst subst context metasenv last head ugraph in
1113                debug_print (lazy ("\nprovo" ^ CicPp.ppterm c));
1114                (try
1115                  debug_print 
1116                    (lazy 
1117                      ("packing: " ^ 
1118                        CicPp.ppterm t ^ " ==> " ^ CicPp.ppterm c));
1119                  let newt,_,subst,metasenv,ugraph = 
1120                    type_of_aux subst metasenv context c ugraph in
1121                  debug_print (lazy "tipa...");
1122                  let subst, metasenv, ugraph =
1123                    (* COME MAI C'ERA UN IF su !pack_coercions ??? *)
1124                     fo_unif_subst subst context metasenv newt t ugraph
1125                  in
1126                  debug_print (lazy "unifica...");
1127                  Some (newt, ty, subst, metasenv, ugraph)
1128                with 
1129                | RefineFailure s | Uncertain s when not !pack_coercions-> 
1130                    debug_print s; debug_print (lazy "stop\n");None
1131                | RefineFailure s | Uncertain s -> 
1132                    debug_print s;debug_print (lazy "goon\n");
1133                    try 
1134                      let old_pack_coercions = !pack_coercions in
1135                      pack_coercions := false; (* to avoid diverging *)
1136                      let refined_c1_c2_implicit,ty,subst,metasenv,ugraph =
1137                        type_of_aux subst metasenv context c1_c2_implicit ugraph 
1138                      in
1139                      pack_coercions := old_pack_coercions;
1140                      let b, _, _, _, _ = 
1141                        is_a_double_coercion refined_c1_c2_implicit 
1142                      in 
1143                      if b then 
1144                        None 
1145                      else
1146                        let head' = 
1147                          match refined_c1_c2_implicit with
1148                          | Cic.Appl l -> HExtlib.list_last l
1149                          | _ -> assert false   
1150                        in
1151                        let subst, metasenv, ugraph =
1152                         try fo_unif_subst subst context metasenv 
1153                           head head' ugraph
1154                         with RefineFailure s| Uncertain s-> 
1155                           debug_print s;assert false 
1156                        in
1157                        let subst, metasenv, ugraph =
1158                          fo_unif_subst subst context metasenv 
1159                           refined_c1_c2_implicit t ugraph
1160                        in
1161                        Some (refined_c1_c2_implicit,ty,subst,metasenv,ugraph)
1162                    with 
1163                    | RefineFailure s | Uncertain s -> 
1164                        pack_coercions := true;debug_print s;None
1165                    | exn -> pack_coercions := true; raise exn))
1166              candidates
1167          in
1168          (match selected with
1169          | Some x -> x
1170          | None -> 
1171               debug_print
1172                 (lazy ("#### Coercion not packed: " ^ CicPp.ppterm t));
1173               t, ty, subst, metasenv, ugraph)
1174       | _ -> t, ty, subst, metasenv, ugraph)
1175     else
1176       t, ty, subst, metasenv, ugraph  
1177
1178   and typeof_list subst metasenv context ugraph l =
1179     let tlbody_and_type,subst,metasenv,ugraph =
1180       List.fold_right
1181         (fun x (res,subst,metasenv,ugraph) ->
1182            let x',ty,subst',metasenv',ugraph1 =
1183              type_of_aux subst metasenv context x ugraph
1184            in
1185             (x', ty)::res,subst',metasenv',ugraph1
1186         ) l ([],subst,metasenv,ugraph)
1187     in
1188       tlbody_and_type,subst,metasenv,ugraph
1189
1190   and eat_prods
1191     allow_coercions subst metasenv context he hetype args_bo_and_ty ugraph 
1192   =
1193     (* given he:hety, gives beack all (c he) such that (c e):?->? *)
1194     let fix_arity n metasenv context subst he hetype ugraph =
1195       let hetype = CicMetaSubst.apply_subst subst hetype in
1196       let src = CoercDb.coerc_carr_of_term hetype in 
1197       let tgt = CoercDb.Fun 0 in
1198       match CoercGraph.look_for_coercion' metasenv subst context src tgt with
1199       | CoercGraph.NoCoercion -> []
1200       | CoercGraph.NotMetaClosed 
1201       | CoercGraph.NotHandled _ ->
1202          raise (MoreArgsThanExpected (n,Uncertain (lazy "")))
1203       | CoercGraph.SomeCoercionToTgt candidates
1204       | CoercGraph.SomeCoercion candidates ->
1205           HExtlib.filter_map
1206             (fun (metasenv,last,coerc) -> 
1207               let pp t = 
1208                 CicMetaSubst.ppterm_in_context ~metasenv subst t context in
1209               let subst,metasenv,ugraph =
1210                fo_unif_subst subst context metasenv last he ugraph in
1211               debug_print (lazy ("New head: "^ pp coerc));
1212               try
1213                 let tty,ugraph =
1214                  CicTypeChecker.type_of_aux' ~subst metasenv context coerc ugraph in 
1215                 debug_print (lazy (" has type: "^ pp tty));
1216                 Some (coerc,tty,subst,metasenv,ugraph)
1217               with
1218               | Uncertain _ | RefineFailure _
1219               | HExtlib.Localized (_,Uncertain _)
1220               | HExtlib.Localized (_,RefineFailure _) -> None 
1221               | exn -> assert false) 
1222             candidates
1223     in
1224     (* aux function to process the type of the head and the args in parallel *)
1225     let rec eat_prods_and_args metasenv subst context he hetype ugraph newargs =
1226       function
1227       | [] -> newargs,subst,metasenv,he,hetype,ugraph
1228       | (hete, hety)::tl as args ->
1229           match (CicReduction.whd ~subst context hetype) with 
1230           | Cic.Prod (n,s,t) ->
1231               let arg,subst,metasenv,ugraph =
1232                 coerce_to_something allow_coercions localization_tbl 
1233                   hete hety s subst metasenv context ugraph in
1234               eat_prods_and_args 
1235                 metasenv subst context he (CicSubstitution.subst (fst arg) t) 
1236                 ugraph (newargs@[arg]) tl
1237           | _ -> 
1238               let he = 
1239                 match he, newargs with
1240                 | _, [] -> he
1241                 | Cic.Appl l, _ -> Cic.Appl (l@List.map fst newargs)
1242                 | _ -> Cic.Appl (he::List.map fst newargs)
1243               in
1244               (*{{{*) debug_print (lazy 
1245                let pp x = 
1246                 CicMetaSubst.ppterm_in_context ~metasenv subst x context in
1247                "Fixing arity of: "^ pp he ^ "\n that has type: "^ pp hetype^
1248                "\n but is applyed to: " ^ String.concat ";" 
1249                (List.map (fun (t,_)->pp t) args_bo_and_ty)); (*}}}*)
1250               let possible_fixes = 
1251                fix_arity (List.length args) metasenv context subst he hetype
1252                 ugraph in
1253               match
1254                 HExtlib.list_findopt
1255                  (fun (he,hetype,subst,metasenv,ugraph) ->
1256                    (* {{{ *)debug_print (lazy ("Try fix: "^
1257                     CicMetaSubst.ppterm_in_context ~metasenv subst he context));
1258                    debug_print (lazy (" of type: "^
1259                     CicMetaSubst.ppterm_in_context 
1260                     ~metasenv subst hetype context)); (* }}} *)
1261                    try      
1262                     Some (eat_prods_and_args 
1263                       metasenv subst context he hetype ugraph [] args)
1264                    with
1265                     | RefineFailure _ | Uncertain _
1266                     | HExtlib.Localized (_,RefineFailure _)
1267                     | HExtlib.Localized (_,Uncertain _) -> None)
1268                 possible_fixes
1269               with
1270               | Some x -> x
1271               | None ->
1272                  raise 
1273                   (MoreArgsThanExpected
1274                     (List.length args, RefineFailure (lazy "")))
1275     in
1276     (* first we check if we are in the simple case of a meta closed term *)
1277     let subst,metasenv,ugraph1,hetype',he,args_bo_and_ty =
1278      if CicUtil.is_meta_closed (CicMetaSubst.apply_subst subst hetype) then
1279       (* this optimization is to postpone fix_arity (the most common case)*)
1280       subst,metasenv,ugraph,hetype,he,args_bo_and_ty
1281      else
1282        (* this (says CSC) is also useful to infer dependent types *)
1283         let pristinemenv = metasenv in
1284         let metasenv,hetype' = 
1285           mk_prod_of_metas metasenv context subst args_bo_and_ty 
1286         in
1287         try
1288           let subst,metasenv,ugraph = 
1289            fo_unif_subst_eat_prods subst context metasenv hetype hetype' ugraph
1290           in
1291           subst,metasenv,ugraph,hetype',he,args_bo_and_ty
1292         with RefineFailure _ | Uncertain _ ->
1293           subst,pristinemenv,ugraph,hetype,he,args_bo_and_ty
1294     in
1295     let coerced_args,subst,metasenv,he,t,ugraph =
1296      try
1297       eat_prods_and_args 
1298         metasenv subst context he hetype' ugraph1 [] args_bo_and_ty
1299      with
1300       MoreArgsThanExpected (residuals,exn) ->
1301         more_args_than_expected localization_tbl metasenv
1302          subst he context hetype' residuals args_bo_and_ty exn
1303     in
1304     he,(List.map fst coerced_args),t,subst,metasenv,ugraph
1305
1306   and coerce_to_something 
1307     allow_coercions localization_tbl t infty expty subst metasenv context ugraph
1308   =
1309     let module CS = CicSubstitution in
1310     let module CR = CicReduction in
1311     let cs_subst = CS.subst ~avoid_beta_redexes:true in
1312     let coerce_atom_to_something t infty expty subst metasenv context ugraph =
1313       debug_print (lazy ("COERCE_ATOM_TO_SOMETHING"));
1314       let coer = 
1315         CoercGraph.look_for_coercion metasenv subst context infty expty
1316       in
1317       match coer with
1318       | CoercGraph.NotMetaClosed -> raise (Uncertain (lazy
1319           "coerce_atom_to_something fails since not meta closed"))
1320       | CoercGraph.NoCoercion 
1321       | CoercGraph.SomeCoercionToTgt _
1322       | CoercGraph.NotHandled _ -> raise (RefineFailure (lazy
1323           "coerce_atom_to_something fails since no coercions found"))
1324       | CoercGraph.SomeCoercion candidates -> 
1325           debug_print (lazy (string_of_int (List.length candidates) ^ 
1326             " candidates found"));
1327           let uncertain = ref false in
1328           let selected = 
1329             let posibilities =
1330               HExtlib.filter_map
1331               (fun (metasenv,last,c) -> 
1332                try
1333                 (* {{{ *) debug_print (lazy ("FO_UNIF_SUBST: " ^
1334                 CicMetaSubst.ppterm_in_context ~metasenv subst last context ^
1335                 " <==> " ^
1336                 CicMetaSubst.ppterm_in_context ~metasenv subst t context));
1337                 debug_print (lazy ("FO_UNIF_SUBST: " ^
1338                 CicPp.ppterm last ^ " <==> " ^ CicPp.ppterm t)); (* }}} *)
1339                 let subst,metasenv,ugraph =
1340                  fo_unif_subst subst context metasenv last t ugraph
1341                 in
1342                 let newt,newhety,subst,metasenv,ugraph = 
1343                  type_of_aux subst metasenv context c ugraph in
1344                 let newt, newty, subst, metasenv, ugraph = 
1345                  avoid_double_coercion context subst metasenv ugraph newt expty 
1346                 in
1347                 let subst,metasenv,ugraph = 
1348                   fo_unif_subst subst context metasenv newhety expty ugraph in
1349                  Some ((newt,newty), subst, metasenv, ugraph)
1350                with 
1351                | Uncertain _ -> uncertain := true; None
1352                | RefineFailure _ -> None)
1353               candidates
1354             in
1355             match 
1356               List.fast_sort 
1357                 (fun (_,_,m1,_) (_,_,m2,_) -> List.length m1 - List.length m2) 
1358                 posibilities 
1359             with
1360             | [] -> None
1361             | x::_ -> Some x
1362           in
1363           match selected with
1364           | Some x -> x
1365           | None when !uncertain -> raise (Uncertain (lazy "coerce_atom fails"))
1366           | None -> raise (RefineFailure (lazy "coerce_atom fails"))
1367     in
1368     let rec coerce_to_something_aux 
1369       t infty expty subst metasenv context ugraph 
1370     =
1371       try            
1372         let subst, metasenv, ugraph =
1373           fo_unif_subst subst context metasenv infty expty ugraph
1374         in
1375         (t, expty), subst, metasenv, ugraph
1376       with Uncertain _ | RefineFailure _ as exn ->
1377         if not allow_coercions || not !insert_coercions then
1378           enrich localization_tbl t exn
1379         else
1380           let whd = CicReduction.whd ~delta:false in
1381           let clean t s c = whd c (CicMetaSubst.apply_subst s t) in
1382           let infty = clean infty subst context in
1383           let expty = clean expty subst context in
1384           let t = clean t subst context in
1385           (*{{{*) debug_print (lazy ("COERCE_TO_SOMETHING: " ^
1386           CicMetaSubst.ppterm_in_context ~metasenv subst t context ^ " : " ^
1387           CicMetaSubst.ppterm_in_context ~metasenv subst infty context ^" ==> "^
1388           CicMetaSubst.ppterm_in_context ~metasenv subst expty context));(*}}}*)
1389           let (coerced,_),subst,metasenv,_ as result = 
1390            match infty, expty, t with
1391            | Cic.Prod (nameprod,src,ty), Cic.Prod (_,src2,ty2),Cic.Fix (n,fl) ->
1392               (*{{{*) debug_print (lazy "FIX");
1393               (match fl with
1394                   [name,i,_(* infty *),bo] ->
1395                     let context_bo =
1396                      Some (Cic.Name name,Cic.Decl expty)::context in
1397                     let (rel1, _), subst, metasenv, ugraph =
1398                      coerce_to_something_aux (Cic.Rel 1) 
1399                        (CS.lift 1 expty) (CS.lift 1 infty) subst
1400                       metasenv context_bo ugraph in
1401                     let bo = cs_subst rel1 (CS.lift_from 2 1 bo) in
1402                     let (bo,_), subst, metasenv, ugraph =
1403                      coerce_to_something_aux bo (CS.lift 1 infty) (CS.lift 1
1404                      expty) subst
1405                       metasenv context_bo ugraph
1406                     in
1407                      (Cic.Fix (n,[name,i,expty,bo]),expty),subst,metasenv,ugraph
1408                 | _ -> assert false (* not implemented yet *)) (*}}}*)
1409            | _,_, Cic.MutCase (uri,tyno,outty,m,pl) ->
1410                (*{{{*) debug_print (lazy "CASE");
1411                (* {{{ helper functions *)
1412                let get_cl_and_left_p uri tyno outty ugraph =
1413                  match CicEnvironment.get_obj ugraph uri with
1414                  | Cic.InductiveDefinition (tl, _, leftno, _),ugraph ->
1415                      let count_pis t =
1416                        let rec aux ctx t = 
1417                          match CicReduction.whd ~delta:false ctx t with
1418                          | Cic.Prod (name,src,tgt) ->
1419                              let ctx = Some (name, Cic.Decl src) :: ctx in
1420                              1 + aux ctx tgt
1421                          | _ -> 0
1422                        in
1423                          aux [] t
1424                      in
1425                      let rec skip_lambda_delifting t n =
1426                        match t,n with
1427                        | _,0 -> t
1428                        | Cic.Lambda (_,_,t),n -> 
1429                            skip_lambda_delifting
1430                              (CS.subst (Cic.Implicit None) t) (n - 1)
1431                        | _ -> assert false
1432                      in
1433                      let get_l_r_p n = function
1434                        | Cic.Lambda (_,Cic.MutInd _,_) -> [],[]
1435                        | Cic.Lambda (_,Cic.Appl (Cic.MutInd _ :: args),_) ->
1436                            HExtlib.split_nth n args
1437                        | _ -> assert false
1438                      in
1439                      let _, _, ty, cl = List.nth tl tyno in
1440                      let pis = count_pis ty in
1441                      let rno = pis - leftno in
1442                      let t = skip_lambda_delifting outty rno in
1443                      let left_p, _ = get_l_r_p leftno t in
1444                      let instantiale_with_left cl =
1445                        List.map 
1446                          (fun ty -> 
1447                            List.fold_left 
1448                              (fun t p -> match t with
1449                                | Cic.Prod (_,_,t) ->
1450                                    cs_subst p t
1451                                | _-> assert false)
1452                              ty left_p) 
1453                          cl 
1454                      in
1455                      let cl = instantiale_with_left (List.map snd cl) in
1456                      cl, left_p, leftno, rno, ugraph
1457                  | _ -> raise exn
1458                in
1459                let rec keep_lambdas_and_put_expty ctx t bo right_p matched n =
1460                  match t,n with
1461                  | _,0 ->
1462                    let rec mkr n = function 
1463                      | [] -> [] | _::tl -> Cic.Rel n :: mkr (n+1) tl
1464                    in
1465                    let bo =
1466                    CicReplace.replace_lifting
1467                      ~equality:(fun _ -> CicUtil.alpha_equivalence)
1468                      ~context:ctx
1469                      ~what:(matched::right_p)
1470                      ~with_what:(Cic.Rel 1::List.rev (mkr 2 right_p))
1471                      ~where:bo
1472                    in
1473                    bo
1474                  | Cic.Lambda (name, src, tgt),_ ->
1475                      Cic.Lambda (name, src,
1476                       keep_lambdas_and_put_expty 
1477                        (Some (name, Cic.Decl src)::ctx) tgt (CS.lift 1 bo)
1478                        (List.map (CS.lift 1) right_p) (CS.lift 1 matched) (n-1))
1479                  | _ -> assert false
1480                in
1481                let eq_uri, eq, eq_refl = 
1482                  match LibraryObjects.eq_URI () with 
1483                  | None -> HLog.warn "no default equality"; raise exn
1484                  | Some u -> u, Cic.MutInd(u,0,[]), Cic.MutConstruct (u,0,1,[])
1485                in
1486                let add_params 
1487                  metasenv subst context uri tyno cty outty mty m leftno i 
1488                =
1489                  let rec aux context outty par k mty m = function
1490                    | Cic.Prod (name, src, tgt) ->
1491                        let t,k = 
1492                          aux 
1493                            (Some (name, Cic.Decl src) :: context)
1494                            (CS.lift 1 outty) (Cic.Rel k::par) (k+1) 
1495                            (CS.lift 1 mty) (CS.lift 1 m) tgt
1496                        in
1497                        Cic.Prod (name, src, t), k
1498                    | Cic.MutInd _ ->
1499                        let k = 
1500                          let k = Cic.MutConstruct (uri,tyno,i,[]) in
1501                          if par <> [] then Cic.Appl (k::par) else k
1502                        in
1503                        Cic.Prod (Cic.Name "p", 
1504                         Cic.Appl [eq; mty; m; k],
1505                         (CS.lift 1
1506                          (CR.head_beta_reduce ~delta:false 
1507                           (Cic.Appl [outty;k])))),k
1508                    | Cic.Appl (Cic.MutInd _::pl) ->
1509                        let left_p,right_p = HExtlib.split_nth leftno pl in
1510                        let has_rights = right_p <> [] in
1511                        let k = 
1512                          let k = Cic.MutConstruct (uri,tyno,i,[]) in
1513                          Cic.Appl (k::left_p@par)
1514                        in
1515                        let right_p = 
1516                          try match 
1517                            CicTypeChecker.type_of_aux' ~subst metasenv context k
1518                              CicUniv.oblivion_ugraph 
1519                          with
1520                          | Cic.Appl (Cic.MutInd _::args),_ ->
1521                              snd (HExtlib.split_nth leftno args)
1522                          | _ -> assert false
1523                          with CicTypeChecker.TypeCheckerFailure _-> assert false
1524                        in
1525                        if has_rights then
1526                          CR.head_beta_reduce ~delta:false 
1527                            (Cic.Appl (outty ::right_p @ [k])),k
1528                        else
1529                          Cic.Prod (Cic.Name "p", 
1530                           Cic.Appl [eq; mty; m; k],
1531                           (CS.lift 1
1532                            (CR.head_beta_reduce ~delta:false 
1533                             (Cic.Appl (outty ::right_p @ [k]))))),k
1534                    | _ -> assert false
1535                  in
1536                    aux context outty [] 1 mty m cty
1537                in
1538                let add_lambda_for_refl_m pbo rno mty m k cty =
1539                  (* k lives in the right context *)
1540                  if rno <> 0 then pbo else
1541                  let rec aux mty m = function 
1542                    | Cic.Lambda (name,src,bo), Cic.Prod (_,_,ty) ->
1543                       Cic.Lambda (name,src,
1544                        (aux (CS.lift 1 mty) (CS.lift 1 m) (bo,ty)))
1545                    | t,_ -> 
1546                        Cic.Lambda (Cic.Name "p",
1547                          Cic.Appl [eq; mty; m; k],CS.lift 1 t)
1548                  in
1549                  aux mty m (pbo,cty)
1550                in
1551                let add_pi_for_refl_m new_outty mty m rno =
1552                  if rno <> 0 then new_outty else
1553                    let rec aux m mty = function
1554                      | Cic.Lambda (name, src, tgt) ->
1555                          Cic.Lambda (name, src, 
1556                            aux (CS.lift 1 m) (CS.lift 1 mty) tgt)
1557                      | t ->
1558                          Cic.Prod 
1559                            (Cic.Anonymous, Cic.Appl [eq;mty;m;Cic.Rel 1],
1560                            CS.lift 1 t)
1561                    in
1562                      aux m mty new_outty
1563                in (* }}} end helper functions *)
1564                (* constructors types with left params already instantiated *)
1565                let outty = CicMetaSubst.apply_subst subst outty in
1566                let cl, left_p, leftno,rno,ugraph = 
1567                  get_cl_and_left_p uri tyno outty ugraph 
1568                in
1569                let right_p, mty = 
1570                  try
1571                    match 
1572                      CicTypeChecker.type_of_aux' ~subst metasenv context m
1573                        CicUniv.oblivion_ugraph 
1574                    with
1575                    | Cic.MutInd _ as mty,_ -> [], mty
1576                    | Cic.Appl (Cic.MutInd _::args) as mty,_ ->
1577                        snd (HExtlib.split_nth leftno args), mty
1578                    | _ -> assert false
1579                  with CicTypeChecker.TypeCheckerFailure _ -> assert false
1580                in
1581                let new_outty =
1582                 keep_lambdas_and_put_expty context outty expty right_p m (rno+1)
1583                in
1584                debug_print 
1585                  (lazy ("CASE: new_outty: " ^ CicMetaSubst.ppterm_in_context 
1586                   ~metasenv subst new_outty context));
1587                let _,pl,subst,metasenv,ugraph = 
1588                  List.fold_right2
1589                    (fun cty pbo (i, acc, s, menv, ugraph) -> 
1590                      (* Pi k_par, (Pi H:m=(K_i left_par k_par)), 
1591                       *   (new_)outty right_par (K_i left_par k_par) *)
1592                       let infty_pbo, _ = 
1593                         add_params menv s context uri tyno 
1594                           cty outty mty m leftno i in
1595                       debug_print 
1596                        (lazy ("CASE: infty_pbo: "^CicMetaSubst.ppterm_in_context
1597                         ~metasenv subst infty_pbo context));
1598                       let expty_pbo, k = (* k is (K_i left_par k_par) *)
1599                         add_params menv s context uri tyno 
1600                           cty new_outty mty m leftno i in
1601                       debug_print 
1602                        (lazy ("CASE: expty_pbo: "^CicMetaSubst.ppterm_in_context
1603                         ~metasenv subst expty_pbo context));
1604                       let pbo = add_lambda_for_refl_m pbo rno mty m k cty in
1605                       debug_print 
1606                         (lazy ("CASE: pbo: " ^ CicMetaSubst.ppterm_in_context 
1607                         ~metasenv subst pbo context));
1608                       let (pbo, _), subst, metasenv, ugraph =
1609                         coerce_to_something_aux pbo infty_pbo expty_pbo 
1610                           s menv context ugraph
1611                       in
1612                       debug_print 
1613                         (lazy ("CASE: pbo: " ^ CicMetaSubst.ppterm_in_context 
1614                         ~metasenv subst pbo context));
1615                       (i-1, pbo::acc, subst, metasenv, ugraph))
1616                    cl pl (List.length pl, [], subst, metasenv, ugraph)
1617                in
1618                let new_outty = add_pi_for_refl_m new_outty mty m rno in
1619                debug_print 
1620                  (lazy ("CASE: new_outty: " ^ CicMetaSubst.ppterm_in_context 
1621                   ~metasenv subst new_outty context));
1622                let t = 
1623                  if rno = 0 then
1624                    let refl_m=Cic.Appl[eq_refl;mty;m]in
1625                    Cic.Appl [Cic.MutCase(uri,tyno,new_outty,m,pl);refl_m] 
1626                  else 
1627                    Cic.MutCase(uri,tyno,new_outty,m,pl)
1628                in
1629                (t, expty), subst, metasenv, ugraph (*}}}*)
1630            | Cic.Prod (nameprod, src, ty),Cic.Prod (_, src2, ty2), _ -> 
1631                (*{{{*) debug_print (lazy "LAM");
1632                let name_con = 
1633                  FreshNamesGenerator.mk_fresh_name 
1634                    ~subst metasenv context ~typ:src2 Cic.Anonymous
1635                in
1636                let context_src2 = (Some (name_con, Cic.Decl src2) :: context) in
1637                (* contravariant part: the argument of f:src->ty *)
1638                let (rel1, _), subst, metasenv, ugraph = 
1639                  coerce_to_something_aux
1640                   (Cic.Rel 1) (CS.lift 1 src2) 
1641                   (CS.lift 1 src) subst metasenv context_src2 ugraph
1642                in
1643                (* covariant part: the result of f(c x); x:src2; (c x):src *)
1644                let name_t, bo = 
1645                  match t with
1646                  | Cic.Lambda (n,_,bo) -> n, cs_subst rel1 (CS.lift_from 2 1 bo)
1647                  | _ -> name_con, Cic.Appl[CS.lift 1 t;rel1]
1648                in
1649                (* we fix the possible dependency problem in the source ty *)
1650                let ty = cs_subst rel1 (CS.lift_from 2 1 ty) in
1651                let (bo, _), subst, metasenv, ugraph = 
1652                  coerce_to_something_aux
1653                    bo ty ty2 subst metasenv context_src2 ugraph
1654                in
1655                let coerced = Cic.Lambda (name_t,src2, bo) in
1656                (coerced, expty), subst, metasenv, ugraph (*}}}*)
1657            | _ -> 
1658                (*{{{*)debug_print (lazy ("ATOM: "^CicMetaSubst.ppterm_in_context
1659                 ~metasenv subst infty context ^ " ==> " ^
1660                 CicMetaSubst.ppterm_in_context ~metasenv subst expty context));
1661                coerce_atom_to_something
1662                t infty expty subst metasenv context ugraph (*}}}*)
1663           in
1664           debug_print (lazy ("COERCE TO SOMETHING END: "^
1665             CicMetaSubst.ppterm_in_context ~metasenv subst coerced context));
1666           result
1667     in
1668     try
1669       coerce_to_something_aux t infty expty subst metasenv context ugraph
1670     with Uncertain _ | RefineFailure _ as exn ->
1671       let f _ =
1672         lazy ("The term " ^
1673           CicMetaSubst.ppterm_in_context metasenv subst t context ^ 
1674           " has type " ^ CicMetaSubst.ppterm_in_context metasenv subst
1675           infty context ^ " but is here used with type " ^ 
1676           CicMetaSubst.ppterm_in_context metasenv subst expty context)
1677       in
1678         enrich localization_tbl ~f t exn
1679
1680   and coerce_to_sort localization_tbl t infty subst context metasenv uragph =
1681     match CicReduction.whd ~delta:false ~subst context infty with
1682     | Cic.Meta _ | Cic.Sort _ -> 
1683         t,infty, subst, metasenv, ugraph
1684     | src ->
1685        debug_print (lazy ("COERCE TO SORT: "^CicMetaSubst.ppterm_in_context
1686          ~metasenv subst src context));
1687        let tgt = Cic.Sort (Cic.Type (CicUniv.fresh())) in
1688        try
1689          let (t, ty_t), subst, metasenv, ugraph =
1690            coerce_to_something true
1691              localization_tbl t src tgt subst metasenv context ugraph
1692          in
1693          debug_print (lazy ("COERCE TO SORT END: "^ 
1694            CicMetaSubst.ppterm_in_context ~metasenv subst t context));
1695          t, ty_t, subst, metasenv, ugraph
1696        with HExtlib.Localized (_, exn) -> 
1697          let f _ = 
1698            lazy ("(7)The term " ^ 
1699             CicMetaSubst.ppterm_in_context ~metasenv subst t context 
1700             ^ " is not a type since it has type " ^ 
1701             CicMetaSubst.ppterm_in_context ~metasenv subst src context
1702             ^ " that is not a sort")
1703          in
1704            enrich localization_tbl ~f t exn
1705   in
1706   
1707   (* eat prods ends here! *)
1708   
1709   let t',ty,subst',metasenv',ugraph1 =
1710    type_of_aux [] metasenv context t ugraph
1711   in
1712   let substituted_t = CicMetaSubst.apply_subst subst' t' in
1713   let substituted_ty = CicMetaSubst.apply_subst subst' ty in
1714     (* Andrea: ho rimesso qui l'applicazione della subst al
1715        metasenv dopo che ho droppato l'invariante che il metsaenv
1716        e' sempre istanziato *)
1717   let substituted_metasenv = 
1718     CicMetaSubst.apply_subst_metasenv subst' metasenv' in
1719     (* metasenv' *)
1720     (*  substituted_t,substituted_ty,substituted_metasenv *)
1721     (* ANDREA: spostare tutta questa robaccia da un altra parte *)
1722   let cleaned_t =
1723     FreshNamesGenerator.clean_dummy_dependent_types substituted_t in
1724   let cleaned_ty =
1725     FreshNamesGenerator.clean_dummy_dependent_types substituted_ty in
1726   let cleaned_metasenv =
1727     List.map
1728       (function (n,context,ty) ->
1729          let ty' = FreshNamesGenerator.clean_dummy_dependent_types ty in
1730          let context' =
1731            List.map
1732              (function
1733                   None -> None
1734                 | Some (n, Cic.Decl t) ->
1735                     Some (n,
1736                           Cic.Decl (FreshNamesGenerator.clean_dummy_dependent_types t))
1737                 | Some (n, Cic.Def (bo,ty)) ->
1738                     let bo' = FreshNamesGenerator.clean_dummy_dependent_types bo in
1739                     let ty' =
1740                       match ty with
1741                           None -> None
1742                         | Some ty ->
1743                             Some (FreshNamesGenerator.clean_dummy_dependent_types ty)
1744                     in
1745                       Some (n, Cic.Def (bo',ty'))
1746              ) context
1747          in
1748            (n,context',ty')
1749       ) substituted_metasenv
1750   in
1751     (cleaned_t,cleaned_ty,cleaned_metasenv,ugraph1) 
1752 ;;
1753
1754 let undebrujin uri typesno tys t =
1755   snd
1756    (List.fold_right
1757      (fun (name,_,_,_) (i,t) ->
1758        (* here the explicit_named_substituion is assumed to be *)
1759        (* of length 0 *)
1760        let t' = Cic.MutInd (uri,i,[])  in
1761        let t = CicSubstitution.subst t' t in
1762         i - 1,t
1763      ) tys (typesno - 1,t)) 
1764
1765 let map_first_n n start f g l = 
1766   let rec aux acc k l =
1767     if k < n then
1768       match l with
1769       | [] -> raise (Invalid_argument "map_first_n")
1770       | hd :: tl -> f hd k (aux acc (k+1) tl)
1771     else
1772       g acc l
1773   in
1774   aux start 0 l
1775    
1776 (*CSC: this is a very rough approximation; to be finished *)
1777 let are_all_occurrences_positive metasenv ugraph uri tys leftno =
1778   let subst,metasenv,ugraph,tys = 
1779     List.fold_right
1780       (fun (name,ind,arity,cl) (subst,metasenv,ugraph,acc) ->
1781         let subst,metasenv,ugraph,cl = 
1782           List.fold_right
1783             (fun (name,ty) (subst,metasenv,ugraph,acc) ->
1784                let rec aux ctx k subst = function
1785                  | Cic.Appl((Cic.MutInd (uri',_,_)as hd)::tl) when uri = uri'->
1786                      let subst,metasenv,ugraph,tl = 
1787                        map_first_n leftno 
1788                          (subst,metasenv,ugraph,[]) 
1789                          (fun t n (subst,metasenv,ugraph,acc) ->
1790                            let subst,metasenv,ugraph = 
1791                              fo_unif_subst 
1792                                subst ctx metasenv t (Cic.Rel (k-n)) ugraph 
1793                            in
1794                            subst,metasenv,ugraph,(t::acc)) 
1795                          (fun (s,m,g,acc) tl -> assert(acc=[]);(s,m,g,tl)) 
1796                          tl
1797                      in
1798                      subst,metasenv,ugraph,(Cic.Appl (hd::tl))
1799                  | Cic.MutInd(uri',_,_) as t when uri = uri'->
1800                      subst,metasenv,ugraph,t 
1801                  | Cic.Prod (name,s,t) -> 
1802                      let ctx = (Some (name,Cic.Decl s))::ctx in 
1803                      let subst,metasenv,ugraph,t = aux ctx (k+1) subst t in
1804                      subst,metasenv,ugraph,Cic.Prod (name,s,t)
1805                  | _ -> 
1806                      raise 
1807                       (RefineFailure 
1808                         (lazy "not well formed constructor type"))
1809                in
1810                let subst,metasenv,ugraph,ty = aux [] 0 subst ty in  
1811                subst,metasenv,ugraph,(name,ty) :: acc)
1812           cl (subst,metasenv,ugraph,[])
1813         in 
1814         subst,metasenv,ugraph,(name,ind,arity,cl)::acc)
1815       tys ([],metasenv,ugraph,[])
1816   in
1817   let substituted_tys = 
1818     List.map 
1819       (fun (name,ind,arity,cl) -> 
1820         let cl = 
1821           List.map (fun (name, ty) -> name,CicMetaSubst.apply_subst subst ty) cl
1822         in
1823         name,ind,CicMetaSubst.apply_subst subst arity,cl)
1824       tys 
1825   in
1826   metasenv,ugraph,substituted_tys
1827     
1828 let typecheck metasenv uri obj ~localization_tbl =
1829  let ugraph = CicUniv.empty_ugraph in
1830  match obj with
1831     Cic.Constant (name,Some bo,ty,args,attrs) ->
1832      let bo',boty,metasenv,ugraph =
1833       type_of_aux' ~localization_tbl metasenv [] bo ugraph in
1834      let ty',_,metasenv,ugraph =
1835       type_of_aux' ~localization_tbl metasenv [] ty ugraph in
1836      let subst,metasenv,ugraph = fo_unif_subst [] [] metasenv boty ty' ugraph in
1837      let bo' = CicMetaSubst.apply_subst subst bo' in
1838      let ty' = CicMetaSubst.apply_subst subst ty' in
1839      let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
1840       Cic.Constant (name,Some bo',ty',args,attrs),metasenv,ugraph
1841   | Cic.Constant (name,None,ty,args,attrs) ->
1842      let ty',_,metasenv,ugraph =
1843       type_of_aux' ~localization_tbl metasenv [] ty ugraph
1844      in
1845       Cic.Constant (name,None,ty',args,attrs),metasenv,ugraph
1846   | Cic.CurrentProof (name,metasenv',bo,ty,args,attrs) ->
1847      assert (metasenv' = metasenv);
1848      (* Here we do not check the metasenv for correctness *)
1849      let bo',boty,metasenv,ugraph =
1850       type_of_aux' ~localization_tbl metasenv [] bo ugraph in
1851      let ty',sort,metasenv,ugraph =
1852       type_of_aux' ~localization_tbl metasenv [] ty ugraph in
1853      begin
1854       match sort with
1855          Cic.Sort _
1856        (* instead of raising Uncertain, let's hope that the meta will become
1857           a sort *)
1858        | Cic.Meta _ -> ()
1859        | _ -> raise (RefineFailure (lazy "The term provided is not a type"))
1860      end;
1861      let subst,metasenv,ugraph = fo_unif_subst [] [] metasenv boty ty' ugraph in
1862      let bo' = CicMetaSubst.apply_subst subst bo' in
1863      let ty' = CicMetaSubst.apply_subst subst ty' in
1864      let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
1865       Cic.CurrentProof (name,metasenv,bo',ty',args,attrs),metasenv,ugraph
1866   | Cic.Variable _ -> assert false (* not implemented *)
1867   | Cic.InductiveDefinition (tys,args,paramsno,attrs) ->
1868      (*CSC: this code is greately simplified and many many checks are missing *)
1869      (*CSC: e.g. the constructors are not required to build their own types,  *)
1870      (*CSC: the arities are not required to have as type a sort, etc.         *)
1871      let uri = match uri with Some uri -> uri | None -> assert false in
1872      let typesno = List.length tys in
1873      (* first phase: we fix only the types *)
1874      let metasenv,ugraph,tys =
1875       List.fold_right
1876        (fun (name,b,ty,cl) (metasenv,ugraph,res) ->
1877          let ty',_,metasenv,ugraph =
1878           type_of_aux' ~localization_tbl metasenv [] ty ugraph
1879          in
1880           metasenv,ugraph,(name,b,ty',cl)::res
1881        ) tys (metasenv,ugraph,[]) in
1882      let con_context =
1883       List.rev_map (fun (name,_,ty,_)-> Some (Cic.Name name,Cic.Decl ty)) tys in
1884      (* second phase: we fix only the constructors *)
1885      let saved_menv = metasenv in
1886      let metasenv,ugraph,tys =
1887       List.fold_right
1888        (fun (name,b,ty,cl) (metasenv,ugraph,res) ->
1889          let metasenv,ugraph,cl' =
1890           List.fold_right
1891            (fun (name,ty) (metasenv,ugraph,res) ->
1892              let ty =
1893               CicTypeChecker.debrujin_constructor
1894                ~cb:(relocalize localization_tbl) uri typesno ty in
1895              let ty',_,metasenv,ugraph =
1896               type_of_aux' ~localization_tbl metasenv con_context ty ugraph in
1897              let ty' = undebrujin uri typesno tys ty' in
1898               metasenv@saved_menv,ugraph,(name,ty')::res
1899            ) cl (metasenv,ugraph,[])
1900          in
1901           metasenv,ugraph,(name,b,ty,cl')::res
1902        ) tys (metasenv,ugraph,[]) in
1903      (* third phase: we check the positivity condition *)
1904      let metasenv,ugraph,tys = 
1905        are_all_occurrences_positive metasenv ugraph uri tys paramsno 
1906      in
1907      Cic.InductiveDefinition (tys,args,paramsno,attrs),metasenv,ugraph
1908 ;;
1909
1910 (* sara' piu' veloce che raffinare da zero? mah.... *)
1911 let pack_coercion metasenv ctx t =
1912  let module C = Cic in
1913  let rec merge_coercions ctx =
1914    let aux = (fun (u,t) -> u,merge_coercions ctx t) in
1915    function
1916    | C.Rel _ | C.Sort _ | C.Implicit _ as t -> t
1917    | C.Meta (n,subst) ->
1918       let subst' =
1919        List.map
1920         (function None -> None | Some t -> Some (merge_coercions ctx t)) subst
1921       in
1922        C.Meta (n,subst')
1923    | C.Cast (te,ty) -> C.Cast (merge_coercions ctx te, merge_coercions ctx ty)
1924    | C.Prod (name,so,dest) -> 
1925        let ctx' = (Some (name,C.Decl so))::ctx in
1926        C.Prod (name, merge_coercions ctx so, merge_coercions ctx' dest) 
1927    | C.Lambda (name,so,dest) -> 
1928        let ctx' = (Some (name,C.Decl so))::ctx in
1929        C.Lambda (name, merge_coercions ctx so, merge_coercions ctx' dest)
1930    | C.LetIn (name,so,dest) -> 
1931        let _,ty,metasenv,ugraph =
1932         pack_coercions := false;
1933         type_of_aux' metasenv ctx so CicUniv.oblivion_ugraph in
1934         pack_coercions := true;
1935        let ctx' = Some (name,(C.Def (so,Some ty)))::ctx in
1936        C.LetIn (name, merge_coercions ctx so, merge_coercions ctx' dest)
1937    | C.Appl l -> 
1938       let l = List.map (merge_coercions ctx) l in
1939       let t = C.Appl l in
1940        let b,_,_,_,_ = is_a_double_coercion t in
1941        if b then
1942          let ugraph = CicUniv.oblivion_ugraph in
1943          let old_insert_coercions = !insert_coercions in
1944          insert_coercions := false;
1945          let newt, _, menv, _ = 
1946            try 
1947              type_of_aux' metasenv ctx t ugraph 
1948            with RefineFailure _ | Uncertain _ -> 
1949              t, t, [], ugraph 
1950          in
1951          insert_coercions := old_insert_coercions;
1952          if metasenv <> [] || menv = [] then 
1953            newt 
1954          else 
1955            (prerr_endline "PUO' SUCCEDERE!!!!!";t)
1956        else
1957          t
1958    | C.Var (uri,exp_named_subst) -> 
1959        let exp_named_subst = List.map aux exp_named_subst in
1960        C.Var (uri, exp_named_subst)
1961    | C.Const (uri,exp_named_subst) ->
1962        let exp_named_subst = List.map aux exp_named_subst in
1963        C.Const (uri, exp_named_subst)
1964    | C.MutInd (uri,tyno,exp_named_subst) ->
1965        let exp_named_subst = List.map aux exp_named_subst in
1966        C.MutInd (uri,tyno,exp_named_subst)
1967    | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
1968        let exp_named_subst = List.map aux exp_named_subst in
1969        C.MutConstruct (uri,tyno,consno,exp_named_subst)  
1970    | C.MutCase (uri,tyno,out,te,pl) ->
1971        let pl = List.map (merge_coercions ctx) pl in
1972        C.MutCase (uri,tyno,merge_coercions ctx out, merge_coercions ctx te, pl)
1973    | C.Fix (fno, fl) ->
1974        let ctx' =
1975          List.fold_left
1976            (fun l (n,_,ty,_) -> (Some (C.Name n,C.Decl ty))::l) 
1977            ctx fl
1978        in 
1979        let fl = 
1980          List.map 
1981            (fun (name,idx,ty,bo) -> 
1982              (name,idx,merge_coercions ctx ty,merge_coercions ctx' bo)) 
1983          fl
1984        in
1985        C.Fix (fno, fl)
1986    | C.CoFix (fno, fl) ->
1987        let ctx' =
1988          List.fold_left
1989            (fun l (n,ty,_) -> (Some (C.Name n,C.Decl ty))::l) 
1990            ctx fl
1991        in 
1992        let fl = 
1993          List.map 
1994            (fun (name,ty,bo) -> 
1995              (name, merge_coercions ctx ty, merge_coercions ctx' bo)) 
1996          fl 
1997        in
1998        C.CoFix (fno, fl)
1999  in
2000   merge_coercions ctx t
2001 ;;
2002
2003 let pack_coercion_metasenv conjectures = conjectures (*
2004
2005   TASSI: this code war written when coercions were a toy,
2006          now packing coercions involves unification thus
2007          the metasenv may change, and this pack coercion 
2008          does not handle that.
2009
2010   let module C = Cic in
2011   List.map 
2012     (fun (i, ctx, ty) -> 
2013        let ctx = 
2014          List.fold_right 
2015            (fun item ctx ->
2016               let item' =
2017                 match item with
2018                     Some (name, C.Decl t) -> 
2019                       Some (name, C.Decl (pack_coercion conjectures ctx t))
2020                   | Some (name, C.Def (t,None)) -> 
2021                       Some (name,C.Def (pack_coercion conjectures ctx t,None))
2022                   | Some (name, C.Def (t,Some ty)) -> 
2023                       Some (name, C.Def (pack_coercion conjectures ctx t, 
2024                                          Some (pack_coercion conjectures ctx ty)))
2025                   | None -> None
2026               in
2027                 item'::ctx
2028            ) ctx []
2029        in
2030          ((i,ctx,pack_coercion conjectures ctx ty))
2031     ) conjectures
2032     *)
2033 ;;
2034
2035 let pack_coercion_obj obj = obj (*
2036
2037   TASSI: this code war written when coercions were a toy,
2038          now packing coercions involves unification thus
2039          the metasenv may change, and this pack coercion 
2040          does not handle that.
2041
2042   let module C = Cic in
2043   match obj with
2044   | C.Constant (id, body, ty, params, attrs) -> 
2045       let body = 
2046         match body with 
2047         | None -> None 
2048         | Some body -> Some (pack_coercion [] [] body) 
2049       in
2050       let ty = pack_coercion [] [] ty in
2051         C.Constant (id, body, ty, params, attrs)
2052   | C.Variable (name, body, ty, params, attrs) ->
2053       let body = 
2054         match body with 
2055         | None -> None 
2056         | Some body -> Some (pack_coercion [] [] body) 
2057       in
2058       let ty = pack_coercion [] [] ty in
2059         C.Variable (name, body, ty, params, attrs)
2060   | C.CurrentProof (name, conjectures, body, ty, params, attrs) ->
2061       let conjectures = pack_coercion_metasenv conjectures in
2062       let body = pack_coercion conjectures [] body in
2063       let ty = pack_coercion conjectures [] ty in
2064       C.CurrentProof (name, conjectures, body, ty, params, attrs)
2065   | C.InductiveDefinition (indtys, params, leftno, attrs) ->
2066       let indtys = 
2067         List.map 
2068           (fun (name, ind, arity, cl) -> 
2069             let arity = pack_coercion [] [] arity in
2070             let cl = 
2071               List.map (fun (name, ty) -> (name,pack_coercion [] [] ty)) cl 
2072             in
2073             (name, ind, arity, cl))
2074           indtys
2075       in
2076         C.InductiveDefinition (indtys, params, leftno, attrs) *)
2077 ;;
2078
2079
2080 (* DEBUGGING ONLY 
2081 let type_of_aux' metasenv context term =
2082  try
2083   let (t,ty,m) = 
2084       type_of_aux' metasenv context term in
2085     debug_print (lazy
2086      ("@@@ REFINE SUCCESSFUL: " ^ CicPp.ppterm t ^ " : " ^ CicPp.ppterm ty));
2087    debug_print (lazy
2088     ("@@@ REFINE SUCCESSFUL (metasenv):\n" ^ CicMetaSubst.ppmetasenv ~sep:";" m []));
2089    (t,ty,m)
2090  with
2091  | RefineFailure msg as e ->
2092      debug_print (lazy ("@@@ REFINE FAILED: " ^ msg));
2093      raise e
2094  | Uncertain msg as e ->
2095      debug_print (lazy ("@@@ REFINE UNCERTAIN: " ^ msg));
2096      raise e
2097 ;; *)
2098
2099 let profiler2 = HExtlib.profile "CicRefine"
2100
2101 let type_of_aux' ?localization_tbl metasenv context term ugraph =
2102  profiler2.HExtlib.profile
2103   (type_of_aux' ?localization_tbl metasenv context term) ugraph
2104
2105 let typecheck ~localization_tbl metasenv uri obj =
2106  profiler2.HExtlib.profile (typecheck ~localization_tbl metasenv uri) obj
2107
2108 let _ = DoubleTypeInference.pack_coercion := pack_coercion;;
2109 (* vim:set foldmethod=marker: *)