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