]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/doubleTypeInference.ml
f58c554fb0990a005f4f790c9691c305ce19cfa9
[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 expected_hetype =
312          (* Inefficient, the head is computed twice. But I know *)
313          (* of no other solution.                               *)
314          R.whd context (CicTypeChecker.type_of_aux' metasenv context he)
315         in
316          let hetype = type_of_aux context he (Some expected_hetype) in
317          let tlbody_and_type =
318           let rec aux =
319            function
320               _,[] -> []
321             | C.Prod (n,s,t),he::tl ->
322                (he, type_of_aux context he (Some (head_beta_reduce s)))::
323                 (aux (R.whd context (S.subst he t), tl))
324             | _ -> assert false
325           in
326            aux (expected_hetype, tl)
327          in
328           eat_prods context hetype tlbody_and_type
329      | C.Appl _ -> raise (NotWellTyped "Appl: no arguments")
330      | C.Const (uri,cookingsno) ->
331         cooked_type_of_constant uri cookingsno
332      | C.MutInd (uri,cookingsno,i) ->
333         cooked_type_of_mutual_inductive_defs uri cookingsno i
334      | C.MutConstruct (uri,cookingsno,i,j) ->
335         let cty = cooked_type_of_mutual_inductive_constr uri cookingsno i j in
336          cty
337      | C.MutCase (uri,cookingsno,i,outtype,term,pl) ->
338         let outsort = type_of_aux context outtype None in
339         let (need_dummy, k) =
340          let rec guess_args context t =
341           match CicReduction.whd context t with
342              C.Sort _ -> (true, 0)
343            | C.Prod (name, s, t) ->
344               let (b, n) = guess_args ((Some (name,(C.Decl s)))::context) t in
345                if n = 0 then
346                 (* last prod before sort *)
347                 match CicReduction.whd context s with
348                    (*CSC vedi nota delirante su cookingsno in cicReduction.ml *)
349                    C.MutInd (uri',_,i') when U.eq uri' uri && i' = i ->
350                     (false, 1)
351                  | C.Appl ((C.MutInd (uri',_,i')) :: _)
352                     when U.eq uri' uri && i' = i -> (false, 1)
353                  | _ -> (true, 1)
354                else
355                 (b, n + 1)
356            | _ -> raise (NotWellTyped "MutCase: outtype ill-formed")
357          in
358           let (b, k) = guess_args context outsort in
359            if not b then (b, k - 1) else (b, k)
360         in
361         let (parameters, arguments) =
362          let type_of_term =
363           CicTypeChecker.type_of_aux' metasenv context term
364          in
365           match
366            R.whd context (type_of_aux context term
367             (Some (head_beta_reduce type_of_term)))
368           with
369              (*CSC manca il caso dei CAST *)
370              C.MutInd (uri',_,i') ->
371               (* Checks suppressed *)
372               [],[]
373            | C.Appl (C.MutInd (uri',_,i') :: tl) ->
374               split tl (List.length tl - k)
375            | _ ->
376              raise (NotWellTyped "MutCase: the term is not an inductive one")
377         in
378          (* Checks suppressed *)
379          (* Let's visit all the subterms that will not be visited later *)
380          let (cl,parsno) =
381           match CicEnvironment.get_cooked_obj uri cookingsno with
382              C.InductiveDefinition (tl,_,parsno) ->
383               let (_,_,_,cl) = List.nth tl i in (cl,parsno)
384            | _ ->
385              raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
386          in
387           let _ =
388            List.fold_left
389             (fun j (p,(_,c,_)) ->
390               let cons =
391                if parameters = [] then
392                 (C.MutConstruct (uri,cookingsno,i,j))
393                else
394                 (C.Appl (C.MutConstruct (uri,cookingsno,i,j)::parameters))
395               in
396                let expectedtype =
397                 type_of_branch context parsno need_dummy outtype cons
398                   (CicTypeChecker.type_of_aux' metasenv context cons)
399                in
400                 ignore (type_of_aux context p
401                  (Some (head_beta_reduce expectedtype))) ;
402                 j+1
403             ) 1 (List.combine pl cl)
404           in
405            if not need_dummy then
406             C.Appl ((outtype::arguments)@[term])
407            else if arguments = [] then
408             outtype
409            else
410             C.Appl (outtype::arguments)
411      | C.Fix (i,fl) ->
412         (* Let's visit all the subterms that will not be visited later *)
413         let context' =
414          List.rev
415           (List.map
416             (fun (n,_,ty,_) ->
417               let _ = type_of_aux context ty None in
418                (Some (C.Name n,(C.Decl ty)))
419             ) fl
420           ) @
421           context
422         in
423          let _ =
424           List.iter
425            (fun (_,_,ty,bo) ->
426              let expectedty =
427               head_beta_reduce (CicSubstitution.lift (List.length fl) ty)
428              in
429               ignore (type_of_aux context' bo (Some expectedty))
430            ) fl
431          in
432           (* Checks suppressed *)
433           let (_,_,ty,_) = List.nth fl i in
434            ty
435      | C.CoFix (i,fl) ->
436         (* Let's visit all the subterms that will not be visited later *)
437         let context' =
438          List.rev
439           (List.map
440             (fun (n,ty,_) ->
441               let _ = type_of_aux context ty None in
442                (Some (C.Name n,(C.Decl ty)))
443             ) fl
444           ) @
445           context
446         in
447          let _ =
448           List.iter
449            (fun (_,ty,bo) ->
450              let expectedty =
451               head_beta_reduce (CicSubstitution.lift (List.length fl) ty)
452              in
453               ignore (type_of_aux context' bo (Some expectedty))
454            ) fl
455          in
456           (* Checks suppressed *)
457           let (_,ty,_) = List.nth fl i in
458            ty
459    in
460     let synthesized' = head_beta_reduce synthesized in
461      let types,res =
462       match expectedty with
463          None ->
464           (* No expected type *)
465           {synthesized = synthesized' ; expected = None}, synthesized
466        | Some ty when syntactic_equality synthesized' ty ->
467           (* The expected type is synthactically equal to *)
468           (* the synthesized type. Let's forget it.       *)
469           {synthesized = synthesized' ; expected = None}, synthesized
470        | Some expectedty' ->
471           {synthesized = synthesized' ; expected = Some expectedty'},
472           expectedty'
473      in
474       CicHash.add subterms_to_types t types ;
475       res
476
477  and sort_of_prod context (name,s) (t1, t2) =
478   let module C = Cic in
479    let t1' = CicReduction.whd context t1 in
480    let t2' = CicReduction.whd ((Some (name,C.Decl s))::context) t2 in
481    match (t1', t2') with
482       (C.Sort s1, C.Sort s2)
483         when (s2 = C.Prop or s2 = C.Set) -> (* different from Coq manual!!! *)
484          C.Sort s2
485     | (C.Sort s1, C.Sort s2) -> C.Sort C.Type (*CSC manca la gestione degli universi!!! *)
486     | (_,_) ->
487       raise
488        (NotWellTyped
489         ("Prod: sort1= " ^ CicPp.ppterm t1' ^ " ; sort2= " ^ CicPp.ppterm t2'))
490
491  and eat_prods context hetype =
492   (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
493   (*CSC: cucinati                                                         *)
494   function
495      [] -> hetype
496    | (hete, hety)::tl ->
497     (match (CicReduction.whd context hetype) with
498         Cic.Prod (n,s,t) ->
499          (* Checks suppressed *)
500          eat_prods context (CicSubstitution.subst hete t) tl
501       | _ -> raise (NotWellTyped "Appl: wrong Prod-type")
502     )
503
504 and type_of_branch context argsno need_dummy outtype term constype =
505  let module C = Cic in
506  let module R = CicReduction in
507   match R.whd context constype with
508      C.MutInd (_,_,_) ->
509       if need_dummy then
510        outtype
511       else
512        C.Appl [outtype ; term]
513    | C.Appl (C.MutInd (_,_,_)::tl) ->
514       let (_,arguments) = split tl argsno
515       in
516        if need_dummy && arguments = [] then
517         outtype
518        else
519         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
520    | C.Prod (name,so,de) ->
521       let term' =
522        match CicSubstitution.lift 1 term with
523           C.Appl l -> C.Appl (l@[C.Rel 1])
524         | t -> C.Appl [t ; C.Rel 1]
525       in
526        C.Prod (C.Anonimous,so,type_of_branch
527         ((Some (name,(C.Decl so)))::context) argsno need_dummy
528         (CicSubstitution.lift 1 outtype) term' de)
529   | _ -> raise (Impossible 20)
530
531  in
532   type_of_aux context t expectedty
533 ;;
534
535 let double_type_of metasenv context t expectedty =
536  let subterms_to_types = CicHash.create 503 in
537   ignore (type_of_aux' subterms_to_types metasenv context t expectedty) ;
538   subterms_to_types
539 ;;