]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/doubleTypeInference.ml
* Abst removed from the DTD
[helm.git] / helm / gTopLevel / 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 type types = {synthesized : Cic.term ; expected : Cic.term option};;
35
36 (*CSC: potrebbe creare applicazioni di applicazioni *)
37 (*CSC: ora non e' piu' head, ma completa!!! *)
38 let rec head_beta_reduce =
39  let module S = CicSubstitution in
40  let module C = Cic in
41   function
42       C.Rel _
43     | C.Var _ as t -> t
44     | C.Meta (n,l) ->
45        C.Meta (n,
46         List.map
47          (function None -> None | Some t -> Some (head_beta_reduce t)) l
48        )
49     | C.Sort _ as t -> t
50     | C.Implicit -> assert false
51     | C.Cast (te,ty) ->
52        C.Cast (head_beta_reduce te, head_beta_reduce ty)
53     | C.Prod (n,s,t) ->
54        C.Prod (n, head_beta_reduce s, head_beta_reduce t)
55     | C.Lambda (n,s,t) ->
56        C.Lambda (n, head_beta_reduce s, head_beta_reduce t)
57     | C.LetIn (n,s,t) ->
58        C.LetIn (n, head_beta_reduce s, head_beta_reduce t)
59     | C.Appl ((C.Lambda (name,s,t))::he::tl) ->
60        let he' = S.subst he t in
61         if tl = [] then
62          head_beta_reduce he'
63         else
64          head_beta_reduce (C.Appl (he'::tl))
65     | C.Appl l ->
66        C.Appl (List.map head_beta_reduce l)
67     | C.Const _ as t -> t
68     | C.MutInd _
69     | C.MutConstruct _ as t -> t
70     | C.MutCase (sp,cno,i,outt,t,pl) ->
71        C.MutCase (sp,cno,i,head_beta_reduce outt,head_beta_reduce t,
72         List.map head_beta_reduce pl)
73     | C.Fix (i,fl) ->
74        let fl' =
75         List.map
76          (function (name,i,ty,bo) ->
77            name,i,head_beta_reduce ty,head_beta_reduce bo
78          ) fl
79        in
80         C.Fix (i,fl')
81     | C.CoFix (i,fl) ->
82        let fl' =
83         List.map
84          (function (name,ty,bo) ->
85            name,head_beta_reduce ty,head_beta_reduce bo
86          ) fl
87        in
88         C.CoFix (i,fl')
89 ;;
90
91 (* syntactic_equality up to cookingsno for uris *)
92 (* (which is often syntactically irrilevant),   *)
93 (* distinction between fake dependent products  *)
94 (* and non-dependent products, alfa-conversion  *)
95 (*CSC: must alfa-conversion be considered or not? *)
96 let syntactic_equality t t' =
97  let module C = Cic in
98  let rec syntactic_equality t t' =
99   if t = t' then true
100   else
101    match t, t' with
102       C.Rel _, C.Rel _
103     | C.Var _, C.Var _
104     | C.Meta _, C.Meta _
105     | C.Sort _, C.Sort _
106     | C.Implicit, C.Implicit -> false (* we already know that t != t' *)
107     | C.Cast (te,ty), C.Cast (te',ty') ->
108        syntactic_equality te te' &&
109         syntactic_equality ty ty'
110     | C.Prod (_,s,t), C.Prod (_,s',t') ->
111        syntactic_equality s s' &&
112         syntactic_equality t t'
113     | C.Lambda (_,s,t), C.Lambda (_,s',t') ->
114        syntactic_equality s s' &&
115         syntactic_equality t t'
116     | C.LetIn (_,s,t), C.LetIn(_,s',t') ->
117        syntactic_equality s s' &&
118         syntactic_equality t t'
119     | C.Appl l, C.Appl l' ->
120        List.fold_left2 (fun b t1 t2 -> b && syntactic_equality t1 t2) true l l'
121     | C.Const (uri,_), C.Const (uri',_) -> UriManager.eq uri uri'
122     | C.MutInd (uri,_,i), C.MutInd (uri',_,i') ->
123        UriManager.eq uri uri' && i = i'
124     | C.MutConstruct (uri,_,i,j), C.MutConstruct (uri',_,i',j') ->
125        UriManager.eq uri uri' && i = i' && j = j'
126     | C.MutCase (sp,_,i,outt,t,pl), C.MutCase (sp',_,i',outt',t',pl') ->
127        UriManager.eq sp sp' && i = i' &&
128         syntactic_equality outt outt' &&
129          syntactic_equality t t' &&
130           List.fold_left2
131            (fun b t1 t2 -> b && syntactic_equality t1 t2) true pl pl'
132     | C.Fix (i,fl), C.Fix (i',fl') ->
133        i = i' &&
134         List.fold_left2
135          (fun b (_,i,ty,bo) (_,i',ty',bo') ->
136            b && i = i' &&
137             syntactic_equality ty ty' &&
138              syntactic_equality bo bo') true fl fl'
139     | C.CoFix (i,fl), C.CoFix (i',fl') ->
140        i = i' &&
141         List.fold_left2
142          (fun b (_,ty,bo) (_,ty',bo') ->
143            b &&
144             syntactic_equality ty ty' &&
145              syntactic_equality bo bo') true fl fl'
146     | _,_ -> false
147  in
148   try
149    syntactic_equality t t'
150   with
151    _ -> false
152 ;;
153
154 let rec split l n =
155  match (l,n) with
156     (l,0) -> ([], l)
157   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
158   | (_,_) -> raise ListTooShort
159 ;;
160
161 let cooked_type_of_constant uri cookingsno =
162  let module C = Cic in
163  let module R = CicReduction in
164  let module U = UriManager in
165   let cobj =
166    match CicEnvironment.is_type_checked uri cookingsno with
167       CicEnvironment.CheckedObj cobj -> cobj
168     | CicEnvironment.UncheckedObj uobj ->
169        raise (NotWellTyped "Reference to an unchecked constant")
170   in
171    match cobj with
172       C.Definition (_,_,ty,_) -> ty
173     | C.Axiom (_,ty,_) -> ty
174     | C.CurrentProof (_,_,_,ty) -> ty
175     | _ -> raise (WrongUriToConstant (U.string_of_uri uri))
176 ;;
177
178 let type_of_variable uri =
179  let module C = Cic in
180  let module R = CicReduction in
181  let module U = UriManager in
182   (* 0 because a variable is never cooked => no partial cooking at one level *)
183   match CicEnvironment.is_type_checked uri 0 with
184      CicEnvironment.CheckedObj (C.Variable (_,_,ty)) -> ty
185    | CicEnvironment.UncheckedObj (C.Variable _) ->
186       raise (NotWellTyped "Reference to an unchecked variable")
187    |  _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
188 ;;
189
190 let cooked_type_of_mutual_inductive_defs uri cookingsno i =
191  let module C = Cic in
192  let module R = CicReduction in
193  let module U = UriManager in
194   let cobj =
195    match CicEnvironment.is_type_checked uri cookingsno with
196       CicEnvironment.CheckedObj cobj -> cobj
197     | CicEnvironment.UncheckedObj uobj ->
198        raise (NotWellTyped "Reference to an unchecked inductive type")
199   in
200    match cobj with
201       C.InductiveDefinition (dl,_,_) ->
202        let (_,_,arity,_) = List.nth dl i in
203         arity
204     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
205 ;;
206
207 let cooked_type_of_mutual_inductive_constr uri cookingsno i j =
208  let module C = Cic in
209  let module R = CicReduction in
210  let module U = UriManager in
211   let cobj =
212    match CicEnvironment.is_type_checked uri cookingsno with
213       CicEnvironment.CheckedObj cobj -> cobj
214     | CicEnvironment.UncheckedObj uobj ->
215        raise (NotWellTyped "Reference to an unchecked constructor")
216   in
217    match cobj with
218       C.InductiveDefinition (dl,_,_) ->
219        let (_,_,_,cl) = List.nth dl i in
220         let (_,ty,_) = List.nth cl (j-1) in
221          ty
222     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
223 ;;
224
225 module CicHash =
226  Hashtbl.Make
227   (struct
228     type t = Cic.term
229     let equal = (==)
230     let hash = Hashtbl.hash
231    end)
232 ;;
233
234 (* type_of_aux' is just another name (with a different scope) for type_of_aux *)
235 let rec type_of_aux' subterms_to_types metasenv context t expectedty =
236  (* Coscoy's double type-inference algorithm             *)
237  (* It computes the inner-types of every subterm of [t], *)
238  (* even when they are not needed to compute the types   *)
239  (* of other terms.                                      *)
240  let rec type_of_aux context t expectedty =
241   let module C = Cic in
242   let module R = CicReduction in
243   let module S = CicSubstitution in
244   let module U = UriManager in
245    let synthesized =
246     match t with
247        C.Rel n ->
248         (try
249           match List.nth context (n - 1) with
250              Some (_,C.Decl t) -> S.lift n t
251            | Some (_,C.Def bo) -> type_of_aux context (S.lift n bo) expectedty
252            | None -> raise RelToHiddenHypothesis
253          with
254           _ -> raise (NotWellTyped "Not a close term")
255         )
256      | C.Var uri -> type_of_variable uri
257      | C.Meta (n,l) -> 
258         (* Let's visit all the subterms that will not be visited later *)
259         let _ =
260          List.iter
261           (function
262               None -> ()
263             | Some t -> ignore (type_of_aux context t None)
264           ) l
265         in
266          let (_,canonical_context,ty) =
267           List.find (function (m,_,_) -> n = m) metasenv
268          in
269           (* Checks suppressed *)
270           CicSubstitution.lift_meta l ty
271      | C.Sort s -> C.Sort C.Type (*CSC manca la gestione degli universi!!! *)
272      | C.Implicit -> raise (Impossible 21)
273      | C.Cast (te,ty) ->
274         (* Let's visit all the subterms that will not be visited later *)
275         let _ = type_of_aux context te (Some (head_beta_reduce ty)) in
276         let _ = type_of_aux context ty None in
277          (* Checks suppressed *)
278          ty
279      | C.Prod (name,s,t) ->
280         let sort1 = type_of_aux context s None
281         and sort2 = type_of_aux ((Some (name,(C.Decl s)))::context) t None in
282          sort_of_prod context (name,s) (sort1,sort2)
283      | C.Lambda (n,s,t) ->
284         (* Let's visit all the subterms that will not be visited later *)
285         let _ = type_of_aux context s None in
286          let expected_target_type =
287           match expectedty with
288              None -> None
289            | Some expectedty' ->
290               let ty =
291                match R.whd context expectedty' with
292                   C.Prod (_,_,expected_target_type) ->
293                    head_beta_reduce expected_target_type
294                 | _ -> assert false
295               in
296                Some ty
297          in
298           let type2 =
299            type_of_aux ((Some (n,(C.Decl s)))::context) t expected_target_type
300           in
301            (* Checks suppressed *)
302            C.Prod (n,s,type2)
303      | C.LetIn (n,s,t) ->
304 (*CSC: What are the right expected types for the source and *)
305 (*CSC: target of a LetIn? None used.                        *)
306         (* Let's visit all the subterms that will not be visited later *)
307         let _ = type_of_aux context s None in
308          (* Checks suppressed *)
309          C.LetIn (n,s, type_of_aux ((Some (n,(C.Def s)))::context) t None)
310      | C.Appl (he::tl) when List.length tl > 0 ->
311         let hetype = type_of_aux context he None in
312         let tlbody_and_type =
313          let rec aux =
314           function
315              _,[] -> []
316            | C.Prod (n,s,t),he::tl ->
317               (he, type_of_aux context he (Some (head_beta_reduce s)))::
318                (aux (R.whd context (S.subst he t), tl))
319            | _ -> assert false
320          in
321           aux (R.whd context hetype, tl)
322         in
323          eat_prods context hetype tlbody_and_type
324      | C.Appl _ -> raise (NotWellTyped "Appl: no arguments")
325      | C.Const (uri,cookingsno) ->
326         cooked_type_of_constant uri cookingsno
327      | C.MutInd (uri,cookingsno,i) ->
328         cooked_type_of_mutual_inductive_defs uri cookingsno i
329      | C.MutConstruct (uri,cookingsno,i,j) ->
330         let cty = cooked_type_of_mutual_inductive_constr uri cookingsno i j in
331          cty
332      | C.MutCase (uri,cookingsno,i,outtype,term,pl) ->
333         let outsort = type_of_aux context outtype None in
334         let (need_dummy, k) =
335          let rec guess_args context t =
336           match CicReduction.whd context t with
337              C.Sort _ -> (true, 0)
338            | C.Prod (name, s, t) ->
339               let (b, n) = guess_args ((Some (name,(C.Decl s)))::context) t in
340                if n = 0 then
341                 (* last prod before sort *)
342                 match CicReduction.whd context s with
343                    (*CSC vedi nota delirante su cookingsno in cicReduction.ml *)
344                    C.MutInd (uri',_,i') when U.eq uri' uri && i' = i ->
345                     (false, 1)
346                  | C.Appl ((C.MutInd (uri',_,i')) :: _)
347                     when U.eq uri' uri && i' = i -> (false, 1)
348                  | _ -> (true, 1)
349                else
350                 (b, n + 1)
351            | _ -> raise (NotWellTyped "MutCase: outtype ill-formed")
352          in
353           let (b, k) = guess_args context outsort in
354            if not b then (b, k - 1) else (b, k)
355         in
356         let (parameters, arguments) =
357          let type_of_term =
358           CicTypeChecker.type_of_aux' metasenv context term
359          in
360           match
361            R.whd context (type_of_aux context term
362             (Some (head_beta_reduce type_of_term)))
363           with
364              (*CSC manca il caso dei CAST *)
365              C.MutInd (uri',_,i') ->
366               (* Checks suppressed *)
367               [],[]
368            | C.Appl (C.MutInd (uri',_,i') :: tl) ->
369               split tl (List.length tl - k)
370            | _ ->
371              raise (NotWellTyped "MutCase: the term is not an inductive one")
372         in
373          (* Checks suppressed *)
374          (* Let's visit all the subterms that will not be visited later *)
375          let (cl,parsno) =
376           match CicEnvironment.get_cooked_obj uri cookingsno with
377              C.InductiveDefinition (tl,_,parsno) ->
378               let (_,_,_,cl) = List.nth tl i in (cl,parsno)
379            | _ ->
380              raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
381          in
382           let _ =
383            List.fold_left
384             (fun j (p,(_,c,_)) ->
385               let cons =
386                if parameters = [] then
387                 (C.MutConstruct (uri,cookingsno,i,j))
388                else
389                 (C.Appl (C.MutConstruct (uri,cookingsno,i,j)::parameters))
390               in
391                let expectedtype =
392                 type_of_branch context parsno need_dummy outtype cons
393                   (CicTypeChecker.type_of_aux' metasenv context cons)
394                in
395                 ignore (type_of_aux context p
396                  (Some (head_beta_reduce expectedtype))) ;
397                 j+1
398             ) 1 (List.combine pl cl)
399           in
400            if not need_dummy then
401             C.Appl ((outtype::arguments)@[term])
402            else if arguments = [] then
403             outtype
404            else
405             C.Appl (outtype::arguments)
406      | C.Fix (i,fl) ->
407         (* Let's visit all the subterms that will not be visited later *)
408         let context' =
409          List.rev
410           (List.map
411             (fun (n,_,ty,_) ->
412               let _ = type_of_aux context ty None in
413                (Some (C.Name n,(C.Decl ty)))
414             ) fl
415           ) @
416           context
417         in
418          let _ =
419           List.iter
420            (fun (_,_,ty,bo) ->
421              let expectedty =
422               head_beta_reduce (CicSubstitution.lift (List.length fl) ty)
423              in
424               ignore (type_of_aux context' bo (Some expectedty))
425            ) fl
426          in
427           (* Checks suppressed *)
428           let (_,_,ty,_) = List.nth fl i in
429            ty
430      | C.CoFix (i,fl) ->
431         (* Let's visit all the subterms that will not be visited later *)
432         let context' =
433          List.rev
434           (List.map
435             (fun (n,ty,_) ->
436               let _ = type_of_aux context ty None in
437                (Some (C.Name n,(C.Decl ty)))
438             ) fl
439           ) @
440           context
441         in
442          let _ =
443           List.iter
444            (fun (_,ty,bo) ->
445              let expectedty =
446               head_beta_reduce (CicSubstitution.lift (List.length fl) ty)
447              in
448               ignore (type_of_aux context' bo (Some expectedty))
449            ) fl
450          in
451           (* Checks suppressed *)
452           let (_,ty,_) = List.nth fl i in
453            ty
454    in
455     let synthesized' = head_beta_reduce synthesized in
456      let types,res =
457       match expectedty with
458          None ->
459           (* No expected type *)
460           {synthesized = synthesized' ; expected = None}, synthesized
461        | Some ty when syntactic_equality synthesized' ty ->
462           (* The expected type is synthactically equal to *)
463           (* the synthesized type. Let's forget it.       *)
464           {synthesized = synthesized' ; expected = None}, synthesized
465        | Some expectedty' ->
466 prerr_endline ("t: " ^ CicPp.ppterm t) ; flush stderr ;
467 prerr_endline (CicPp.ppterm synthesized' ^ " <-> " ^ CicPp.ppterm expectedty') ; flush stderr ;
468           {synthesized = synthesized' ; expected = Some expectedty'},
469           expectedty'
470      in
471       CicHash.add subterms_to_types t types ;
472       res
473
474  and sort_of_prod context (name,s) (t1, t2) =
475   let module C = Cic in
476    let t1' = CicReduction.whd context t1 in
477    let t2' = CicReduction.whd ((Some (name,C.Decl s))::context) t2 in
478    match (t1', t2') with
479       (C.Sort s1, C.Sort s2)
480         when (s2 = C.Prop or s2 = C.Set) -> (* different from Coq manual!!! *)
481          C.Sort s2
482     | (C.Sort s1, C.Sort s2) -> C.Sort C.Type (*CSC manca la gestione degli universi!!! *)
483     | (_,_) ->
484       raise
485        (NotWellTyped
486         ("Prod: sort1= " ^ CicPp.ppterm t1' ^ " ; sort2= " ^ CicPp.ppterm t2'))
487
488  and eat_prods context hetype =
489   (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
490   (*CSC: cucinati                                                         *)
491   function
492      [] -> hetype
493    | (hete, hety)::tl ->
494     (match (CicReduction.whd context hetype) with
495         Cic.Prod (n,s,t) ->
496          (* Checks suppressed *)
497          eat_prods context (CicSubstitution.subst hete t) tl
498       | _ -> raise (NotWellTyped "Appl: wrong Prod-type")
499     )
500
501 and type_of_branch context argsno need_dummy outtype term constype =
502  let module C = Cic in
503  let module R = CicReduction in
504   match R.whd context constype with
505      C.MutInd (_,_,_) ->
506       if need_dummy then
507        outtype
508       else
509        C.Appl [outtype ; term]
510    | C.Appl (C.MutInd (_,_,_)::tl) ->
511       let (_,arguments) = split tl argsno
512       in
513        if need_dummy && arguments = [] then
514         outtype
515        else
516         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
517    | C.Prod (name,so,de) ->
518       let term' =
519        match CicSubstitution.lift 1 term with
520           C.Appl l -> C.Appl (l@[C.Rel 1])
521         | t -> C.Appl [t ; C.Rel 1]
522       in
523        C.Prod (C.Anonimous,so,type_of_branch
524         ((Some (name,(C.Decl so)))::context) argsno need_dummy
525         (CicSubstitution.lift 1 outtype) term' de)
526   | _ -> raise (Impossible 20)
527
528  in
529   type_of_aux context t expectedty
530 ;;
531
532 let double_type_of metasenv context t expectedty =
533  let subterms_to_types = CicHash.create 503 in
534   ignore (type_of_aux' subterms_to_types metasenv context t expectedty) ;
535   subterms_to_types
536 ;;