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