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