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