]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_acic/doubleTypeInference.ml
test branch
[helm.git] / helm / ocaml / cic_acic / doubleTypeInference.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 exception Impossible of int;;
29 exception NotWellTyped of string;;
30 exception WrongUriToConstant of string;;
31 exception WrongUriToVariable of string;;
32 exception WrongUriToMutualInductiveDefinitions of string;;
33 exception ListTooShort;;
34 exception RelToHiddenHypothesis;;
35
36 let syntactic_equality_add_time = ref 0.0;;
37 let type_of_aux'_add_time = ref 0.0;;
38 let number_new_type_of_aux'_double_work = ref 0;;
39 let number_new_type_of_aux' = ref 0;;
40 let number_new_type_of_aux'_prop = ref 0;;
41
42 let double_work = ref 0;;
43
44 let xxx_type_of_aux' m c t =
45  let t1 = Sys.time () in
46  let res,_ = CicTypeChecker.type_of_aux' m c t CicUniv.empty_ugraph in
47  let t2 = Sys.time () in
48  type_of_aux'_add_time := !type_of_aux'_add_time +. t2 -. t1 ;
49  res
50 ;;
51
52 type types = {synthesized : Cic.term ; expected : Cic.term option};;
53
54 (* does_not_occur n te                              *)
55 (* returns [true] if [Rel n] does not occur in [te] *)
56 let rec does_not_occur n =
57  let module C = Cic in
58   function
59      C.Rel m when m = n -> false
60    | C.Rel _
61    | C.Meta _
62    | C.Sort _
63    | C.Implicit _ -> true 
64    | C.Cast (te,ty) ->
65       does_not_occur n te && does_not_occur n ty
66    | C.Prod (name,so,dest) ->
67       does_not_occur n so &&
68        does_not_occur (n + 1) dest
69    | C.Lambda (name,so,dest) ->
70       does_not_occur n so &&
71        does_not_occur (n + 1) dest
72    | C.LetIn (name,so,dest) ->
73       does_not_occur n so &&
74        does_not_occur (n + 1) dest
75    | C.Appl l ->
76       List.fold_right (fun x i -> i && does_not_occur n x) l true
77    | C.Var (_,exp_named_subst)
78    | C.Const (_,exp_named_subst)
79    | C.MutInd (_,_,exp_named_subst)
80    | C.MutConstruct (_,_,_,exp_named_subst) ->
81       List.fold_right (fun (_,x) i -> i && does_not_occur n x)
82        exp_named_subst true
83    | C.MutCase (_,_,out,te,pl) ->
84       does_not_occur n out && does_not_occur n te &&
85        List.fold_right (fun x i -> i && does_not_occur n x) pl true
86    | C.Fix (_,fl) ->
87       let len = List.length fl in
88        let n_plus_len = n + len in
89         List.fold_right
90          (fun (_,_,ty,bo) i ->
91            i && does_not_occur n ty &&
92            does_not_occur n_plus_len bo
93          ) fl true
94    | C.CoFix (_,fl) ->
95       let len = List.length fl in
96        let n_plus_len = n + len in
97         List.fold_right
98          (fun (_,ty,bo) i ->
99            i && does_not_occur n ty &&
100            does_not_occur n_plus_len bo
101          ) fl true
102 ;;
103
104 let rec beta_reduce =
105  let module S = CicSubstitution in
106  let module C = Cic in
107   function
108       C.Rel _ as t -> t
109     | C.Var (uri,exp_named_subst) ->
110        let exp_named_subst' =
111         List.map (function (i,t) -> i, beta_reduce t) exp_named_subst
112        in
113         C.Var (uri,exp_named_subst')
114     | C.Meta (n,l) ->
115        C.Meta (n,
116         List.map
117          (function None -> None | Some t -> Some (beta_reduce t)) l
118        )
119     | C.Sort _ as t -> t
120     | C.Implicit _ -> assert false
121     | C.Cast (te,ty) ->
122        C.Cast (beta_reduce te, beta_reduce ty)
123     | C.Prod (n,s,t) ->
124        C.Prod (n, beta_reduce s, beta_reduce t)
125     | C.Lambda (n,s,t) ->
126        C.Lambda (n, beta_reduce s, beta_reduce t)
127     | C.LetIn (n,s,t) ->
128        C.LetIn (n, beta_reduce s, beta_reduce t)
129     | C.Appl ((C.Lambda (name,s,t))::he::tl) ->
130        let he' = S.subst he t in
131         if tl = [] then
132          beta_reduce he'
133         else
134          (match he' with
135              C.Appl l -> beta_reduce (C.Appl (l@tl))
136            | _ -> beta_reduce (C.Appl (he'::tl)))
137     | C.Appl l ->
138        C.Appl (List.map beta_reduce l)
139     | C.Const (uri,exp_named_subst) ->
140        let exp_named_subst' =
141         List.map (function (i,t) -> i, beta_reduce t) exp_named_subst
142        in
143         C.Const (uri,exp_named_subst')
144     | C.MutInd (uri,i,exp_named_subst) ->
145        let exp_named_subst' =
146         List.map (function (i,t) -> i, beta_reduce t) exp_named_subst
147        in
148         C.MutInd (uri,i,exp_named_subst')
149     | C.MutConstruct (uri,i,j,exp_named_subst) ->
150        let exp_named_subst' =
151         List.map (function (i,t) -> i, beta_reduce t) exp_named_subst
152        in
153         C.MutConstruct (uri,i,j,exp_named_subst')
154     | C.MutCase (sp,i,outt,t,pl) ->
155        C.MutCase (sp,i,beta_reduce outt,beta_reduce t,
156         List.map beta_reduce pl)
157     | C.Fix (i,fl) ->
158        let fl' =
159         List.map
160          (function (name,i,ty,bo) ->
161            name,i,beta_reduce ty,beta_reduce bo
162          ) fl
163        in
164         C.Fix (i,fl')
165     | C.CoFix (i,fl) ->
166        let fl' =
167         List.map
168          (function (name,ty,bo) ->
169            name,beta_reduce ty,beta_reduce bo
170          ) fl
171        in
172         C.CoFix (i,fl')
173 ;;
174
175 (* syntactic_equality up to the                 *)
176 (* distinction between fake dependent products  *)
177 (* and non-dependent products, alfa-conversion  *)
178 (*CSC: must alfa-conversion be considered or not? *)
179 let syntactic_equality t t' =
180  let module C = Cic in
181  let rec syntactic_equality t t' =
182   if t = t' then true
183   else
184    match t, t' with
185       C.Var (uri,exp_named_subst), C.Var (uri',exp_named_subst') ->
186        UriManager.eq uri uri' &&
187         syntactic_equality_exp_named_subst exp_named_subst exp_named_subst'
188     | C.Cast (te,ty), C.Cast (te',ty') ->
189        syntactic_equality te te' &&
190         syntactic_equality ty ty'
191     | C.Prod (_,s,t), C.Prod (_,s',t') ->
192        syntactic_equality s s' &&
193         syntactic_equality t t'
194     | C.Lambda (_,s,t), C.Lambda (_,s',t') ->
195        syntactic_equality s s' &&
196         syntactic_equality t t'
197     | C.LetIn (_,s,t), C.LetIn(_,s',t') ->
198        syntactic_equality s s' &&
199         syntactic_equality t t'
200     | C.Appl l, C.Appl l' ->
201        List.fold_left2 (fun b t1 t2 -> b && syntactic_equality t1 t2) true l l'
202     | C.Const (uri,exp_named_subst), C.Const (uri',exp_named_subst') ->
203        UriManager.eq uri uri' &&
204         syntactic_equality_exp_named_subst exp_named_subst exp_named_subst'
205     | C.MutInd (uri,i,exp_named_subst), C.MutInd (uri',i',exp_named_subst') ->
206        UriManager.eq uri uri' && i = i' &&
207         syntactic_equality_exp_named_subst exp_named_subst exp_named_subst'
208     | C.MutConstruct (uri,i,j,exp_named_subst),
209       C.MutConstruct (uri',i',j',exp_named_subst') ->
210        UriManager.eq uri uri' && i = i' && j = j' &&
211         syntactic_equality_exp_named_subst exp_named_subst exp_named_subst'
212     | C.MutCase (sp,i,outt,t,pl), C.MutCase (sp',i',outt',t',pl') ->
213        UriManager.eq sp sp' && i = i' &&
214         syntactic_equality outt outt' &&
215          syntactic_equality t t' &&
216           List.fold_left2
217            (fun b t1 t2 -> b && syntactic_equality t1 t2) true pl pl'
218     | C.Fix (i,fl), C.Fix (i',fl') ->
219        i = i' &&
220         List.fold_left2
221          (fun b (_,i,ty,bo) (_,i',ty',bo') ->
222            b && i = i' &&
223             syntactic_equality ty ty' &&
224              syntactic_equality bo bo') true fl fl'
225     | C.CoFix (i,fl), C.CoFix (i',fl') ->
226        i = i' &&
227         List.fold_left2
228          (fun b (_,ty,bo) (_,ty',bo') ->
229            b &&
230             syntactic_equality ty ty' &&
231              syntactic_equality bo bo') true fl fl'
232     | _, _ -> false (* we already know that t != t' *)
233  and syntactic_equality_exp_named_subst exp_named_subst1 exp_named_subst2 =
234   List.fold_left2
235    (fun b (_,t1) (_,t2) -> b && syntactic_equality t1 t2) true
236    exp_named_subst1 exp_named_subst2
237  in
238   try
239    syntactic_equality t t'
240   with
241    _ -> false
242 ;;
243
244 let xxx_syntactic_equality t t' =
245  let t1 = Sys.time () in
246  let res = syntactic_equality t t' in
247  let t2 = Sys.time () in
248  syntactic_equality_add_time := !syntactic_equality_add_time +. t2 -. t1 ;
249  res
250 ;;
251
252
253 let rec split l n =
254  match (l,n) with
255     (l,0) -> ([], l)
256   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
257   | (_,_) -> raise ListTooShort
258 ;;
259
260 let type_of_constant uri =
261  let module C = Cic in
262  let module R = CicReduction in
263  let module U = UriManager in
264   let cobj =
265    match CicEnvironment.is_type_checked CicUniv.empty_ugraph uri with
266       CicEnvironment.CheckedObj (cobj,_) -> cobj
267     | CicEnvironment.UncheckedObj uobj ->
268        raise (NotWellTyped "Reference to an unchecked constant")
269   in
270    match cobj with
271       C.Constant (_,_,ty,_,_) -> ty
272     | C.CurrentProof (_,_,_,ty,_,_) -> ty
273     | _ -> raise (WrongUriToConstant (U.string_of_uri uri))
274 ;;
275
276 let type_of_variable uri =
277  let module C = Cic in
278  let module R = CicReduction in
279  let module U = UriManager in
280   match CicEnvironment.is_type_checked CicUniv.empty_ugraph uri with
281      CicEnvironment.CheckedObj ((C.Variable (_,_,ty,_,_)),_) -> ty
282    | CicEnvironment.UncheckedObj (C.Variable _) ->
283       raise (NotWellTyped "Reference to an unchecked variable")
284    |  _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
285 ;;
286
287 let type_of_mutual_inductive_defs uri i =
288  let module C = Cic in
289  let module R = CicReduction in
290  let module U = UriManager in
291   let cobj =
292    match CicEnvironment.is_type_checked CicUniv.empty_ugraph uri with
293       CicEnvironment.CheckedObj (cobj,_) -> cobj
294     | CicEnvironment.UncheckedObj uobj ->
295        raise (NotWellTyped "Reference to an unchecked inductive type")
296   in
297    match cobj with
298       C.InductiveDefinition (dl,_,_,_) ->
299        let (_,_,arity,_) = List.nth dl i in
300         arity
301     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
302 ;;
303
304 let type_of_mutual_inductive_constr uri i j =
305  let module C = Cic in
306  let module R = CicReduction in
307  let module U = UriManager in
308   let cobj =
309    match CicEnvironment.is_type_checked CicUniv.empty_ugraph uri with
310       CicEnvironment.CheckedObj (cobj,_) -> cobj
311     | CicEnvironment.UncheckedObj uobj ->
312        raise (NotWellTyped "Reference to an unchecked constructor")
313   in
314    match cobj with
315       C.InductiveDefinition (dl,_,_,_) ->
316        let (_,_,_,cl) = List.nth dl i in
317         let (_,ty) = List.nth cl (j-1) in
318          ty
319     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
320 ;;
321
322 (* type_of_aux' is just another name (with a different scope) for type_of_aux *)
323 let rec type_of_aux' subterms_to_types metasenv context t expectedty =
324  (* Coscoy's double type-inference algorithm             *)
325  (* It computes the inner-types of every subterm of [t], *)
326  (* even when they are not needed to compute the types   *)
327  (* of other terms.                                      *)
328  let rec type_of_aux context t expectedty =
329   let module C = Cic in
330   let module R = CicReduction in
331   let module S = CicSubstitution in
332   let module U = UriManager in
333    let synthesized =
334     match t with
335        C.Rel n ->
336         (try
337           match List.nth context (n - 1) with
338              Some (_,C.Decl t) -> S.lift n t
339            | Some (_,C.Def (_,Some ty)) -> S.lift n ty
340            | Some (_,C.Def (bo,None)) ->
341               type_of_aux context (S.lift n bo) expectedty
342                  | None -> raise RelToHiddenHypothesis
343          with
344           _ -> raise (NotWellTyped "Not a close term")
345         )
346      | C.Var (uri,exp_named_subst) ->
347         visit_exp_named_subst context uri exp_named_subst ;
348         CicSubstitution.subst_vars exp_named_subst (type_of_variable uri)
349      | C.Meta (n,l) -> 
350         (* Let's visit all the subterms that will not be visited later *)
351         let (_,canonical_context,_) = CicUtil.lookup_meta n metasenv in
352          let lifted_canonical_context =
353           let rec aux i =
354            function
355               [] -> []
356             | (Some (n,C.Decl t))::tl ->
357                (Some (n,C.Decl (S.subst_meta l (S.lift i t))))::(aux (i+1) tl)
358             | (Some (n,C.Def (t,None)))::tl ->
359                (Some (n,C.Def ((S.subst_meta l (S.lift i t)),None)))::
360                 (aux (i+1) tl)
361             | None::tl -> None::(aux (i+1) tl)
362             | (Some (_,C.Def (_,Some _)))::_ -> assert false
363           in
364            aux 1 canonical_context
365          in
366           let _ =
367            List.iter2
368             (fun t ct ->
369               match t,ct with
370                  _,None -> ()
371                | Some t,Some (_,C.Def (ct,_)) ->
372                   let expected_type =
373                    R.whd context
374                     (xxx_type_of_aux' metasenv context ct)
375                   in
376                    (* Maybe I am a bit too paranoid, because   *)
377                    (* if the term is well-typed than t and ct  *)
378                    (* are convertible. Nevertheless, I compute *)
379                    (* the expected type.                       *)
380                    ignore (type_of_aux context t (Some expected_type))
381                | Some t,Some (_,C.Decl ct) ->
382                   ignore (type_of_aux context t (Some ct))
383                | _,_ -> assert false (* the term is not well typed!!! *)
384             ) l lifted_canonical_context
385           in
386            let (_,canonical_context,ty) = CicUtil.lookup_meta n metasenv in
387             (* Checks suppressed *)
388             CicSubstitution.subst_meta l ty
389      | C.Sort (C.Type t) -> (* TASSI: CONSTRAINT *)
390          C.Sort (C.Type (CicUniv.fresh()))
391      | C.Sort _ -> C.Sort (C.Type (CicUniv.fresh())) (* TASSI: CONSTRAINT *)
392      | C.Implicit _ -> raise (Impossible 21)
393      | C.Cast (te,ty) ->
394         (* Let's visit all the subterms that will not be visited later *)
395         let _ = type_of_aux context te (Some (beta_reduce ty)) in
396         let _ = type_of_aux context ty None in
397          (* Checks suppressed *)
398          ty
399      | C.Prod (name,s,t) ->
400         let sort1 = type_of_aux context s None
401         and sort2 = type_of_aux ((Some (name,(C.Decl s)))::context) t None in
402          sort_of_prod context (name,s) (sort1,sort2)
403      | C.Lambda (n,s,t) ->
404         (* Let's visit all the subterms that will not be visited later *)
405          let _ = type_of_aux context s None in 
406          let expected_target_type =
407           match expectedty with
408              None -> None
409            | Some expectedty' ->
410               let ty =
411                match R.whd context expectedty' with
412                   C.Prod (_,_,expected_target_type) ->
413                    beta_reduce expected_target_type
414                 | _ -> assert false
415               in
416                Some ty
417          in 
418           let type2 =
419            type_of_aux ((Some (n,(C.Decl s)))::context) t expected_target_type
420           in
421            (* Checks suppressed *)
422            C.Prod (n,s,type2)
423      | C.LetIn (n,s,t) ->
424 (*CSC: What are the right expected types for the source and *)
425 (*CSC: target of a LetIn? None used.                        *)
426         (* Let's visit all the subterms that will not be visited later *)
427         let ty = type_of_aux context s None in
428          let t_typ =
429           (* Checks suppressed *)
430           type_of_aux ((Some (n,(C.Def (s,Some ty))))::context) t None
431          in  (* CicSubstitution.subst s t_typ *)
432           if does_not_occur 1 t_typ then
433            (* since [Rel 1] does not occur in typ, substituting any term *)
434            (* in place of [Rel 1] is equivalent to delifting once        *)
435            CicSubstitution.subst (C.Implicit None) t_typ
436           else
437            C.LetIn (n,s,t_typ)
438      | C.Appl (he::tl) when List.length tl > 0 ->
439         (* 
440         let expected_hetype =
441          (* Inefficient, the head is computed twice. But I know *)
442          (* of no other solution. *)                               
443          (beta_reduce
444           (R.whd context (xxx_type_of_aux' metasenv context he)))
445         in 
446          let hetype = type_of_aux context he (Some expected_hetype) in 
447          let tlbody_and_type =
448           let rec aux =
449            function
450               _,[] -> []
451             | C.Prod (n,s,t),he::tl ->
452                (he, type_of_aux context he (Some (beta_reduce s)))::
453                 (aux (R.whd context (S.subst he t), tl))
454             | _ -> assert false
455           in
456            aux (expected_hetype, tl) *)
457          let hetype = R.whd context (type_of_aux context he None) in 
458          let tlbody_and_type =
459           let rec aux =
460            function
461               _,[] -> []
462             | C.Prod (n,s,t),he::tl ->
463                (he, type_of_aux context he (Some (beta_reduce s)))::
464                 (aux (R.whd context (S.subst he t), tl))
465             | _ -> assert false
466           in
467            aux (hetype, tl)
468          in
469           eat_prods context hetype tlbody_and_type
470      | C.Appl _ -> raise (NotWellTyped "Appl: no arguments")
471      | C.Const (uri,exp_named_subst) ->
472         visit_exp_named_subst context uri exp_named_subst ;
473         CicSubstitution.subst_vars exp_named_subst (type_of_constant uri)
474      | C.MutInd (uri,i,exp_named_subst) ->
475         visit_exp_named_subst context uri exp_named_subst ;
476         CicSubstitution.subst_vars exp_named_subst
477          (type_of_mutual_inductive_defs uri i)
478      | C.MutConstruct (uri,i,j,exp_named_subst) ->
479         visit_exp_named_subst context uri exp_named_subst ;
480         CicSubstitution.subst_vars exp_named_subst
481          (type_of_mutual_inductive_constr uri i j)
482      | C.MutCase (uri,i,outtype,term,pl) ->
483         let outsort = type_of_aux context outtype None in
484         let (need_dummy, k) =
485          let rec guess_args context t =
486           match CicReduction.whd context t with
487              C.Sort _ -> (true, 0)
488            | C.Prod (name, s, t) ->
489               let (b, n) = guess_args ((Some (name,(C.Decl s)))::context) t in
490                if n = 0 then
491                 (* last prod before sort *)
492                 match CicReduction.whd context s with
493                    C.MutInd (uri',i',_) when U.eq uri' uri && i' = i ->
494                     (false, 1)
495                  | C.Appl ((C.MutInd (uri',i',_)) :: _)
496                     when U.eq uri' uri && i' = i -> (false, 1)
497                  | _ -> (true, 1)
498                else
499                 (b, n + 1)
500            | _ -> raise (NotWellTyped "MutCase: outtype ill-formed")
501          in
502           let (b, k) = guess_args context outsort in
503            if not b then (b, k - 1) else (b, k)
504         in
505         let (parameters, arguments,exp_named_subst) =
506          let type_of_term =
507           xxx_type_of_aux' metasenv context term
508          in
509           match
510            R.whd context (type_of_aux context term
511             (Some (beta_reduce type_of_term)))
512           with
513              (*CSC manca il caso dei CAST *)
514              C.MutInd (uri',i',exp_named_subst) ->
515               (* Checks suppressed *)
516               [],[],exp_named_subst
517            | C.Appl (C.MutInd (uri',i',exp_named_subst) :: tl) ->
518              let params,args =
519               split tl (List.length tl - k)
520              in params,args,exp_named_subst
521            | _ ->
522              raise (NotWellTyped "MutCase: the term is not an inductive one")
523         in
524          (* Checks suppressed *)
525          (* Let's visit all the subterms that will not be visited later *)
526          let (cl,parsno) =
527            let obj,_ =
528              try
529                CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
530              with Not_found -> assert false
531            in
532           match obj with
533              C.InductiveDefinition (tl,_,parsno,_) ->
534               let (_,_,_,cl) = List.nth tl i in (cl,parsno)
535            | _ ->
536              raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
537          in
538           let _ =
539            List.fold_left
540             (fun j (p,(_,c)) ->
541               let cons =
542                if parameters = [] then
543                 (C.MutConstruct (uri,i,j,exp_named_subst))
544                else
545                 (C.Appl (C.MutConstruct (uri,i,j,exp_named_subst)::parameters))
546               in
547                let expectedtype =
548                 type_of_branch context parsno need_dummy outtype cons
549                   (xxx_type_of_aux' metasenv context cons)
550                in
551                 ignore (type_of_aux context p
552                  (Some (beta_reduce expectedtype))) ;
553                 j+1
554             ) 1 (List.combine pl cl)
555           in
556            if not need_dummy then
557             C.Appl ((outtype::arguments)@[term])
558            else if arguments = [] then
559             outtype
560            else
561             C.Appl (outtype::arguments)
562      | C.Fix (i,fl) ->
563         (* Let's visit all the subterms that will not be visited later *)
564         let context' =
565          List.rev
566           (List.map
567             (fun (n,_,ty,_) ->
568               let _ = type_of_aux context ty None in
569                (Some (C.Name n,(C.Decl ty)))
570             ) fl
571           ) @
572           context
573         in
574          let _ =
575           List.iter
576            (fun (_,_,ty,bo) ->
577              let expectedty =
578               beta_reduce (CicSubstitution.lift (List.length fl) ty)
579              in
580               ignore (type_of_aux context' bo (Some expectedty))
581            ) fl
582          in
583           (* Checks suppressed *)
584           let (_,_,ty,_) = List.nth fl i in
585            ty
586      | C.CoFix (i,fl) ->
587         (* Let's visit all the subterms that will not be visited later *)
588         let context' =
589          List.rev
590           (List.map
591             (fun (n,ty,_) ->
592               let _ = type_of_aux context ty None in
593                (Some (C.Name n,(C.Decl ty)))
594             ) fl
595           ) @
596           context
597         in
598          let _ =
599           List.iter
600            (fun (_,ty,bo) ->
601              let expectedty =
602               beta_reduce (CicSubstitution.lift (List.length fl) ty)
603              in
604               ignore (type_of_aux context' bo (Some expectedty))
605            ) fl
606          in
607           (* Checks suppressed *)
608           let (_,ty,_) = List.nth fl i in
609            ty
610    in
611     let synthesized' = beta_reduce synthesized in
612      let types,res =
613       match expectedty with
614          None ->
615           (* No expected type *)
616           {synthesized = synthesized' ; expected = None}, synthesized
617        | Some ty when xxx_syntactic_equality synthesized' ty ->
618           (* The expected type is synthactically equal to *)
619           (* the synthesized type. Let's forget it.       *)
620           {synthesized = synthesized' ; expected = None}, synthesized
621        | Some expectedty' ->
622           {synthesized = synthesized' ; expected = Some expectedty'},
623           expectedty'
624      in
625       assert (not (Cic.CicHash.mem subterms_to_types t));
626       Cic.CicHash.add subterms_to_types t types ;
627       res
628
629  and visit_exp_named_subst context uri exp_named_subst =
630   let uris_and_types =
631      let obj,_ =
632        try
633          CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
634        with Not_found -> assert false
635      in
636     let params = CicUtil.params_of_obj obj in
637      List.map
638       (function uri ->
639          let obj,_ =
640            try
641              CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
642            with Not_found -> assert false
643          in
644          match obj with
645            Cic.Variable (_,None,ty,_,_) -> uri,ty
646          | _ -> assert false (* the theorem is well-typed *)
647       ) params
648   in
649    let rec check uris_and_types subst =
650     match uris_and_types,subst with
651        _,[] -> []
652      | (uri,ty)::tytl,(uri',t)::substtl when uri = uri' ->
653         ignore (type_of_aux context t (Some ty)) ;
654         let tytl' =
655          List.map
656           (function uri,t' -> uri,(CicSubstitution.subst_vars [uri',t] t')) tytl
657         in
658          check tytl' substtl
659      | _,_ -> assert false (* the theorem is well-typed *)
660    in
661     check uris_and_types exp_named_subst
662
663  and sort_of_prod context (name,s) (t1, t2) =
664   let module C = Cic in
665    let t1' = CicReduction.whd context t1 in
666    let t2' = CicReduction.whd ((Some (name,C.Decl s))::context) t2 in
667    match (t1', t2') with
668       (C.Sort _, C.Sort s2)
669         when (s2 = C.Prop or s2 = C.Set or s2 = C.CProp) -> 
670          (* different from Coq manual!!! *)
671          C.Sort s2
672     | (C.Sort (C.Type t1), C.Sort (C.Type t2)) -> 
673         C.Sort (C.Type (CicUniv.fresh()))
674     | (C.Sort _,C.Sort (C.Type t1)) -> 
675         (* TASSI: CONSRTAINTS: the same in cictypechecker,cicrefine *)
676         C.Sort (C.Type t1) (* c'e' bisogno di un fresh? *)
677     | (C.Meta _, C.Sort _) -> t2'
678     | (C.Meta _, (C.Meta (_,_) as t))
679     | (C.Sort _, (C.Meta (_,_) as t)) when CicUtil.is_closed t ->
680         t2'
681     | (_,_) ->
682       raise
683        (NotWellTyped
684         ("Prod: sort1= " ^ CicPp.ppterm t1' ^ " ; sort2= " ^ CicPp.ppterm t2'))
685
686  and eat_prods context hetype =
687   (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
688   (*CSC: cucinati                                                         *)
689   function
690      [] -> hetype
691    | (hete, hety)::tl ->
692     (match (CicReduction.whd context hetype) with
693         Cic.Prod (n,s,t) ->
694          (* Checks suppressed *)
695          eat_prods context (CicSubstitution.subst hete t) tl
696       | _ -> raise (NotWellTyped "Appl: wrong Prod-type")
697     )
698
699 and type_of_branch context argsno need_dummy outtype term constype =
700  let module C = Cic in
701  let module R = CicReduction in
702   match R.whd context constype with
703      C.MutInd (_,_,_) ->
704       if need_dummy then
705        outtype
706       else
707        C.Appl [outtype ; term]
708    | C.Appl (C.MutInd (_,_,_)::tl) ->
709       let (_,arguments) = split tl argsno
710       in
711        if need_dummy && arguments = [] then
712         outtype
713        else
714         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
715    | C.Prod (name,so,de) ->
716       let term' =
717        match CicSubstitution.lift 1 term with
718           C.Appl l -> C.Appl (l@[C.Rel 1])
719         | t -> C.Appl [t ; C.Rel 1]
720       in
721        C.Prod (C.Anonymous,so,type_of_branch
722         ((Some (name,(C.Decl so)))::context) argsno need_dummy
723         (CicSubstitution.lift 1 outtype) term' de)
724   | _ -> raise (Impossible 20)
725
726  in
727   type_of_aux context t expectedty
728 ;;
729
730 let double_type_of metasenv context t expectedty =
731  let subterms_to_types = Cic.CicHash.create 503 in
732   ignore (type_of_aux' subterms_to_types metasenv context t expectedty) ;
733   subterms_to_types
734 ;;