]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
Benchmarking integrated in folding/unfolding.
[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 debug = ref false;;
22 let indent = ref "";;
23 let times = ref [];;
24 let pp s =
25  if !debug then
26   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
27  else 
28   ()
29 ;;
30 let inside c =
31  if !debug then
32   begin
33    let time1 = Unix.gettimeofday () in
34    indent := !indent ^ String.make 1 c;
35    times := time1 :: !times;
36    prerr_endline ("{{{" ^ !indent ^ " ")
37   end
38 ;;
39 let outside ok =
40  if !debug then
41   begin
42    let time2 = Unix.gettimeofday () in
43    let time1 =
44     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
45    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
46    if not ok then prerr_endline "exception raised!";
47    try
48     indent := String.sub !indent 0 (String.length !indent -1)
49    with
50     Invalid_argument _ -> indent := "??"; ()
51  end
52 ;;
53
54
55 let wrap_exc msg = function
56   | NCicUnification.Uncertain _ -> Uncertain msg
57   | NCicUnification.UnificationFailure _ -> RefineFailure msg
58   | NCicTypeChecker.TypeCheckerFailure _ -> RefineFailure msg
59   | e -> raise e
60 ;;
61
62 let exp_implicit rdb ~localise metasenv subst context expty t =
63  let foo x = function Some t -> `WithType t | None -> x in
64  function      
65   | `Closed ->
66       let metasenv,subst,expty =
67        match expty with
68           None -> metasenv,subst,None
69         | Some typ ->
70            let (metasenv,subst),typ =
71             try
72              NCicMetaSubst.delift
73               ~unify:(fun m s c t1 t2 ->
74                 try Some (NCicUnification.unify rdb m s c t1 t2)
75                 with NCicUnification.UnificationFailure _ | NCicUnification.Uncertain _ -> None)
76               metasenv subst context 0 (0,NCic.Irl 0) typ
77             with
78               NCicMetaSubst.MetaSubstFailure _
79             | NCicMetaSubst.Uncertain _ ->
80                raise (RefineFailure (lazy (localise t,"Trying to create a closed meta with a non closed type")))
81
82            in
83             metasenv,subst,Some typ
84       in
85        NCicMetaSubst.mk_meta metasenv [] (foo `Term expty),subst
86   | `Type -> NCicMetaSubst.mk_meta metasenv context (foo `Type expty),subst
87   | `Term -> NCicMetaSubst.mk_meta metasenv context (foo `Term expty),subst
88   | `Tagged s ->
89       NCicMetaSubst.mk_meta ~attrs:[`Name s] metasenv context (foo `Term expty),subst
90   | `Vector ->
91       raise (RefineFailure (lazy (localise t, "A vector of implicit terms " ^
92        "can only be used in argument position")))
93   | _ -> assert false
94 ;;
95
96 let check_allowed_sort_elimination rdb localise r orig =
97    let mkapp he arg =
98      match he with
99      | C.Appl l -> C.Appl (l @ [arg])
100      | t -> C.Appl [t;arg] in
101    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
102    let rec aux metasenv subst context ind arity1 arity2 =
103      (*D*)inside 'S'; try let rc = 
104      let arity1 = NCicReduction.whd ~subst context arity1 in
105      pp (lazy(NCicPp.ppterm ~subst ~metasenv ~context arity1 ^ "   elimsto   " ^
106         NCicPp.ppterm ~subst ~metasenv ~context arity2 ^ "\nMENV:\n"^
107         NCicPp.ppmetasenv ~subst metasenv));
108      match arity1 with
109      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
110         let metasenv, _, meta, _ = 
111           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `Type 
112         in
113         let metasenv, subst = 
114           try NCicUnification.unify rdb metasenv subst context 
115                 arity2 (C.Prod (name, so1, meta)) 
116           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
117             "expected %s, found %s" (* XXX localizzare meglio *)
118             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod (name, so1, meta)))
119             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
120         in
121         aux metasenv subst ((name, C.Decl so1)::context)
122          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
123      | C.Sort _ (* , t ==?== C.Prod _ *) ->
124         let metasenv, _, meta, _ = NCicMetaSubst.mk_meta metasenv [] `Type in
125         let metasenv, subst = 
126           try NCicUnification.unify rdb metasenv subst context 
127                 arity2 (C.Prod ("_", ind, meta)) 
128           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
129             "expected %s, found %s" (* XXX localizzare meglio *)
130             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta)))
131             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
132         in
133         (try NCicTypeChecker.check_allowed_sort_elimination
134             ~metasenv ~subst r context ind arity1 arity2; 
135             metasenv, subst
136         with exc -> raise (wrap_exc (lazy (localise orig, 
137           "Sort elimination not allowed ")) exc))
138      | _ -> assert false
139      (*D*)in outside true; rc with exc -> outside false; raise exc
140    in
141     aux
142 ;;
143
144 let rec typeof rdb 
145   ?(localise=fun _ -> Stdpp.dummy_loc) 
146   metasenv subst context term expty 
147 =
148   let force_ty skip_lambda skip_appl metasenv subst context orig t infty expty =
149     (*D*)inside 'F'; try let rc = 
150     match expty with
151     | Some expty ->
152        (match t with
153        | C.Implicit _ -> assert false
154        | C.Lambda _ when skip_lambda -> metasenv, subst, t, expty
155        | C.Appl _ when skip_appl -> metasenv, subst, t, expty
156        | _ ->
157           pp (lazy ("forcing infty=expty: "^
158           (NCicPp.ppterm ~metasenv ~subst ~context infty) ^  " === " ^
159           (NCicPp.ppterm ~metasenv ~subst:[] ~context expty)));
160            try 
161              let metasenv, subst =
162     (*D*)inside 'U'; try let rc = 
163                NCicUnification.unify rdb metasenv subst context infty expty 
164     (*D*)in outside true; rc with exc -> outside false; raise exc
165              in
166              metasenv, subst, t, expty
167            with 
168            | NCicUnification.Uncertain _ 
169            | NCicUnification.UnificationFailure _ as exc -> 
170              try_coercions rdb ~localise 
171                metasenv subst context t orig infty expty true exc)
172     | None -> metasenv, subst, t, infty
173     (*D*)in outside true; rc with exc -> outside false; raise exc
174   in
175   let rec typeof_aux metasenv subst context expty = 
176     fun t as orig -> 
177     (*D*)inside 'R'; try let rc = 
178     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " ::exp:: " ^
179        match expty with None -> "None" | Some e -> 
180        NCicPp.ppterm ~metasenv ~subst ~context e));
181     let metasenv, subst, t, infty = 
182     match t with
183     | C.Rel n ->
184         let infty = 
185          (try
186            match List.nth context (n - 1) with
187            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
188            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
189          with Failure _ -> 
190            raise (RefineFailure (lazy (localise t,"unbound variable"))))
191         in
192         metasenv, subst, t, infty
193     | C.Sort s -> 
194          (try metasenv, subst, t, C.Sort (NCicEnvironment.typeof_sort s)
195          with 
196          | NCicEnvironment.UntypableSort msg -> 
197               raise (RefineFailure (lazy (localise t, Lazy.force msg)))
198          | NCicEnvironment.AssertFailure msg -> raise (AssertFailure msg))
199     | C.Implicit infos -> 
200          let (metasenv,_,t,ty),subst =
201            exp_implicit rdb ~localise metasenv subst context expty t infos
202          in
203           metasenv, subst, t, ty 
204     | C.Meta (n,l) as t -> 
205        let ty =
206         try
207          let _,_,_,ty = NCicUtils.lookup_subst n subst in ty 
208         with NCicUtils.Subst_not_found _ -> try
209          let _,_,ty = NCicUtils.lookup_meta n metasenv in 
210          match ty with C.Implicit _ -> 
211                  prerr_endline (string_of_int n);
212                  prerr_endline (NCicPp.ppmetasenv ~subst metasenv);
213                  prerr_endline (NCicPp.ppsubst ~metasenv subst);
214                  assert false | _ -> ty 
215         with NCicUtils.Meta_not_found _ ->
216          raise (AssertFailure (lazy (Printf.sprintf
217           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
218        in
219        metasenv, subst, t, NCicSubstitution.subst_meta l ty
220     | C.Const _ -> 
221        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
222     | C.Prod (name,(s as orig_s),(t as orig_t)) ->
223        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
224        let metasenv, subst, s, s1 = 
225          force_to_sort rdb 
226            metasenv subst context s orig_s localise s1 in
227        let context1 = (name,(C.Decl s))::context in
228        let metasenv, subst, t, s2 = typeof_aux metasenv subst context1 None t in
229        let metasenv, subst, t, s2 = 
230          force_to_sort rdb 
231            metasenv subst context1 t orig_t localise s2 in
232        let metasenv, subst, s, t, ty = 
233          sort_of_prod localise metasenv subst 
234            context orig_s orig_t (name,s) t (s1,s2)
235        in
236        metasenv, subst, NCic.Prod(name,s,t), ty
237     | C.Lambda (n,(s as orig_s),t) as orig ->
238        let exp_s, exp_ty_t, force_after =
239          match expty with
240          | None -> None, None, false
241          | Some expty -> 
242              match NCicReduction.whd ~subst context expty with
243              | C.Prod (_,s,t) -> Some s, Some t, false
244              | _ -> None, None, true 
245        in
246        let metasenv, subst, s, ty_s = 
247          typeof_aux metasenv subst context None s in
248        let metasenv, subst, s, _ = 
249          force_to_sort rdb 
250            metasenv subst context s orig_s localise ty_s in
251        let (metasenv,subst), exp_ty_t = 
252          match exp_s with 
253          | Some exp_s -> 
254              (try 
255                pp(lazy("Force source to: "^NCicPp.ppterm ~metasenv ~subst
256                   ~context exp_s));
257                NCicUnification.unify rdb metasenv subst context s exp_s,exp_ty_t
258              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
259                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
260                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
261                exp_s))) exc))
262          | None -> (metasenv, subst), None
263        in
264        let context_for_t = (n,C.Decl s) :: context in
265        let metasenv, subst, t, ty_t = 
266          typeof_aux metasenv subst context_for_t exp_ty_t t 
267        in
268        if force_after then
269          force_ty false true metasenv subst context orig 
270            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
271        else 
272          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
273     | C.LetIn (n,(ty as orig_ty),t,bo) ->
274        let metasenv, subst, ty, ty_ty = 
275          typeof_aux metasenv subst context None ty in
276        let metasenv, subst, ty, _ = 
277          force_to_sort rdb
278            metasenv subst context ty orig_ty localise ty_ty in
279        let metasenv, subst, t, _ = 
280          typeof_aux metasenv subst context (Some ty) t in
281        let context1 = (n, C.Def (t,ty)) :: context in
282        let metasenv, subst, expty1 = 
283          match expty with 
284          | None -> metasenv, subst, None 
285          | Some x -> 
286              let m, s, x = 
287                NCicUnification.delift_type_wrt_terms 
288                 rdb metasenv subst context1 (NCicSubstitution.lift 1 x)
289                 [NCicSubstitution.lift 1 t]
290              in
291                m, s, Some x
292        in
293        let metasenv, subst, bo, bo_ty = 
294          typeof_aux metasenv subst context1 expty1 bo 
295        in
296        let bo_ty = NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty in
297        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
298     | C.Appl ((he as orig_he)::(_::_ as args)) ->
299        let upto = match orig_he with C.Meta _ -> List.length args | _ -> 0 in
300        let hbr t = 
301          if upto > 0 then NCicReduction.head_beta_reduce ~upto t else t 
302        in
303        let refine_appl () =
304          let metasenv, subst, he, ty_he = 
305             typeof_aux metasenv subst context None he in
306          let metasenv, subst, t, ty = 
307            eat_prods rdb ~localise force_ty metasenv subst context expty t
308             orig_he he ty_he args in
309          metasenv, subst, hbr t, ty
310        in
311        if args = [C.Implicit `Vector] && expty <> None then
312          (* we try here to expand the vector a 0 implicits, but we use
313           * the expected type *)
314          try
315            let metasenv, subst, he, ty_he = 
316               typeof_aux metasenv subst context expty he in
317            metasenv, subst, hbr he, ty_he
318          with Uncertain _ | RefineFailure _ -> refine_appl ()
319        else refine_appl ()
320    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
321    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
322           outtype,(term as orig_term),pl) as orig ->
323       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
324       let _, _, arity, cl = List.nth itl tyno in
325       let constructorsno = List.length cl in
326       let _, metasenv, args = 
327         NCicMetaSubst.saturate metasenv subst context arity 0 in
328       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
329       let metasenv, subst, term, _ = 
330         typeof_aux metasenv subst context (Some ind) term in
331       let parameters, arguments = HExtlib.split_nth leftno args in
332       let outtype =  
333         match outtype with
334         | C.Implicit _ as ot -> 
335              let rec aux = function
336                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
337                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
338              in
339                aux arguments
340         | _ -> outtype
341       in 
342       let metasenv, subst, outtype, outsort = 
343         typeof_aux metasenv subst context None outtype in
344
345       (* next lines are to do a subst-expansion of the outtype, so
346          that when it becomes a beta-abstraction, the beta-redex is
347          fired during substitution *)
348       (*CSC: this is instantiate! should we move it from tactics to the
349              refiner? I think so! *)
350       let metasenv,metanoouttype,newouttype,metaoutsort =
351        NCicMetaSubst.mk_meta metasenv context `Term in
352       let metasenv,subst =
353        NCicUnification.unify rdb metasenv subst context outsort metaoutsort in
354       let metasenv =
355        List.filter (function (j,_) -> j <> metanoouttype) metasenv in
356       let subst =
357        (metanoouttype,([`Name "outtype"],context,outtype,metaoutsort))::subst in
358       let outtype = newouttype in
359
360       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
361       let ind =
362         if parameters = [] then C.Const r
363         else C.Appl ((C.Const r)::parameters) in
364       let metasenv, subst, ind, ind_ty = 
365         typeof_aux metasenv subst context None ind in
366       let metasenv, subst = 
367          check_allowed_sort_elimination rdb localise r orig_term metasenv subst 
368            context ind ind_ty outsort 
369       in
370       (* let's check if the type of branches are right *)
371       if List.length pl <> constructorsno then
372        raise (RefineFailure (lazy (localise orig, 
373          "Wrong number of cases in a match")));
374 (*
375       let metasenv, subst =
376         match expty with
377         | None -> metasenv, subst
378         | Some expty -> 
379            NCicUnification.unify rdb metasenv subst context resty expty 
380       in
381 *)
382       let _, metasenv, subst, pl =
383         List.fold_right
384           (fun p (j, metasenv, subst, branches) ->
385               let cons = 
386                 let cons = Ref.mk_constructor j r in
387                 if parameters = [] then C.Const cons
388                 else C.Appl (C.Const cons::parameters)
389               in
390               let metasenv, subst, cons, ty_cons = 
391                 typeof_aux metasenv subst context None cons in
392               let ty_branch = 
393                 NCicTypeChecker.type_of_branch 
394                   ~subst context leftno outtype cons ty_cons in
395               pp (lazy ("TYPEOFBRANCH: " ^
396                NCicPp.ppterm ~metasenv ~subst ~context p ^ " ::inf:: " ^
397                NCicPp.ppterm ~metasenv ~subst ~context ty_branch ));
398               let metasenv, subst, p, _ = 
399                 typeof_aux metasenv subst context (Some ty_branch) p in
400               j-1, metasenv, subst, p :: branches)
401           pl (List.length pl, metasenv, subst, [])
402       in
403       let resty = C.Appl (outtype::arguments@[term]) in
404       let resty = NCicReduction.head_beta_reduce ~subst resty in
405       metasenv, subst, C.Match (r, outtype, term, pl),resty
406     | C.Match _ -> assert false
407     in
408     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " ::inf:: "^
409          NCicPp.ppterm ~metasenv ~subst ~context infty ));
410       force_ty true true metasenv subst context orig t infty expty
411     (*D*)in outside true; rc with exc -> outside false; raise exc
412   in
413     typeof_aux metasenv subst context expty term
414
415 and try_coercions rdb 
416   ~localise 
417   metasenv subst context t orig_t infty expty perform_unification exc 
418 =
419   (* we try with a coercion *)
420   let rec first exc = function
421   | [] ->         
422       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
423         "The term\n%s\nhas type\n%s\nbut is here used with type\n%s"
424         (NCicPp.ppterm ~metasenv ~subst ~context t)
425         (NCicPp.ppterm ~metasenv ~subst ~context infty)
426         (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
427   | (_,metasenv, newterm, newtype, meta)::tl ->
428       try 
429           pp (lazy("K=" ^ NCicPp.ppterm ~metasenv ~subst ~context newterm));
430           pp (lazy ( "UNIFICATION in CTX:\n"^ 
431             NCicPp.ppcontext ~metasenv ~subst context
432             ^ "\nMENV: " ^
433             NCicPp.ppmetasenv metasenv ~subst
434             ^ "\nOF: " ^
435             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
436             NCicPp.ppterm ~metasenv ~subst ~context meta ^ "\n"));
437         let metasenv, subst = 
438           NCicUnification.unify rdb metasenv subst context t meta
439         in
440           pp (lazy ( "UNIFICATION in CTX:\n"^ 
441             NCicPp.ppcontext ~metasenv ~subst context
442             ^ "\nMENV: " ^
443             NCicPp.ppmetasenv metasenv ~subst
444             ^ "\nOF: " ^
445             NCicPp.ppterm ~metasenv ~subst ~context newtype ^  " === " ^
446             NCicPp.ppterm ~metasenv ~subst ~context expty ^ "\n"));
447         let metasenv, subst = 
448           if perform_unification then
449             NCicUnification.unify rdb metasenv subst context newtype expty
450           else metasenv, subst
451         in
452         metasenv, subst, newterm, newtype
453       with 
454       | NCicUnification.UnificationFailure _ -> first exc tl
455       | NCicUnification.Uncertain _ as exc -> first exc tl
456   in 
457   pp(lazy("try_coercion " ^ 
458     NCicPp.ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
459     NCicPp.ppterm ~metasenv ~subst ~context expty));
460     first exc
461       (NCicCoercion.look_for_coercion 
462         rdb metasenv subst context infty expty)
463
464 and force_to_sort rdb metasenv subst context t orig_t localise ty =
465   match NCicReduction.whd ~subst context ty with
466   | C.Meta (_,(0,(C.Irl 0 | C.Ctx []))) as ty -> 
467      metasenv, subst, t, ty
468   | C.Meta (_i,(_,(C.Irl 0 | C.Ctx []))) -> assert false (*CSC: ???
469      metasenv, subst, t, C.Meta(i,(0,C.Irl 0)) *)
470   | C.Meta (i,(_,lc)) ->
471      let len = match lc with C.Irl len->len | C.Ctx l->List.length l in
472      let metasenv, subst, newmeta = 
473        if len > 0 then
474          NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 (len+1)) 
475        else metasenv, subst, i
476      in
477      metasenv, subst, t, C.Meta (newmeta,(0,C.Irl 0))
478   | C.Sort _ as ty -> metasenv, subst, t, ty 
479   | ty -> 
480       try_coercions rdb ~localise metasenv subst context
481         t orig_t ty (NCic.Sort (NCic.Type NCicEnvironment.type0)) false 
482          (Uncertain (lazy (localise orig_t, 
483          "The type of " ^ NCicPp.ppterm ~metasenv ~subst ~context t
484          ^ " is not a sort: " ^ NCicPp.ppterm ~metasenv ~subst ~context ty)))
485
486 and sort_of_prod 
487   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
488 =
489    (* force to sort is done in the Prod case in typeof *)
490    match t1, t2 with
491    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
492    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
493         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
494    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
495    | C.Meta _, C.Sort _ 
496    | C.Meta _, C.Meta (_,(_,_))
497    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
498    | x, (C.Sort _ | C.Meta _) | _, x -> 
499       let y, context, orig = 
500         if x == t1 then s, context, orig_s 
501         else t, ((name,C.Decl s)::context), orig_t
502       in
503       raise (RefineFailure (lazy (localise orig,Printf.sprintf
504         "%s is expected to be a type, but its type is %s that is not a sort" 
505          (NCicPp.ppterm ~subst ~metasenv ~context y) 
506          (NCicPp.ppterm ~subst ~metasenv ~context x))))
507
508 and guess_name subst ctx ty = 
509   let aux initial = "#" ^ String.make 1 initial in
510   match ty with
511   | C.Const (NReference.Ref (u,_))
512   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
513       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
514   | C.Prod _ -> aux 'f' 
515   | C.Meta (n,lc) -> 
516       (try
517          let _,_,t,_ = NCicUtils.lookup_subst n subst in
518          guess_name subst ctx (NCicSubstitution.subst_meta lc t)
519       with NCicUtils.Subst_not_found _ -> aux 'M')
520   | _ -> aux 'H' 
521
522 and eat_prods rdb ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
523   (*D*)inside 'E'; try let rc = 
524   let rec aux metasenv subst args_so_far he ty_he xxx =
525   (*D*)inside 'V'; try let rc = 
526    match xxx with
527   | [] ->
528      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
529      pp(lazy("FORCE FINAL APPL: " ^ 
530        NCicPp.ppterm ~metasenv ~subst ~context res ^
531        " of type " ^ NCicPp.ppterm ~metasenv ~subst ~context ty_he
532        ^ " to type " ^ match expty with None -> "None" | Some x -> 
533        NCicPp.ppterm ~metasenv ~subst ~context x));
534      (* whatever the term is, we force the type. in case of ((Lambda..) ?...)
535       * the application may also be a lambda! *)
536      force_ty false false metasenv subst context orig_t res ty_he expty
537   | NCic.Implicit `Vector::tl ->
538       let has_some_more_pis x =
539         match NCicReduction.whd ~subst context x with
540         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
541         | _ -> true
542       in
543      (try
544        aux metasenv subst args_so_far he ty_he tl
545       with
546       | Uncertain _
547       | RefineFailure _ as exc when has_some_more_pis ty_he ->
548           (try
549            aux metasenv subst args_so_far he ty_he
550             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
551           with
552            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc))
553      | RefineFailure msg when not (has_some_more_pis ty_he) ->
554         (* instantiating the head could change the has_some_more_pis flag *)
555         raise (Uncertain msg))
556   | arg::tl ->
557       match NCicReduction.whd ~subst context ty_he with 
558       | C.Prod (_,s,t) ->
559           let metasenv, subst, arg, _ = 
560             typeof rdb ~localise metasenv subst context arg (Some s) in
561           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
562           aux metasenv subst (arg :: args_so_far) he t tl
563       | C.Meta _
564       | C.Appl (C.Meta _ :: _) as t ->
565           let metasenv, subst, arg, ty_arg = 
566             typeof rdb ~localise metasenv subst context arg None in
567           let name = guess_name subst context ty_arg in
568           let metasenv, _, meta, _ = 
569             NCicMetaSubst.mk_meta metasenv 
570               ((name,C.Decl ty_arg) :: context) `Type
571           in
572           let flex_prod = C.Prod (name, ty_arg, meta) in
573           (* next line grants that ty_args is a type *)
574           let metasenv,subst, flex_prod, _ =
575            typeof rdb ~localise metasenv subst context flex_prod None in
576 (*
577           pp (lazy ( "UNIFICATION in CTX:\n"^ 
578             NCicPp.ppcontext ~metasenv ~subst context
579             ^ "\nOF: " ^
580             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
581             NCicPp.ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
582 *)
583           let metasenv, subst =
584              try NCicUnification.unify rdb metasenv subst context t flex_prod 
585              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
586               ("The term %s has an inferred type %s, but is applied to the" ^^
587                " argument %s of type %s")
588               (NCicPp.ppterm ~metasenv ~subst ~context he)
589               (NCicPp.ppterm ~metasenv ~subst ~context t)
590               (NCicPp.ppterm ~metasenv ~subst ~context arg)
591               (NCicPp.ppterm ~metasenv ~subst ~context ty_arg))) 
592                  (match exc with
593                  | NCicUnification.UnificationFailure m -> 
594                      NCicUnification.Uncertain m
595                  | x -> x))
596               (* XXX coerce to funclass *)
597           in
598           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
599           aux metasenv subst (arg :: args_so_far) he meta tl
600       | C.Match (_,_,C.Meta _,_) 
601       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
602       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
603           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
604             ("The term %s is here applied to %d arguments but expects " ^^
605             "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
606             (List.length args) (List.length args_so_far))))
607       | ty ->
608           let metasenv, subst, newhead, newheadty = 
609             try_coercions rdb ~localise metasenv subst context
610               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
611               (NCic.Prod ("_",NCic.Implicit `Term,NCic.Implicit `Term))
612               false
613               (RefineFailure (lazy (localise orig_he, Printf.sprintf
614                ("The term %s is here applied to %d arguments but expects " ^^
615                "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
616                (List.length args) (List.length args_so_far))))
617           in
618            aux metasenv subst [] newhead newheadty (arg :: tl)
619   (*D*)in outside true; rc with exc -> outside false; raise exc
620   in
621    (* We need to reverse the order of the new created metas since they
622       are pushed on top of the metasenv in the wrong order *)
623    let highest_meta = NCicMetaSubst.maxmeta () in
624    let metasenv, subst, newhead, newheadty = 
625     aux metasenv subst [] he ty_he args in
626    let metasenv_old,metasenv_new =
627     List.partition (fun (i,_) -> i <= highest_meta) metasenv
628    in
629     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
630   (*D*)in outside true; rc with exc -> outside false; raise exc
631 ;;
632
633 let rec first f l1 l2 =
634   match l1,l2 with
635   | x1::tl1, x2::tl2 -> 
636       (try f x1 x2 with Not_found -> first f tl1 tl2)
637   | _ -> raise Not_found
638 ;;
639
640 let rec find add dt t =
641   if dt == add then t
642   else
643     let dl, l = 
644       match dt, t with
645       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
646       | C.Appl dl,C.Appl l -> dl,l
647       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
648       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
649       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
650       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
651       | _ -> raise Not_found
652     in
653       first (find add) dl l
654 ;;
655
656 let relocalise old_localise dt t add = 
657   old_localise 
658     (try find add dt t with Not_found -> assert false)
659 ;;
660
661 let undebruijnate inductive ref t rev_fl =
662   NCicSubstitution.psubst (fun x -> x) 
663    (List.rev (HExtlib.list_mapi 
664       (fun (_,_,rno,_,_,_) i -> 
665          NCic.Const 
666            (if inductive then NReference.mk_fix i rno ref
667             else NReference.mk_cofix i ref))
668       rev_fl))
669     t
670 ;; 
671
672
673 let typeof_obj 
674   rdb ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
675
676   let check_type metasenv subst context (ty as orig_ty) =  (* XXX fattorizza *)
677     let metasenv, subst, ty, sort = 
678       typeof rdb ~localise metasenv subst context ty None
679     in
680     let metasenv, subst, ty, sort = 
681       force_to_sort rdb metasenv subst context ty orig_ty localise sort
682     in
683       metasenv, subst, ty, sort
684   in
685   match obj with 
686   | C.Constant (relevance, name, bo, ty , attr) ->
687        let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
688        let metasenv, subst, bo, ty, height = 
689          match bo with
690          | Some bo ->
691              let metasenv, subst, bo, ty = 
692                typeof rdb ~localise metasenv subst [] bo (Some ty) in
693              let height = (* XXX recalculate *) height in
694                metasenv, subst, Some bo, ty, height
695          | None -> metasenv, subst, None, ty, 0
696        in
697        uri, height, metasenv, subst, 
698          C.Constant (relevance, name, bo, ty, attr)
699   | C.Fixpoint (inductive, fl, attr) -> 
700       let len = List.length fl in
701       let types, metasenv, subst, rev_fl =
702         List.fold_left
703          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
704            let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
705            let dbo = NCicTypeChecker.debruijn uri len [] ~subst bo in
706            let localise = relocalise localise dbo bo in
707             (name,C.Decl ty)::types,
708               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
709          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
710       in
711       let metasenv, subst, fl = 
712         List.fold_left 
713           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
714             let metasenv, subst, dbo, ty = 
715               typeof rdb ~localise metasenv subst types dbo (Some ty)
716             in
717             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
718           (metasenv, subst, []) rev_fl
719       in
720       let height = (* XXX recalculate *) height in
721       let fl =
722         List.map 
723           (fun (relevance,name,k,ty,dbo) ->
724             let bo = 
725               undebruijnate inductive 
726                (NReference.reference_of_spec uri 
727                  (if inductive then NReference.Fix (0,k,0) 
728                   else NReference.CoFix 0)) dbo rev_fl
729             in
730               relevance,name,k,ty,bo)
731           fl
732       in
733        uri, height, metasenv, subst, 
734          C.Fixpoint (inductive, fl, attr)
735   | C.Inductive (ind, leftno, itl, attr) ->
736      let len = List.length itl in
737      let metasenv,subst,rev_itl,tys =
738       List.fold_left
739        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
740           let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
741           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
742        ) (metasenv,subst,[],[]) itl in
743      let metasenv,subst,itl,_ =
744       List.fold_left
745        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
746          let context,ty_sort = NCicReduction.split_prods ~subst [] ~-1 ty in
747          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
748          let metasenv,subst,cl =
749           List.fold_right
750            (fun (k_relev,n,te) (metasenv,subst,res) ->
751              let k_relev =
752               try snd (HExtlib.split_nth leftno k_relev)
753               with Failure _ -> k_relev in
754              let te = NCicTypeChecker.debruijn uri len [] ~subst te in
755              let metasenv, subst, te, _ = check_type metasenv subst tys te in
756              let context,te = NCicReduction.split_prods ~subst tys leftno te in
757              let _,chopped_context_rev =
758               HExtlib.split_nth (List.length tys) (List.rev context) in
759              let sx_context_te_rev,_ =
760               HExtlib.split_nth leftno chopped_context_rev in
761              let metasenv,subst,_ =
762               try
763                List.fold_left2
764                 (fun (metasenv,subst,context) item1 item2 ->
765                   let (metasenv,subst),convertible =
766                    try
767                     match item1,item2 with
768                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
769                         if n1 = n2 then
770                          NCicUnification.unify rdb ~test_eq_only:true metasenv
771                           subst context ty1 ty2,true
772                         else
773                          (metasenv,subst),false
774                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
775                         if n1 = n2 then
776                          let metasenv,subst =
777                           NCicUnification.unify rdb ~test_eq_only:true metasenv
778                            subst context ty1 ty2
779                          in
780                           NCicUnification.unify rdb ~test_eq_only:true metasenv
781                            subst context bo1 bo2,true
782                         else
783                          (metasenv,subst),false
784                     | _,_ -> (metasenv,subst),false
785                    with
786                    | NCicUnification.Uncertain _
787                    | NCicUnification.UnificationFailure _ ->
788                       (metasenv,subst),false
789                   in
790                    let term2 =
791                     match item2 with
792                        _,C.Decl t -> t
793                      | _,C.Def (b,_) -> b in
794                    if not convertible then
795                     raise (RefineFailure (lazy (localise term2,
796                      ("Mismatch between the left parameters of the constructor " ^
797                       "and those of its inductive type"))))
798                    else
799                     metasenv,subst,item1::context
800                 ) (metasenv,subst,tys) sx_context_ty_rev sx_context_te_rev
801               with Invalid_argument "List.fold_left2" -> assert false in
802              let con_sort= NCicTypeChecker.typeof ~subst ~metasenv context te in
803               (match
804                 NCicReduction.whd ~subst context con_sort,
805                 NCicReduction.whd ~subst [] ty_sort
806                with
807                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
808                    if not (NCicEnvironment.universe_leq u1 u2) then
809                     raise
810                      (RefineFailure
811                        (lazy(localise te, "The type " ^
812                          NCicPp.ppterm ~metasenv ~subst ~context s1 ^
813                          " of the constructor is not included in the inductive"^
814                          " type sort " ^
815                          NCicPp.ppterm ~metasenv ~subst ~context s2)))
816                 | C.Sort _, C.Sort C.Prop
817                 | C.Sort _, C.Sort C.Type _ -> ()
818                 | _, _ ->
819                    raise
820                     (RefineFailure
821                       (lazy (localise te,
822                         "Wrong constructor or inductive arity shape"))));
823               (* let's check also the positivity conditions *)
824               if 
825                not
826                (NCicTypeChecker.are_all_occurrences_positive
827                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
828               then
829                 raise
830                   (RefineFailure
831                     (lazy (localise te,
832                       "Non positive occurence in " ^
833                         NCicPp.ppterm ~metasenv ~subst ~context te)))
834               else
835                let relsno = List.length itl + leftno in
836                let te = 
837                  NCicSubstitution.psubst 
838                   (fun i ->
839                     if i <= leftno  then
840                      NCic.Rel i
841                     else
842                      NCic.Const (NReference.reference_of_spec uri
843                       (NReference.Ind (ind,relsno - i,leftno))))
844                   (HExtlib.list_seq 1 (relsno+1))
845                    te in
846                let te =
847                 List.fold_right
848                  (fun (name,decl) te ->
849                    match decl with
850                       NCic.Decl ty -> NCic.Prod (name,ty,te)
851                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
852                  ) sx_context_te_rev te
853                in
854                 metasenv,subst,(k_relev,n,te)::res
855               ) cl (metasenv,subst,[])
856          in
857           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
858        ) (metasenv,subst,[],1) rev_itl
859      in
860       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
861 ;;
862
863 let typeof st ?localise m s c t1 t2 =
864 let time1 = Unix.gettimeofday () in
865 let res = typeof st ?localise m s c t1 t2 in
866 let time2 = Unix.gettimeofday () in
867 prerr_endline ("OVERALL TYPEOF TIME: " ^ string_of_float (time2 -. time1));
868 res
869 ;;
870
871 (* vim:set foldmethod=marker: *)