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