]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
more work
[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  let foo x = match expty with Some t -> `WithType t | None -> x in
30  function      
31   | `Closed -> NCicMetaSubst.mk_meta metasenv [] (foo `Type)
32   | `Type -> NCicMetaSubst.mk_meta metasenv context (foo `Type)
33   | `Term -> NCicMetaSubst.mk_meta metasenv context (foo `Term)
34   | _ -> assert false
35 ;;
36
37 let force_to_sort metasenv subst context t =
38   match NCicReduction.whd ~subst context t with
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      prerr_endline "RESTRICT";
44      let metasenv, subst, _ = 
45        NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 len) 
46      in
47      metasenv, subst, t
48   | C.Sort _ -> metasenv, subst, t 
49   | _ -> assert false
50 ;;
51
52 let sort_of_prod 
53   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
54 =
55    let metasenv, subst, t1 = force_to_sort metasenv subst context t1 in
56    let metasenv, subst, t2 = 
57      force_to_sort metasenv subst ((name,C.Decl s)::context) t2 in
58    prerr_endline ("S1:"^NCicPp.ppterm ~metasenv ~subst ~context t1);
59    prerr_endline ("S2:"^NCicPp.ppterm ~metasenv ~subst ~context:((name,C.Decl s)::context) t2);
60    match t1, t2 with
61    | C.Sort _, C.Sort C.Prop -> metasenv, subst, t2
62    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
63         metasenv, subst, C.Sort (C.Type (u1@u2)) 
64    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, t2
65    | C.Meta _, C.Sort _
66    | C.Meta _, C.Meta _
67    | C.Sort _, C.Meta  _ -> metasenv, subst, t2
68    | x, (C.Sort _ | C.Meta _) | _, x -> 
69       let y, context, orig = 
70         if x == t1 then s, context, orig_s 
71         else t, ((name,C.Decl s)::context), orig_t
72       in
73       raise (RefineFailure (lazy (localise orig,Printf.sprintf
74         "%s is expected to be a type, but its type is %s that is not a sort" 
75          (NCicPp.ppterm ~subst ~metasenv ~context y) 
76          (NCicPp.ppterm ~subst ~metasenv ~context x))))
77 ;;
78
79 let check_allowed_sort_elimination localise r orig =
80    let mkapp he arg =
81      match he with
82      | C.Appl l -> C.Appl (l @ [arg])
83      | t -> C.Appl [t;arg] in
84    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
85    let rec aux metasenv subst context ind arity1 arity2 =
86      let arity1 = NCicReduction.whd ~subst context arity1 in
87      match arity1 with
88      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
89         let metasenv, meta, _ = 
90           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `Typeless 
91         in
92         let metasenv, subst = 
93           try NCicUnification.unify metasenv subst context 
94                 (C.Prod (name, so1, meta)) arity2 
95           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
96             "expected %s, found %s" (* XXX localizzare meglio *)
97             (NCicPp.ppterm ~subst ~metasenv ~context arity1)
98             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
99         in
100         aux metasenv subst ((name, C.Decl so1)::context)
101          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
102      | C.Sort _ (* , t ==?== C.Prod _ *) ->
103         let metasenv, meta, _ = NCicMetaSubst.mk_meta metasenv [] `Typeless in
104         prerr_endline (
105             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta))) ^ " ==== " ^
106             (NCicPp.ppterm ~subst ~metasenv ~context arity2) ^ "\nMENV:\n"
107             ^ NCicPp.ppmetasenv ~subst metasenv);
108         let metasenv, subst = 
109           try NCicUnification.unify metasenv subst context 
110                 (C.Prod ("_", ind, meta)) arity2 
111           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
112             "expected %s, found %s" (* XXX localizzare meglio *)
113             (NCicPp.ppterm ~subst ~metasenv ~context arity1)
114             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
115         in
116         (try NCicTypeChecker.check_allowed_sort_elimination
117             ~metasenv ~subst r context ind arity1 arity2; 
118             metasenv, subst
119         with exc -> raise (wrap_exc (lazy (localise orig, 
120           "Sort elimination not allowed ")) exc))
121      | _ -> assert false
122    in
123     aux
124 ;;
125
126 let rec typeof 
127   ?(localise=fun _ -> Stdpp.dummy_loc) metasenv subst context term expty 
128 =
129   let force_ty metasenv subst context orig t infty = function
130     | Some expty ->
131        (match t with
132        | C.Implicit _ 
133        | C.Lambda _ -> metasenv, subst, t, expty
134        | _ ->
135           prerr_endline ("F:" ^
136           (NCicPp.ppterm ~metasenv ~subst ~context infty) ^  " === " ^
137           (NCicPp.ppterm ~metasenv ~subst ~context expty) ^ "\nMENV:\n" ^
138           NCicPp.ppmetasenv ~subst metasenv);
139          let metasenv, subst = 
140            try NCicUnification.unify metasenv subst context infty expty
141            with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
142              "The term %s has type %s but is here used with type %s"
143              (NCicPp.ppterm ~metasenv ~subst ~context t)
144              (NCicPp.ppterm ~metasenv ~subst ~context infty)
145              (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
146          in
147          metasenv, subst, t, expty)
148     | None -> metasenv, subst, t, infty
149   in
150   let rec typeof_aux metasenv subst context expty = 
151     fun t as orig -> 
152     prerr_endline ("R:"^NCicPp.ppterm ~metasenv ~subst ~context t);
153     let metasenv, subst, t, infty = 
154     match t with
155     | C.Rel n ->
156         let infty = 
157          (try
158            match List.nth context (n - 1) with
159            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
160            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
161          with Failure _ -> 
162            raise (RefineFailure (lazy (localise t,"unbound variable"))))
163         in
164         metasenv, subst, t, infty
165     | C.Sort (C.Type [false,u]) -> metasenv,subst,t,(C.Sort (C.Type [true, u]))
166     | C.Sort (C.Type _) -> 
167         raise (AssertFailure (lazy ("Cannot type an inferred type: "^
168           NCicPp.ppterm ~subst ~metasenv ~context t)))
169     | C.Sort _ -> metasenv,subst,t,(C.Sort (C.Type NCicEnvironment.type0))
170     | C.Implicit infos -> 
171          let metasenv,t,ty = exp_implicit metasenv context expty infos in
172          metasenv, subst, t, ty 
173     | C.Meta (n,l) as t -> 
174        let ty =
175         try
176          let _,_,_,ty = NCicUtils.lookup_subst n subst in ty 
177         with NCicUtils.Subst_not_found _ -> try
178          let _,_,ty = NCicUtils.lookup_meta n metasenv in 
179          match ty with C.Implicit _ -> assert false | _ -> ty 
180         with NCicUtils.Meta_not_found _ ->
181          raise (AssertFailure (lazy (Printf.sprintf
182           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
183        in
184        metasenv, subst, t, NCicSubstitution.subst_meta l ty
185     | C.Const _ -> 
186        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
187     | C.Prod (name,(s as orig_s),(t as orig_t)) as orig ->
188        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
189        let context = (name,(C.Decl s))::context in
190        let metasenv, subst, t, s2 = typeof_aux metasenv subst context None t in
191        let metasenv, subst, ty = 
192          sort_of_prod localise metasenv subst 
193            context orig_s orig_t (name,s) t (s1,s2)
194        in
195        metasenv, subst, orig, ty
196     | C.Lambda (n,(s as orig_s),t) ->
197        let exp_s, exp_ty_t =
198          match expty with
199          | None -> None, None
200          | Some expty -> 
201              match NCicReduction.whd ~subst context expty with
202              | C.Prod (_,s,t) -> Some s, Some t
203              | _ -> None, None
204        in
205        let metasenv, subst, s, ty_s = 
206          typeof_aux metasenv subst context None s in
207        let metasenv, subst, _ = force_to_sort metasenv subst context ty_s in
208        let (metasenv,subst), exp_ty_t = 
209          match exp_s with 
210          | Some exp_s -> 
211              (try NCicUnification.unify metasenv subst context s exp_s,exp_ty_t
212              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
213                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
214                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
215                exp_s))) exc))
216          | None -> (metasenv, subst), None
217        in
218        (* XXX coerce_to_sort s *)
219        let context = (n,C.Decl s) :: context in
220        let metasenv, subst, t, ty_t = 
221          typeof_aux metasenv subst context exp_ty_t t 
222        in
223        metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
224     | C.LetIn (n,ty,t,bo) ->
225        let metasenv, subst, ty, ty_ty = 
226          typeof_aux metasenv subst context None ty in
227        let metasenv, subst, _ = force_to_sort metasenv subst context ty_ty in
228        let metasenv, subst, t, _ = 
229          typeof_aux metasenv subst context (Some ty) t in
230        let context = (n, C.Def (t,ty)) :: context in
231        let metasenv, subst, bo, bo_ty = 
232          typeof_aux metasenv subst context expty bo 
233        in
234        metasenv, subst, C.LetIn (n, ty, t, bo), 
235         NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty
236     | C.Appl ((he as orig_he)::(_::_ as args)) ->
237        let metasenv, subst, he, ty_he = 
238          typeof_aux metasenv subst context None he in
239        eat_prods localise metasenv subst context orig_he he ty_he args
240    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
241    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
242           outtype,(term as orig_term),pl) as orig ->
243       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
244       let _, _, arity, cl = List.nth itl tyno in
245       let constructorsno = List.length cl in
246       let _, metasenv, args = 
247         NCicMetaSubst.saturate metasenv context arity 0 in
248       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
249       let metasenv, subst, term, _ = 
250         typeof_aux metasenv subst context (Some ind) term in
251       let metasenv, subst, outtype, outsort = 
252         typeof_aux metasenv subst context None outtype in
253       let parameters, arguments = HExtlib.split_nth leftno args in
254       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
255       let ind =
256         if parameters = [] then C.Const r
257         else C.Appl ((C.Const r)::parameters) in
258       let metasenv, subst, ind, ind_ty = 
259         typeof_aux metasenv subst context None ind in
260       let metasenv, subst = 
261          check_allowed_sort_elimination localise r orig_term metasenv subst 
262            context ind ind_ty outsort 
263       in
264       (* let's check if the type of branches are right *)
265       if List.length pl <> constructorsno then
266        raise (RefineFailure (lazy (localise orig, 
267          "Wrong number of cases in a match")));
268       let _, metasenv, subst, pl_rev =
269         List.fold_left
270           (fun (j, metasenv, subst, branches) p ->
271               let cons = 
272                 let cons = Ref.mk_constructor j r in
273                 if parameters = [] then C.Const cons
274                 else C.Appl (C.Const cons::parameters)
275               in
276               let metasenv, subst, cons, ty_cons = 
277                 typeof_aux metasenv subst context None cons in
278               let ty_branch = 
279                 NCicTypeChecker.type_of_branch 
280                   ~subst context leftno outtype cons ty_cons in
281               let metasenv, subst, p, _ = 
282                 typeof_aux metasenv subst context (Some ty_branch) p in
283               j+1, metasenv, subst, p :: branches)
284           (1, metasenv, subst, []) pl
285       in
286       metasenv, subst, 
287       C.Match (r, outtype, term, List.rev pl_rev),
288       NCicReduction.head_beta_reduce (C.Appl (outtype::arguments@[term]))
289     | C.Match _ -> assert false
290     in
291       force_ty metasenv subst context orig t infty expty
292   in
293     typeof_aux metasenv subst context expty term
294
295 and eat_prods localise metasenv subst context orig_he he ty_he args =
296   let rec aux metasenv subst args_so_far ty_he = function 
297   | [] -> metasenv, subst, NCic.Appl (he :: List.rev args_so_far), ty_he
298   | arg::tl ->
299       match NCicReduction.whd ~subst context ty_he with 
300       | C.Prod (_,s,t) ->
301           let metasenv, subst, arg, _ = 
302             typeof ~localise metasenv subst context arg (Some s) in
303           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
304           aux metasenv subst (arg :: args_so_far) t tl
305       | t ->
306           let metasenv, subst, arg, ty_arg = 
307             typeof ~localise metasenv subst context arg None in
308           let metasenv, meta, _ = 
309             NCicMetaSubst.mk_meta metasenv 
310               (("_",C.Decl ty_arg) :: context) `Type
311           in
312           let flex_prod = C.Prod ("_", ty_arg, meta) in
313           prerr_endline ("F:" ^
314           (NCicPp.ppterm ~metasenv ~subst ~context t) ^  " === " ^
315           (NCicPp.ppterm ~metasenv ~subst ~context flex_prod) ^ "\nMENV:\n" ^
316           NCicPp.ppmetasenv ~subst metasenv ^ "\nCTX:\n" ^
317           NCicPp.ppcontext ~metasenv ~subst context);
318           let metasenv, subst = 
319              try NCicUnification.unify metasenv subst context t flex_prod 
320              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
321               ("The term %s is here applied to %d arguments but expects " ^^
322               "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
323               (List.length args) (List.length args_so_far))) exc)
324               (* XXX coerce to funclass *)
325           in
326           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
327           aux metasenv subst (arg :: args_so_far) meta tl
328   in
329    aux metasenv subst [] ty_he args
330 ;;
331 (* vim:set foldmethod=marker: *)