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