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