]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
term refinement almost done, some functions exported from the kernel since they were...
[helm.git] / helm / software / components / ng_refiner / nCicRefiner.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 exception RefineFailure of (Stdpp.location * string) Lazy.t;;
15 exception Uncertain of (Stdpp.location * string) Lazy.t;;
16 exception AssertFailure of string Lazy.t;;
17
18 module C = NCic
19 module Ref = NReference
20
21 let wrap_exc msg = function
22   | NCicUnification.Uncertain _ -> Uncertain msg
23   | NCicUnification.UnificationFailure _ -> RefineFailure msg
24   | NCicTypeChecker.TypeCheckerFailure _ -> RefineFailure msg
25   | e -> raise e
26 ;;
27
28 let exp_implicit metasenv context expty =
29  function      
30   | `Closed -> NCicMetaSubst.mk_meta metasenv [] expty
31   | `Type | `Term -> NCicMetaSubst.mk_meta metasenv context expty
32   | _ -> assert false
33 ;;
34
35 let sort_of_prod 
36   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
37 =
38    let restrict metasenv subst = function
39      | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) as t -> 
40         metasenv, subst, t
41      | C.Meta (i,(_,lc)) as t ->
42         let len = match lc with C.Irl len->len | C.Ctx l->List.length l in
43         let metasenv, subst, _ = 
44           NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 len) 
45         in
46         metasenv, subst, t
47      | t -> metasenv, subst, t 
48    in
49    let t1 = NCicReduction.whd ~subst context t1 in
50    let t2 = NCicReduction.whd ~subst ((name,C.Decl s)::context) t2 in
51    let metasenv, subst, t1 = restrict metasenv subst t1 in
52    let metasenv, subst, t2 = restrict metasenv subst t2 in
53    match t1, t2 with
54    | C.Sort _, C.Sort C.Prop -> metasenv, subst, t2
55    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
56         metasenv, subst, C.Sort (C.Type (u1@u2)) 
57    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, t2
58    | C.Meta _, C.Sort _
59    | C.Meta _, C.Meta _
60    | C.Sort _, C.Meta  _ -> metasenv, subst, t2
61    | x, (C.Sort _ | C.Meta _) | _, x -> 
62       let y, context, orig = 
63         if x == t1 then s, context, orig_s 
64         else t, ((name,C.Decl s)::context), orig_t
65       in
66       raise (RefineFailure (lazy (localise orig,Printf.sprintf
67         "%s is expected to be a type, but its type is %s that is not a sort" 
68          (NCicPp.ppterm ~subst ~metasenv ~context y) 
69          (NCicPp.ppterm ~subst ~metasenv ~context x))))
70 ;;
71
72 let check_allowed_sort_elimination localise r orig =
73    let mkapp he arg =
74      match he with
75      | C.Appl l -> C.Appl (l @ [arg])
76      | t -> C.Appl [t;arg] in
77    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
78    let rec aux metasenv subst context ind arity1 arity2 =
79      let arity1 = NCicReduction.whd ~subst context arity1 in
80      match arity1 with
81      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
82         let metasenv, meta, _ = 
83           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) None 
84         in
85         let metasenv, subst = 
86           try NCicUnification.unify metasenv subst context 
87                 (C.Prod (name, so1, meta)) arity2 
88           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
89             "expected %s, found %s" (* XXX localizzare meglio *)
90             (NCicPp.ppterm ~subst ~metasenv ~context arity1)
91             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
92         in
93         aux metasenv subst ((name, C.Decl so1)::context)
94          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
95      | C.Sort _ (* , t ==?== C.Prod _ *) ->
96         let metasenv, meta, _ = 
97           NCicMetaSubst.mk_meta metasenv (("_",C.Decl ind)::context) None 
98         in
99         let metasenv, subst = 
100           try NCicUnification.unify metasenv subst context 
101                 (C.Prod ("_", ind, meta)) arity2 
102           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
103             "expected %s, found %s" (* XXX localizzare meglio *)
104             (NCicPp.ppterm ~subst ~metasenv ~context arity1)
105             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
106         in
107         (try NCicTypeChecker.check_allowed_sort_elimination
108              ~metasenv ~subst r context ind arity1 arity2
109         with exc -> raise (wrap_exc (lazy (localise orig, 
110           "Sort elimination not allowed ")) exc))
111      | _ -> assert false
112    in
113     aux
114 ;;
115
116 let rec typeof 
117   ?(localise=fun _ -> Stdpp.dummy_loc) metasenv subst context term expty 
118 =
119   let force_ty metasenv subst context orig t infty = function
120     | Some expty ->
121        (match t with
122        | C.Implicit _ 
123        | C.Lambda _ -> metasenv, subst, t, expty
124        | _ ->
125          let metasenv, subst = 
126            try NCicUnification.unify metasenv subst context infty expty
127            with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
128              "The term %s has type %s but is here used with type %s"
129              (NCicPp.ppterm ~metasenv ~subst ~context t)
130              (NCicPp.ppterm ~metasenv ~subst ~context infty)
131              (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
132          in
133          metasenv, subst, t, expty)
134     | None -> metasenv, subst, t, infty
135   in
136   let rec typeof_aux metasenv subst context expty = 
137     fun t as orig -> (*prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);*)
138     let metasenv, subst, t, infty = 
139     match t with
140     | C.Rel n ->
141         let infty = 
142          (try
143            match List.nth context (n - 1) with
144            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
145            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
146          with Failure _ -> 
147            raise (RefineFailure (lazy (localise t,"unbound variable"))))
148         in
149         metasenv, subst, t, infty
150     | C.Sort (C.Type [false,u]) -> metasenv,subst,t,(C.Sort (C.Type [true, u]))
151     | C.Sort (C.Type _) -> 
152         raise (AssertFailure (lazy ("Cannot type an inferred type: "^
153           NCicPp.ppterm ~subst ~metasenv ~context t)))
154     | C.Sort _ -> metasenv,subst,t,(C.Sort (C.Type NCicEnvironment.type0))
155     | C.Implicit infos -> 
156          let metasenv,t,ty = exp_implicit metasenv context expty infos in
157          metasenv, subst, t, ty 
158     | C.Meta (n,l) as t -> 
159        let ty =
160         try
161          let _,_,_,ty = NCicUtils.lookup_subst n subst in ty 
162         with NCicUtils.Subst_not_found _ -> try
163          let _,_,ty = NCicUtils.lookup_meta n metasenv in 
164          match ty with C.Implicit _ -> assert false | _ -> ty 
165         with NCicUtils.Meta_not_found _ ->
166          raise (AssertFailure (lazy (Printf.sprintf
167           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
168        in
169        metasenv, subst, t, NCicSubstitution.subst_meta l ty
170     | C.Const _ -> 
171        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
172     | C.Prod (name,(s as orig_s),(t as orig_t)) as orig ->
173        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
174        let context = (name,(C.Decl s))::context in
175        let metasenv, subst, t, s2 = typeof_aux metasenv subst context None t in
176        let metasenv, subst, ty = 
177          sort_of_prod localise metasenv subst 
178            context orig_s orig_t (name,s) t (s1,s2)
179        in
180        metasenv, subst, orig, ty
181     | C.Lambda (n,(s as orig_s),t) ->
182        let exp_s, exp_ty_t =
183          match expty with
184          | None -> None, None
185          | Some expty -> 
186              match NCicReduction.whd ~subst context expty with
187              | C.Prod (_,s,t) -> Some s, Some t
188              | _ -> None, None
189        in
190        let metasenv, subst, s, _ = typeof_aux metasenv subst context None s in
191        let (metasenv,subst), exp_ty_t = 
192          match exp_s with 
193          | Some exp_s -> 
194              (try NCicUnification.unify metasenv subst context s exp_s,exp_ty_t
195              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
196                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
197                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
198                exp_s))) exc))
199          | None -> (metasenv, subst), None
200        in
201        (* XXX coerce_to_sort s *)
202        let context = (n,C.Decl s) :: context in
203        let metasenv, subst, t, ty_t = 
204          typeof_aux metasenv subst context exp_ty_t t 
205        in
206        metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
207     | C.LetIn (n,ty,t,bo) ->
208        let metasenv, subst, ty, _ = typeof_aux metasenv subst context None ty in
209        let metasenv, subst, t, _ = 
210          typeof_aux metasenv subst context (Some ty) t in
211        let context = (n, C.Def (t,ty)) :: context in
212        let metasenv, subst, bo, bo_ty = 
213          typeof_aux metasenv subst context expty bo 
214        in
215        metasenv, subst, C.LetIn (n, ty, t, bo), 
216         NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty
217     | C.Appl ((he as orig_he)::(_::_ as args)) ->
218        let metasenv, subst, he, ty_he = 
219          typeof_aux metasenv subst context None he in
220        eat_prods localise metasenv subst context orig_he he ty_he args
221    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
222    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
223           outtype,(term as orig_term),pl) as orig ->
224       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
225       let _, _, arity, cl = List.nth itl tyno in
226       let constructorsno = List.length cl in
227       let _, metasenv, args = 
228         NCicMetaSubst.saturate metasenv context arity 0 in
229       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
230       let metasenv, subst, term, _ = 
231         typeof_aux metasenv subst context (Some ind) term in
232       let metasenv, subst, outtype, outsort = 
233         typeof_aux metasenv subst context None outtype in
234       let parameters, arguments = HExtlib.split_nth leftno args in
235       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
236       let ind =
237         if parameters = [] then C.Const r
238         else C.Appl ((C.Const r)::parameters) in
239       let metasenv, subst, ind, ind_ty = 
240         typeof_aux metasenv subst context None ind in
241       check_allowed_sort_elimination localise r orig_term metasenv subst context
242        ind ind_ty outsort;
243       (* let's check if the type of branches are right *)
244       if List.length pl <> constructorsno then
245        raise (RefineFailure (lazy (localise orig, 
246          "Wrong number of cases in a match")));
247       let _, metasenv, subst, pl_rev =
248         List.fold_left
249           (fun (j, metasenv, subst, branches) p ->
250               let cons = 
251                 let cons = Ref.mk_constructor j r in
252                 if parameters = [] then C.Const cons
253                 else C.Appl (C.Const cons::parameters)
254               in
255               let metasenv, subst, cons, ty_cons = 
256                 typeof_aux metasenv subst context None cons in
257               let ty_branch = 
258                 NCicTypeChecker.type_of_branch 
259                   ~subst context leftno outtype cons ty_cons in
260               let metasenv, subst, p, _ = 
261                 typeof_aux metasenv subst context (Some ty_branch) p in
262               j+1, metasenv, subst, p :: branches)
263           (1, metasenv, subst, []) pl
264       in
265       metasenv, subst, 
266       C.Match (r, outtype, term, List.rev pl_rev),
267       NCicReduction.head_beta_reduce (C.Appl (outtype::arguments@[term]))
268     | C.Match _ -> assert false
269     in
270       force_ty metasenv subst context orig t infty expty
271   in
272     typeof_aux metasenv subst context expty term
273
274 and eat_prods localise metasenv subst context orig_he he ty_he args =
275   let rec aux metasenv subst args_so_far ty_he = function 
276   | [] -> metasenv, subst, NCic.Appl (he :: List.rev args_so_far), ty_he
277   | arg::tl ->
278       match NCicReduction.whd ~subst context ty_he with 
279       | C.Prod (_,s,t) ->
280           let metasenv, subst, arg, _ = 
281             typeof ~localise metasenv subst context arg (Some s) in
282           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
283           aux metasenv subst (arg :: args_so_far) t tl
284       | t ->
285           let metasenv, subst, arg, ty_arg = 
286             typeof ~localise metasenv subst context arg None in
287           let metasenv, meta, _ = 
288             NCicMetaSubst.mk_meta metasenv 
289               (("_",C.Decl ty_arg) :: context) None
290           in
291           let flex_prod = C.Prod ("_", ty_arg, meta) in
292           let metasenv, subst = 
293              try NCicUnification.unify metasenv subst context t flex_prod 
294              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
295               ("The term %s is here applied to %d arguments but expects " ^^
296               "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
297               (List.length args) (List.length args_so_far))) exc)
298               (* XXX coerce to funclass *)
299           in
300           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
301           aux metasenv subst (arg :: args_so_far) meta tl
302   in
303    aux metasenv subst [] ty_he args
304 ;;
305 (* vim:set foldmethod=marker: *)