]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_refiner/nCicRefiner.ml
Name generator for Russell greatly improved.
[helm.git] / matita / 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 ;;
28 let inside c =
29  if !debug then
30   begin
31    let time1 = Unix.gettimeofday () in
32    indent := !indent ^ String.make 1 c;
33    times := time1 :: !times;
34    prerr_endline ("{{{" ^ !indent ^ " ")
35   end
36 ;;
37 let outside ok =
38  if !debug then
39   begin
40    let time2 = Unix.gettimeofday () in
41    let time1 =
42     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
43    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
44    if not ok then prerr_endline "exception raised!";
45    try
46     indent := String.sub !indent 0 (String.length !indent -1)
47    with
48     Invalid_argument _ -> indent := "??"; ()
49  end
50 ;;
51
52
53 let wrap_exc msg = function
54   | NCicUnification.Uncertain _ -> Uncertain msg
55   | NCicUnification.UnificationFailure _ -> RefineFailure msg
56   | NCicTypeChecker.TypeCheckerFailure _ -> RefineFailure msg
57   | e -> raise e
58 ;;
59
60 let exp_implicit status ~localise metasenv subst context with_type t =
61  function      
62   | `Closed ->
63       let metasenv,subst,expty =
64        match with_type with
65           None -> metasenv,subst,None
66         | Some typ ->
67            let (metasenv,subst),typ =
68             try
69              NCicMetaSubst.delift status
70               ~unify:(fun m s c t1 t2 ->
71                 try Some (NCicUnification.unify status m s c t1 t2)
72                 with NCicUnification.UnificationFailure _ | NCicUnification.Uncertain _ -> None)
73               metasenv subst context 0 (0,NCic.Irl 0) typ
74             with
75               NCicMetaSubst.MetaSubstFailure _
76             | NCicMetaSubst.Uncertain _ ->
77                raise (RefineFailure (lazy (localise t,"Trying to create a closed meta with a non closed type: " ^ status#ppterm ~metasenv ~subst ~context typ)))
78
79            in
80             metasenv,subst,Some typ
81       in
82        NCicMetaSubst.mk_meta metasenv [] ?with_type:expty `IsTerm,subst
83   | `Type -> NCicMetaSubst.mk_meta metasenv context ?with_type `IsType,subst
84   | `Term -> NCicMetaSubst.mk_meta metasenv context ?with_type `IsTerm,subst
85   | `Tagged s ->
86       NCicMetaSubst.mk_meta 
87         ~attrs:[`Name s] metasenv context ?with_type `IsTerm,subst
88   | `Vector ->
89       raise (RefineFailure (lazy (localise t, "A vector of implicit terms " ^
90        "can only be used in argument position")))
91   | _ -> assert false
92 ;;
93
94 let check_allowed_sort_elimination status localise r orig =
95    let mkapp he arg =
96      match he with
97      | C.Appl l -> C.Appl (l @ [arg])
98      | t -> C.Appl [t;arg] in
99    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
100    let rec aux metasenv subst context ind arity1 arity2 =
101      (*D*)inside 'S'; try let rc = 
102      let arity1 = NCicReduction.whd status ~subst context arity1 in
103      pp (lazy(status#ppterm ~subst ~metasenv ~context arity1 ^ "   elimsto   " ^
104         status#ppterm ~subst ~metasenv ~context arity2 ^ "\nMENV:\n"^
105         status#ppmetasenv ~subst metasenv));
106      match arity1 with
107      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
108         let metasenv, _, meta, _ = 
109           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `IsType 
110         in
111         let metasenv, subst = 
112           try NCicUnification.unify status metasenv subst context 
113                 arity2 (C.Prod (name, so1, meta)) 
114           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
115             "expected %s, found %s" (* XXX localizzare meglio *)
116             (status#ppterm ~subst ~metasenv ~context (C.Prod (name, so1, meta)))
117             (status#ppterm ~subst ~metasenv ~context arity2))) exc)
118         in
119         aux metasenv subst ((name, C.Decl so1)::context)
120          (mkapp (NCicSubstitution.lift status 1 ind) (C.Rel 1)) de1 meta
121      | C.Sort _ (* , t ==?== C.Prod _ *) ->
122         let metasenv, _, meta, _ = NCicMetaSubst.mk_meta metasenv [] `IsSort in
123         let metasenv, subst = 
124           try NCicUnification.unify status metasenv subst context 
125                 arity2 (C.Prod ("_", ind, meta)) 
126           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
127             "expected %s, found %s" (* XXX localizzare meglio *)
128             (status#ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta)))
129             (status#ppterm ~subst ~metasenv ~context arity2))) exc)
130         in
131         (try NCicTypeChecker.check_allowed_sort_elimination status
132             ~metasenv ~subst r context ind arity1 arity2; 
133             metasenv, subst
134         with exc -> raise (wrap_exc (lazy (localise orig, 
135           "Sort elimination not allowed ")) exc))
136      | _ -> assert false
137      (*D*)in outside true; rc with exc -> outside false; raise exc
138    in
139     aux
140 ;;
141
142 (* CSC: temporary thing, waiting for better times *)
143 let mk_fresh_name context name =
144 try
145  let rex = Str.regexp "[0-9']*$" in
146  let basename = Str.global_replace rex "" in
147  let suffix name =
148   ignore (Str.search_forward rex name 0);
149   let n = Str.matched_string name in
150    if n = "" then 0 else int_of_string n in
151  let name' = basename name in
152  let name' = if name' = "_" then "H" else name' in
153  let last =
154   List.fold_left
155    (fun last (name,_) ->
156      if basename name = name' then
157       max last (suffix name)
158      else
159       last
160    ) (-1) context
161  in
162   name' ^ (if last = -1 then "" else string_of_int (last + 1))
163 with exn -> prerr_endline ("XXX" ^ Printexc.to_string exn); assert false
164
165 let rec typeof (status:#NCicCoercion.status)
166   ?(localise=fun _ -> Stdpp.dummy_loc) 
167   metasenv subst context term expty 
168 =
169   let force_ty skip_lambda skip_appl metasenv subst context orig t infty expty =
170     (*D*)inside 'F'; try let rc = 
171     match expty with
172     | Some expty ->
173        (match t with
174        | C.Implicit _ -> assert false
175        | C.Lambda _ when skip_lambda -> metasenv, subst, t, expty
176        | C.Appl _ when skip_appl -> metasenv, subst, t, expty
177        | _ ->
178           pp (lazy ("forcing infty=expty: "^
179           (status#ppterm ~metasenv ~subst ~context infty) ^  " === " ^
180           (status#ppterm ~metasenv ~subst:[] ~context expty)));
181            try 
182              let metasenv, subst =
183     (*D*)inside 'U'; try let rc = 
184                NCicUnification.unify status metasenv subst context infty expty 
185     (*D*)in outside true; rc with exc -> outside false; raise exc
186              in
187              metasenv, subst, t, expty
188            with 
189            | NCicUnification.Uncertain _ 
190            | NCicUnification.UnificationFailure _ as exc -> 
191              try_coercions status ~localise 
192                metasenv subst context t orig infty (`Type expty) exc)
193     | None -> metasenv, subst, t, infty
194     (*D*)in outside true; rc with exc -> outside false; raise exc
195   in
196   let rec typeof_aux metasenv subst context expty = 
197     fun t as orig -> 
198     (*D*)inside 'R'; try let rc = 
199     pp (lazy (status#ppterm ~metasenv ~subst ~context t ^ " ::exp:: " ^
200        match expty with None -> "None" | Some e -> 
201        status#ppterm ~metasenv ~subst ~context e));
202     let metasenv, subst, t, infty = 
203     match t with
204     | C.Rel n ->
205         let infty = 
206          (try
207            match List.nth context (n - 1) with
208            | (_,C.Decl ty) -> NCicSubstitution.lift status n ty
209            | (_,C.Def (_,ty)) -> NCicSubstitution.lift status n ty
210          with Failure _ -> 
211            raise (RefineFailure (lazy (localise t,"unbound variable"))))
212         in
213         metasenv, subst, t, infty
214     | C.Sort s -> 
215          (try metasenv, subst, t, C.Sort (NCicEnvironment.typeof_sort s)
216          with 
217          | NCicEnvironment.UntypableSort msg -> 
218               raise (RefineFailure (lazy (localise t, Lazy.force msg)))
219          | NCicEnvironment.AssertFailure msg -> raise (AssertFailure msg))
220     | C.Implicit infos -> 
221          let (metasenv,_,t,ty),subst =
222            exp_implicit status ~localise metasenv subst context expty t infos
223          in
224          if expty = None then
225           typeof_aux metasenv subst context None t
226          else
227           metasenv, subst, t, ty 
228     | C.Meta (n,l) as t -> 
229        let metasenv, ty =
230         try
231          let _,_,_,ty = NCicUtils.lookup_subst n subst in metasenv, ty 
232         with NCicUtils.Subst_not_found _ ->
233          NCicMetaSubst.extend_meta metasenv n
234        in
235        metasenv, subst, t, NCicSubstitution.subst_meta status l ty
236     | C.Const _ -> 
237        metasenv, subst, t, NCicTypeChecker.typeof status ~subst ~metasenv context t
238     | C.Prod (name,(s as orig_s),(t as orig_t)) ->
239        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
240        let metasenv, subst, s, s1 = 
241          force_to_sort status 
242            metasenv subst context s orig_s localise s1 in
243        let context1 = (name,(C.Decl s))::context in
244        let metasenv, subst, t, s2 = typeof_aux metasenv subst context1 None t in
245        let metasenv, subst, t, s2 = 
246          force_to_sort status 
247            metasenv subst context1 t orig_t localise s2 in
248        let metasenv, subst, s, t, ty = 
249          sort_of_prod status localise metasenv subst 
250            context orig_s orig_t (name,s) t (s1,s2)
251        in
252        metasenv, subst, NCic.Prod(name,s,t), ty
253     | C.Lambda (n,(s as orig_s),t) as orig ->
254        let exp_s, exp_ty_t, force_after =
255          match expty with
256          | None -> None, None, false
257          | Some expty -> 
258              match NCicReduction.whd status ~subst context expty with
259              | C.Prod (_,s,t) -> Some s, Some t, false
260              | _ -> None, None, true 
261        in
262        let (metasenv,subst), s = 
263          match exp_s with 
264          | Some exp_s ->
265              (* optimized case: implicit and implicitly typed meta
266               * the optimization prevents proliferation of metas  *)
267              (match s with
268               | C.Implicit _ -> (metasenv,subst),exp_s
269               | _ ->
270                   let metasenv, subst, s = match s with 
271                     | C.Meta (n,_) 
272                         when (try (match NCicUtils.lookup_meta n metasenv with
273                               | _,_,C.Implicit (`Typeof _) -> true
274                               | _ -> false)
275                         with 
276                           | _ -> false) -> metasenv, subst, s
277                     | _ ->  check_type status ~localise metasenv subst context s in
278                   (try 
279                     pp(lazy("Force source to: "^status#ppterm ~metasenv ~subst
280                        ~context exp_s));
281                     NCicUnification.unify ~test_eq_only:true status metasenv subst context s exp_s,s
282                   with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
283                     "Source type %s was expected to be %s" (status#ppterm ~metasenv
284                     ~subst ~context s) (status#ppterm ~metasenv ~subst ~context
285                     exp_s))) exc)))
286          | None -> 
287              let metasenv, subst, s = 
288                check_type status ~localise metasenv subst context s in
289              (metasenv, subst), s
290        in
291        let context_for_t = (n,C.Decl s) :: context in
292        let metasenv, subst, t, ty_t = 
293          typeof_aux metasenv subst context_for_t exp_ty_t t 
294        in
295        if force_after then
296          force_ty false true metasenv subst context orig 
297            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
298        else 
299          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
300     | C.LetIn (n,ty,t,bo) ->
301        let metasenv, subst, ty = 
302          check_type status ~localise metasenv subst context ty in
303        let metasenv, subst, t, _ = 
304          typeof_aux metasenv subst context (Some ty) t in
305        let context1 = (n, C.Def (t,ty)) :: context in
306        let metasenv, subst, expty1 = 
307          match expty with 
308          | None -> metasenv, subst, None 
309          | Some x -> 
310              let m, s, x = 
311                NCicUnification.delift_type_wrt_terms 
312                 status metasenv subst context1 (NCicSubstitution.lift status 1 x)
313                 [NCicSubstitution.lift status 1 t]
314              in
315                m, s, Some x
316        in
317        let metasenv, subst, bo, bo_ty = 
318          typeof_aux metasenv subst context1 expty1 bo 
319        in
320        let bo_ty = NCicSubstitution.subst status ~avoid_beta_redexes:true t bo_ty in
321        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
322     | C.Appl ((he as orig_he)::(_::_ as args)) ->
323        let upto = match orig_he with C.Meta _ -> List.length args | _ -> 0 in
324        let hbr t = 
325          if upto > 0 then NCicReduction.head_beta_reduce status ~upto t else t 
326        in
327        let refine_appl metasenv subst args =
328          let metasenv, subst, he, ty_he = 
329             typeof_aux metasenv subst context None he in
330          let metasenv, subst, t, ty = 
331            eat_prods status ~localise force_ty metasenv subst context expty t
332             orig_he he ty_he args in
333          metasenv, subst, hbr t, ty
334        in
335        if args = [C.Implicit `Vector] && expty <> None then
336          (* we try here to expand the vector a 0 implicits, but we use
337           * the expected type *)
338          try
339            let metasenv, subst, he, ty_he = 
340               typeof_aux metasenv subst context expty he in
341            metasenv, subst, hbr he, ty_he
342          with Uncertain _ | RefineFailure _ -> refine_appl metasenv subst args
343        else
344         (* CSC: whd can be useful on he too... *)
345         (match he with
346             C.Const (Ref.Ref (uri1,Ref.Con _)) -> (
347              match
348               HExtlib.map_option (NCicReduction.whd status ~subst context) expty
349              with
350                 Some (C.Appl(C.Const(Ref.Ref (uri2,Ref.Ind _) as ref)::expargs))
351                 when NUri.eq uri1 uri2 ->
352                 (try
353                  let _,leftno,_,_,_ = NCicEnvironment.get_checked_indtys status ref in
354                  let leftexpargs,_ = HExtlib.split_nth leftno expargs in
355                   let rec instantiate metasenv subst revargs args =
356                    function
357                      [] ->
358                       (* some checks are re-done here, but it would be complex
359                          to avoid them (e.g. we did not check yet that the
360                          constructor is a constructor for that inductive type)*)
361                       refine_appl metasenv subst ((List.rev revargs)@args)
362                    | (exparg::expargs) as allexpargs ->
363                       match args with
364                          [] -> raise (Failure "Not enough args")
365                        | (C.Implicit `Vector::args) as allargs ->
366                           (try
367                             instantiate metasenv subst revargs args allexpargs
368                            with
369                               Sys.Break as exn -> raise exn
370                             | _ ->
371                              instantiate metasenv subst revargs
372                               (C.Implicit `Term :: allargs) allexpargs)
373                        | arg::args ->
374                           let metasenv,subst,arg,_ =
375                            typeof_aux metasenv subst context None arg in
376                           let metasenv,subst =
377                            NCicUnification.unify status metasenv subst context
378                             arg exparg
379                           in
380                            instantiate metasenv subst(arg::revargs) args expargs
381                   in
382                    instantiate metasenv subst [] args leftexpargs 
383                 with
384                  | Sys.Break as exn -> raise exn
385                  | _ ->
386                     refine_appl metasenv subst args (* to try coercions *))
387               | _ -> refine_appl metasenv subst args)
388           | _ -> refine_appl metasenv subst args)
389    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
390    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
391           outtype,(term as orig_term),pl) as orig ->
392       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys status r in
393       let _, _, arity, cl = List.nth itl tyno in
394       let constructorsno = List.length cl in
395       let _, metasenv, args = 
396         NCicMetaSubst.saturate status metasenv subst context arity 0 in
397       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
398       let metasenv, subst, term, _ = 
399         typeof_aux metasenv subst context (Some ind) term in
400       let parameters, arguments = HExtlib.split_nth leftno args in
401       let outtype =  
402         match outtype with
403         | C.Implicit _ as ot -> 
404              let rec aux = function
405                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
406                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
407              in
408                aux arguments
409         | _ -> outtype
410       in 
411       let metasenv, subst, outtype, outsort = 
412         typeof_aux metasenv subst context None outtype in
413
414       (* next lines are to do a subst-expansion of the outtype, so
415          that when it becomes a beta-abstraction, the beta-redex is
416          fired during substitution *)
417       let _,fresh_metanoouttype,newouttype,_ =
418        NCicMetaSubst.mk_meta metasenv context `IsTerm in
419       let subst =
420        (fresh_metanoouttype,([`Name "outtype"],context,outtype,outsort))
421          ::subst in
422       let outtype = newouttype in
423
424       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
425       let ind =
426         if parameters = [] then C.Const r
427         else C.Appl ((C.Const r)::parameters) in
428       let metasenv, subst, ind, ind_ty = 
429         typeof_aux metasenv subst context None ind in
430       let metasenv, subst = 
431          check_allowed_sort_elimination status localise r orig_term metasenv subst 
432            context ind ind_ty outsort 
433       in
434       (* let's check if the type of branches are right *)
435       if List.length pl <> constructorsno then
436        raise (RefineFailure (lazy (localise orig, 
437          "Wrong number of cases in a match")));
438 (*
439       let metasenv, subst =
440         match expty with
441         | None -> metasenv, subst
442         | Some expty -> 
443            NCicUnification.unify status metasenv subst context resty expty 
444       in
445 *)
446       let _, metasenv, subst, pl =
447         List.fold_right
448           (fun p (j, metasenv, subst, branches) ->
449               let cons = 
450                 let cons = Ref.mk_constructor j r in
451                 if parameters = [] then C.Const cons
452                 else C.Appl (C.Const cons::parameters)
453               in
454               let metasenv, subst, cons, ty_cons = 
455                 typeof_aux metasenv subst context None cons in
456               let ty_branch = 
457                 NCicTypeChecker.type_of_branch status
458                   ~subst context leftno outtype cons ty_cons in
459               pp (lazy ("TYPEOFBRANCH: " ^
460                status#ppterm ~metasenv ~subst ~context p ^ " ::inf:: " ^
461                status#ppterm ~metasenv ~subst ~context ty_branch ));
462               let metasenv, subst, p, _ = 
463                 typeof_aux metasenv subst context (Some ty_branch) p in
464               j-1, metasenv, subst, p :: branches)
465           pl (List.length pl, metasenv, subst, [])
466       in
467       let resty = C.Appl (outtype::arguments@[term]) in
468       let resty = NCicReduction.head_beta_reduce status ~subst resty in
469       metasenv, subst, C.Match (r, outtype, term, pl),resty
470     | C.Match _ -> assert false
471     in
472     pp (lazy (status#ppterm ~metasenv ~subst ~context t ^ " ::inf:: "^
473          status#ppterm ~metasenv ~subst ~context infty ));
474       force_ty true true metasenv subst context orig t infty expty
475     (*D*)in outside true; rc with exc -> outside false; raise exc
476   in
477     typeof_aux metasenv subst context expty term
478
479 and check_type status ~localise metasenv subst context (ty as orig_ty) =
480   let metasenv, subst, ty, sort = 
481     typeof status ~localise metasenv subst context ty None
482   in
483   let metasenv, subst, ty, _ = 
484     force_to_sort status metasenv subst context ty orig_ty localise sort
485   in
486     metasenv, subst, ty
487
488 and try_coercions status 
489   ~localise metasenv subst context t orig_t infty expty exc 
490 =
491   let cs_subst = NCicSubstitution.subst status ~avoid_beta_redexes:true in
492   try 
493    (match expty with
494        `Type expty ->
495          pp (lazy "WWW: trying coercions -- preliminary unification");
496          let metasenv, subst = 
497            NCicUnification.unify status metasenv subst context infty expty
498          in metasenv, subst, t, expty
499      | _ -> raise (Failure "Special case Prod or Sort"))
500   with
501   | exn ->
502   (* we try with a coercion *)
503   let rec first exc = function
504   | [] ->   
505      let expty =
506       match expty with
507          `Type expty -> status#ppterm ~metasenv ~subst ~context expty
508        | `Sort -> "[[sort]]"
509        | `Prod -> "[[prod]]" in
510       pp (lazy "WWW: no more coercions!");      
511       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
512         "The term\n%s\nhas type\n%s\nbut is here used with type\n%s"
513         (status#ppterm ~metasenv ~subst ~context t)
514         (status#ppterm ~metasenv ~subst ~context infty)
515         expty)) exc)
516   | (_,metasenv, newterm, newtype, meta)::tl ->
517       try 
518           pp (lazy("K=" ^ status#ppterm ~metasenv ~subst ~context newterm));
519           pp (lazy ( "UNIFICATION in CTX:\n"^ 
520             status#ppcontext ~metasenv ~subst context
521             ^ "\nMENV: " ^
522             status#ppmetasenv metasenv ~subst
523             ^ "\nOF: " ^
524             status#ppterm ~metasenv ~subst ~context t ^  " === " ^
525             status#ppterm ~metasenv ~subst ~context meta ^ "\n"));
526         let metasenv, subst = 
527           NCicUnification.unify status metasenv subst context t meta in
528         match expty with
529            `Type expty ->
530              pp (lazy ( "UNIFICATION in CTX:\n"^ 
531                status#ppcontext ~metasenv ~subst context
532                ^ "\nMENV: " ^
533                status#ppmetasenv metasenv ~subst
534                ^ "\nOF: " ^
535                status#ppterm ~metasenv ~subst ~context newtype ^  " === " ^
536                status#ppterm ~metasenv ~subst ~context expty ^ "\n"));
537              let metasenv,subst =
538                NCicUnification.unify status metasenv subst context newtype expty
539              in
540               metasenv, subst, newterm, newtype
541          | `Sort ->
542              (match NCicReduction.whd status ~subst context newtype with
543                  NCic.Sort _ -> metasenv,subst,newterm,newtype
544                | _ -> first exc tl)
545          | `Prod ->
546              (match NCicReduction.whd status ~subst context newtype with
547                  NCic.Prod _ -> metasenv,subst,newterm,newtype
548                | _ -> first exc tl)
549       with 
550       | NCicUnification.UnificationFailure _ -> first exc tl
551       | NCicUnification.Uncertain _ as exc -> first exc tl
552   in
553   
554   try 
555     pp (lazy "WWW: trying coercions -- inner check");
556     match infty, expty, t with
557     (* `Sort|`Prod + Match not implemented *) 
558     | _,`Type expty, NCic.Match (Ref.Ref (_,Ref.Ind (_,tyno,leftno)) as r,outty,m,pl) ->
559         (*{{{*) pp (lazy "CASE");
560         (* {{{ helper functions *)
561         let get_cl_and_left_p refit outty =
562           match refit with
563           | NReference.Ref (uri, NReference.Ind (_,tyno,leftno)) ->
564              let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys status r in
565              let _, _, ty, cl = List.nth itl tyno in
566              let constructorsno = List.length cl in
567               let count_pis t =
568                 let rec aux ctx t = 
569                   match NCicReduction.whd status ~subst ~delta:max_int ctx t with
570                   | NCic.Prod (name,src,tgt) ->
571                       let ctx = (name, (NCic.Decl src)) :: ctx in
572                       1 + aux ctx tgt
573                   | _ -> 0
574                 in
575                   aux [] t
576               in
577               let rec skip_lambda_delifting t n =
578                 match t,n with
579                 | _,0 -> t
580                 | NCic.Lambda (_,_,t),n ->
581                     pp (lazy ("WWW: failing term? "^ status#ppterm ~subst:[] ~metasenv:[] ~context:[] t)); 
582                     skip_lambda_delifting
583                       (* substitute dangling indices with a dummy *)
584                       (NCicSubstitution.subst status (NCic.Sort NCic.Prop) t) (n - 1)
585                 | _ -> assert false
586               in
587               let get_l_r_p n = function
588                 | NCic.Lambda (_,NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))),_) -> [],[]
589                 | NCic.Lambda (_,NCic.Appl 
590                     (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) :: args),_) ->
591                     HExtlib.split_nth n args
592                 | _ -> assert false
593               in
594               let pis = count_pis ty in
595               let rno = pis - leftno in
596               let t = skip_lambda_delifting outty rno in
597               let left_p, _ = get_l_r_p leftno t in
598               let instantiate_with_left cl =
599                 List.map 
600                   (fun ty -> 
601                     List.fold_left 
602                       (fun t p -> match t with
603                         | NCic.Prod (_,_,t) ->
604                             cs_subst p t
605                         | _-> assert false)
606                       ty left_p) 
607                   cl 
608               in
609               let cl = instantiate_with_left (List.map (fun (_,_,x) -> x) cl) in
610               cl, left_p, leftno, rno
611           | _ -> raise exn
612         in
613         (*{{{*) pp (lazy "CASE");
614         let rec keep_lambdas_and_put_expty ctx t bo right_p matched n =
615           match t,n with
616           | _,0 ->
617             let rec mkr n = function 
618               | [] -> [] | _::tl -> NCic.Rel n :: mkr (n+1) tl
619             in
620             pp (lazy ("input replace: " ^ status#ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
621             let bo =
622             NCicRefineUtil.replace_lifting status
623               ~equality:(fun _ -> NCicRefineUtil.alpha_equivalence status)
624               ~context:ctx
625               ~what:(matched::right_p)
626               ~with_what:(NCic.Rel 1::List.rev (mkr 2 right_p))
627               ~where:bo
628             in
629             pp (lazy ("output replace: " ^ status#ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
630             bo
631           | NCic.Lambda (name, src, tgt),_ ->
632               NCic.Lambda (name, src,
633                keep_lambdas_and_put_expty 
634                 ((name, NCic.Decl src)::ctx) tgt (NCicSubstitution.lift status 1 bo)
635                 (List.map (NCicSubstitution.lift status 1) right_p) (NCicSubstitution.lift status 1 matched) (n-1))
636           | _ -> assert false
637         in
638         (*let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.ind(1,0,2)")) in
639         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.con(0,1,2)")) in*)
640         let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/basics/jmeq/jmeq.ind(1,0,2)")) in
641         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/basics/jmeq/jmeq.con(0,1,2)")) in
642         let add_params 
643           metasenv subst context cty outty mty m i 
644         =
645           let rec aux context outty par j mty m = function
646             | NCic.Prod (name, src, tgt) ->
647                 let t,k = 
648                   aux 
649                     ((name, NCic.Decl src) :: context)
650                     (NCicSubstitution.lift status 1 outty) (NCic.Rel j::par) (j+1) 
651                     (NCicSubstitution.lift status 1 mty) (NCicSubstitution.lift status 1 m) tgt
652                 in
653                 NCic.Prod (name, src, t), k
654             | NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r) ->
655                 let k = 
656                   let k = NCic.Const(Ref.mk_constructor i r) in
657                   NCicUntrusted.mk_appl k par
658                 in
659                 (* the type has no parameters, so kty = mty
660                 let kty = 
661                   try NCicTypechecker.typeof ~subst ~metasenv context k
662                   with NCicTypeChecker.TypeCheckerFailure _ -> assert false
663                 in *)
664                 NCic.Prod ("p", 
665                  NCic.Appl [eq; mty; m; mty; k],
666                  (NCicSubstitution.lift status 1
667                   (NCicReduction.head_beta_reduce status ~delta:max_int 
668                    (NCicUntrusted.mk_appl outty [k])))),[mty,m,mty,k]
669             | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r)::pl) ->
670                 let left_p,right_p = HExtlib.split_nth leftno pl in
671                 let has_rights = right_p <> [] in
672                 let k = 
673                   let k = NCic.Const(Ref.mk_constructor i r) in
674                   NCicUntrusted.mk_appl k (left_p@par)
675                 in
676                 let right_p = 
677                   try match 
678                     NCicTypeChecker.typeof status ~subst ~metasenv context k
679                   with
680                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
681                       snd (HExtlib.split_nth leftno args)
682                   | _ -> assert false
683                   with NCicTypeChecker.TypeCheckerFailure _-> assert false
684                 in
685                 let orig_right_p =
686                   match mty with
687                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
688                       snd (HExtlib.split_nth leftno args)
689                   | _ -> assert false
690                 in
691                 List.fold_right2 
692                   (fun x y (tacc,pacc) ->
693                     let xty = 
694                     try NCicTypeChecker.typeof status ~subst ~metasenv context x
695                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
696                     in
697                     let yty = 
698                     try NCicTypeChecker.typeof status ~subst ~metasenv context y
699                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
700                     in
701                     NCic.Prod ("_", NCic.Appl [eq;xty;x;yty;y],
702                      NCicSubstitution.lift status 1 tacc), (xty,x,yty,y)::pacc) 
703                   (orig_right_p @ [m]) (right_p @ [k]) 
704                   (NCicReduction.head_beta_reduce status ~delta:max_int
705                       (NCicUntrusted.mk_appl outty (right_p@[k])), [])  
706
707   (*              if has_rights then
708                   NCicReduction.head_beta_reduce status ~delta:max_int
709                     (NCic.Appl (outty ::right_p @ [k])),k
710                 else
711                   NCic.Prod ("p", 
712                    NCic.Appl [eq; mty; m; k],
713                    (NCicSubstitution.lift status 1
714                     (NCicReduction.head_beta_reduce status ~delta:max_int 
715                      (NCic.Appl (outty ::right_p @ [k]))))),k*)
716             | _ -> assert false
717           in
718             aux context outty [] 1 mty m cty
719         in
720         let add_lambda_for_refl_m pbo eqs cty =
721           (* k lives in the right context *)
722           (* if rno <> 0 then pbo else *)
723           let rec aux = function 
724             | NCic.Lambda (name,src,bo), NCic.Prod (_,_,ty) ->
725                 NCic.Lambda (name,src,
726                 (aux (bo,ty)))
727             | t,_ -> snd (List.fold_right
728                 (fun (xty,x,yty,y) (n,acc) -> n+1, NCic.Lambda ("p" ^ string_of_int n,
729                   NCic.Appl [eq; xty; x; yty; y],
730                   NCicSubstitution.lift status 1 acc)) eqs (1,t))
731                 (*NCic.Lambda ("p",
732                   NCic.Appl [eq; mty; m; k],NCicSubstitution.lift status 1 t)*)
733           in
734           aux (pbo,cty)
735         in
736         let add_pi_for_refl_m context new_outty mty m lno rno =
737           (*if rno <> 0 then new_outty else*)
738             let rec aux context mty m = function
739               | NCic.Lambda (name, src, tgt) ->
740                   let context = (name, NCic.Decl src)::context in
741                   NCic.Lambda (name, src, aux context (NCicSubstitution.lift status 1 mty) (NCicSubstitution.lift status 1 m) tgt)
742               | t -> 
743                   let lhs =
744                     match mty with
745                     | NCic.Appl (_::params) -> (snd (HExtlib.split_nth lno params))@[m]
746                     | _ -> [m]
747                   in
748                   let rhs = 
749                     List.map (fun x -> NCic.Rel x) 
750                       (List.rev (HExtlib.list_seq 1 (rno+2))) in
751                   List.fold_right2
752                     (fun x y acc ->
753                       let xty = 
754                     try NCicTypeChecker.typeof status ~subst ~metasenv context x
755                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
756                       in
757                       let yty = 
758                     try NCicTypeChecker.typeof status ~subst ~metasenv context y
759                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
760                       in
761                       NCic.Prod
762                       ("_", NCic.Appl [eq;xty;x;yty;y],
763                        (NCicSubstitution.lift status 1 acc)))
764                     lhs rhs t
765   (*                NCic.Prod 
766                     ("_", NCic.Appl [eq;mty;m;NCic.Rel 1],
767                     NCicSubstitution.lift status 1 t)*)
768             in
769               aux context mty m new_outty
770         in (* }}} end helper functions *)
771         (* constructors types with left params already instantiated *)
772         let outty = NCicUntrusted.apply_subst status subst context outty in
773         let cl, left_p, leftno,rno = 
774           get_cl_and_left_p r outty
775         in
776         let right_p, mty = 
777           try
778             match 
779               NCicTypeChecker.typeof status ~subst ~metasenv context m
780             with
781             | (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) | NCic.Meta _) as mty -> [], mty
782             | NCic.Appl ((NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))|NCic.Meta _)::args) as mty ->
783                 snd (HExtlib.split_nth leftno args), mty
784             | _ -> assert false
785           with NCicTypeChecker.TypeCheckerFailure _ -> 
786              raise (AssertFailure(lazy "already ill-typed matched term"))
787         in
788         let mty = NCicUntrusted.apply_subst status subst context mty in
789         let outty = NCicUntrusted.apply_subst status subst context outty in
790         let expty = NCicUntrusted.apply_subst status subst context expty in
791         let new_outty =
792          keep_lambdas_and_put_expty context outty expty right_p m (rno+1)
793         in
794         pp 
795           (lazy ("CASE: new_outty: " ^ status#ppterm 
796            ~context ~metasenv ~subst new_outty));
797         let _,pl,subst,metasenv = 
798           List.fold_right2
799             (fun cty pbo (i, acc, s, menv) -> 
800                pp (lazy ("begin iteration"));
801               (* Pi k_par, (Pi H:m=(K_i left_par k_par)), 
802                *   (new_)outty right_par (K_i left_par k_par) *)
803                let infty_pbo, _ = 
804                  add_params menv s context cty outty mty m i in
805                pp 
806                 (lazy ("CASE: infty_pbo: "^ status#ppterm
807                  ~context ~metasenv ~subst infty_pbo));
808                let expty_pbo, eqs = (* k is (K_i left_par k_par) *)
809                  add_params menv s context cty new_outty mty m i in
810                pp 
811                 (lazy ("CASE: expty_pbo: "^ status#ppterm
812                  ~context ~metasenv ~subst expty_pbo));
813                let pbo = add_lambda_for_refl_m pbo eqs cty in
814                pp 
815                  (lazy ("CASE: pbo: " ^ status#ppterm
816                  ~context ~metasenv ~subst pbo));
817                let metasenv, subst, pbo, _ =
818                  try_coercions status ~localise menv s context pbo 
819                  orig_t (*??*) infty_pbo (`Type expty_pbo) exc
820                in
821                pp 
822                  (lazy ("CASE: pbo2: " ^ status#ppterm 
823                  ~context ~metasenv ~subst pbo));
824                (i-1, pbo::acc, subst, metasenv))
825             cl pl (List.length pl, [], subst, metasenv)
826         in
827         (*let metasenv, subst = 
828           try 
829             NCicUnification.unify status metasenv subst context outty new_outty 
830           with _ -> raise (RefineFailure (lazy (localise orig_t, "try_coercions")))
831         in*)
832         let new_outty = add_pi_for_refl_m context new_outty mty m leftno rno in
833         pp (lazy ("CASE: new_outty: " ^ (status#ppterm 
834            ~metasenv ~subst ~context new_outty)));
835         let right_tys = 
836           List.map 
837             (fun t -> NCicTypeChecker.typeof status ~subst ~metasenv context t) right_p in
838         let eqs = 
839           List.map2 (fun x y -> NCic.Appl[eq_refl;x;y]) (right_tys@[mty]) 
840             (right_p@[m]) in
841         let t = NCic.Appl (NCic.Match(r,new_outty,m,pl) :: eqs) 
842         in
843         metasenv, subst, t, expty (*}}}*)
844     | _,`Type expty,NCic.LetIn(name,ty,t,bo) -> 
845         pp (lazy "LETIN");
846         let name' = mk_fresh_name context name in
847         let context_bo = (name', NCic.Def (t,ty)) :: context in
848         let metasenv, subst, bo2, _ = 
849           try_coercions status ~localise metasenv subst context_bo
850            bo orig_t (NCicSubstitution.lift status 1 infty)
851            (`Type (NCicSubstitution.lift status 1 expty)) exc
852         in
853         let coerced = NCic.LetIn (name',ty,t,bo2) in
854         pp (lazy ("LETIN: coerced = " ^ status#ppterm ~metasenv ~subst ~context coerced));
855         metasenv, subst, coerced, expty
856     | NCic.Prod (nameprod, src, ty),`Type (NCic.Prod (_, src2, ty2) as expty), _ -> 
857         (*{{{*) pp (lazy "LAM");
858         pp (lazy ("LAM: t = " ^ status#ppterm ~metasenv ~subst ~context t));
859         let namename = match t with NCic.Lambda (n,_,_) -> n | _ -> nameprod in
860         let name_con = mk_fresh_name context namename in
861         let context_src2 = ((name_con, NCic.Decl src2) :: context) in
862         (* contravariant part: the argument of f:src->ty *)
863         let metasenv, subst, rel1, _ = 
864           try_coercions status ~localise metasenv subst context_src2
865            (NCic.Rel 1) orig_t (NCicSubstitution.lift status 1 src2) 
866            (`Type (NCicSubstitution.lift status 1 src)) exc
867         in
868         (* covariant part: the result of f(c x); x:src2; (c x):src *)
869         let name_t, bo = 
870           match t with
871           | NCic.Lambda (n,_,bo) -> n, cs_subst rel1 (NCicSubstitution.lift_from status 2 1 bo)
872           | _ -> name_con, NCicUntrusted.mk_appl (NCicSubstitution.lift status 1 t) [rel1]
873         in
874         (* we fix the possible dependency problem in the source ty *)
875         let ty = cs_subst rel1 (NCicSubstitution.lift_from status 2 1 ty) in
876         let metasenv, subst, bo, _ = 
877           try_coercions status ~localise metasenv subst context_src2
878             bo orig_t ty (`Type ty2) exc
879         in
880         let coerced = NCic.Lambda (name_t,src2, bo) in
881         pp (lazy ("LAM: coerced = " ^ status#ppterm ~metasenv ~subst ~context coerced));
882         metasenv, subst, coerced, expty (*}}}*)
883     | _ -> raise exc
884   with exc2 ->    
885   let expty =
886    match expty with
887       `Type expty -> expty
888     | `Sort ->
889         NCic.Sort (NCic.Type 
890          (match NCicEnvironment.get_universes () with
891            | x::_ -> x 
892            | _ -> assert false))
893     | `Prod -> NCic.Prod ("_",NCic.Implicit `Type,NCic.Implicit `Type)
894   in
895   pp(lazy("try_coercion " ^ 
896     status#ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
897     status#ppterm ~metasenv ~subst ~context expty));
898     first exc
899       (NCicCoercion.look_for_coercion 
900         status metasenv subst context infty expty)
901
902 and force_to_sort status metasenv subst context t orig_t localise ty =
903   try 
904     let metasenv, subst, ty = 
905       NCicUnification.sortfy status (Failure "sortfy") metasenv subst context ty in
906       metasenv, subst, t, ty
907   with
908       Failure _ -> 
909         let ty = NCicReduction.whd status ~subst context ty in
910           try_coercions status ~localise metasenv subst context
911             t orig_t ty `Sort 
912              (Uncertain (lazy (localise orig_t, 
913              "The type of " ^ status#ppterm ~metasenv ~subst ~context t ^
914              " is not a sort: " ^ status#ppterm ~metasenv ~subst ~context ty)))
915
916 and sort_of_prod status localise metasenv subst context orig_s orig_t (name,s)
917  t (t1, t2) 
918 =
919    (* force to sort is done in the Prod case in typeof *)
920    match t1, t2 with
921    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
922    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
923         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
924    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
925    | C.Meta _, C.Sort _ 
926    | C.Meta _, C.Meta (_,(_,_))
927    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
928    | x, (C.Sort _ | C.Meta _) | _, x -> 
929       let y, context, orig = 
930         if x == t1 then s, context, orig_s 
931         else t, ((name,C.Decl s)::context), orig_t
932       in
933       raise (RefineFailure (lazy (localise orig,Printf.sprintf
934         "%s is expected to be a type, but its type is %s that is not a sort" 
935          (status#ppterm ~subst ~metasenv ~context y) 
936          (status#ppterm ~subst ~metasenv ~context x))))
937
938 and guess_name status subst ctx ty = 
939   let aux initial = "#" ^ String.make 1 initial in
940   match ty with
941   | C.Const (NReference.Ref (u,_))
942   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
943       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
944   | C.Prod _ -> aux 'f' 
945   | C.Meta (n,lc) -> 
946       (try
947          let _,_,t,_ = NCicUtils.lookup_subst n subst in
948          guess_name status subst ctx (NCicSubstitution.subst_meta status lc t)
949       with NCicUtils.Subst_not_found _ -> aux 'M')
950   | _ -> aux 'H' 
951
952 and eat_prods status ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
953   (*D*)inside 'E'; try let rc = 
954   let rec aux metasenv subst args_so_far he ty_he xxx =
955   (*D*)inside 'V'; try let rc = 
956    match xxx with
957   | [] ->
958      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
959      pp(lazy("FORCE FINAL APPL: " ^ 
960        status#ppterm ~metasenv ~subst ~context res ^
961        " of type " ^ status#ppterm ~metasenv ~subst ~context ty_he
962        ^ " to type " ^ match expty with None -> "None" | Some x -> 
963        status#ppterm ~metasenv ~subst ~context x));
964      (* whatever the term is, we force the type. in case of ((Lambda..) ?...)
965       * the application may also be a lambda! *)
966      force_ty false false metasenv subst context orig_t res ty_he expty
967   | NCic.Implicit `Vector::tl ->
968       let has_some_more_pis x =
969         match NCicReduction.whd status ~subst context x with
970         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
971         | _ -> true
972       in
973      (try
974        aux metasenv subst args_so_far he ty_he tl
975       with
976       | Uncertain _
977       | RefineFailure _ as exc when has_some_more_pis ty_he ->
978           (try
979            aux metasenv subst args_so_far he ty_he
980             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
981           with
982            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc))
983      | RefineFailure msg when not (has_some_more_pis ty_he) ->
984         (* instantiating the head could change the has_some_more_pis flag *)
985         raise (Uncertain msg))
986   | arg::tl ->
987       match NCicReduction.whd status ~subst context ty_he with 
988       | C.Prod (_,s,t) ->
989           let metasenv, subst, arg, _ = 
990             typeof status ~localise metasenv subst context arg (Some s) in
991           let t = NCicSubstitution.subst status ~avoid_beta_redexes:true arg t in
992           aux metasenv subst (arg :: args_so_far) he t tl
993       | C.Meta _
994       | C.Appl (C.Meta _ :: _) as t ->
995           let metasenv, subst, arg, ty_arg = 
996             typeof status ~localise metasenv subst context arg None in
997           let name = guess_name status subst context ty_arg in
998           let metasenv, _, meta, _ = 
999             NCicMetaSubst.mk_meta metasenv 
1000               ((name,C.Decl ty_arg) :: context) `IsType
1001           in
1002           let flex_prod = C.Prod (name, ty_arg, meta) in
1003           (* next line grants that ty_args is a type *)
1004           let metasenv,subst, flex_prod, _ =
1005            typeof status ~localise metasenv subst context flex_prod None in
1006 (*
1007           pp (lazy ( "UNIFICATION in CTX:\n"^ 
1008             status#ppcontext ~metasenv ~subst context
1009             ^ "\nOF: " ^
1010             status#ppterm ~metasenv ~subst ~context t ^  " === " ^
1011             status#ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
1012 *)
1013           let metasenv, subst =
1014              try NCicUnification.unify status metasenv subst context t flex_prod 
1015              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
1016               ("The term %s has an inferred type %s, but is applied to the" ^^
1017                " argument %s of type %s")
1018               (status#ppterm ~metasenv ~subst ~context he)
1019               (status#ppterm ~metasenv ~subst ~context t)
1020               (status#ppterm ~metasenv ~subst ~context arg)
1021               (status#ppterm ~metasenv ~subst ~context ty_arg))) 
1022                  (match exc with
1023                  | NCicUnification.UnificationFailure m -> 
1024                      NCicUnification.Uncertain m
1025                  | x -> x))
1026               (* XXX coerce to funclass *)
1027           in
1028           let meta = NCicSubstitution.subst status ~avoid_beta_redexes:true arg meta in
1029           aux metasenv subst (arg :: args_so_far) he meta tl
1030       | C.Match (_,_,C.Meta _,_) 
1031       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
1032       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
1033           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
1034             ("The term %s is here applied to %d arguments but expects " ^^
1035             "only %d arguments") (status#ppterm ~metasenv ~subst ~context he)
1036             (List.length args) (List.length args_so_far))))
1037       | ty ->
1038           let metasenv, subst, newhead, newheadty = 
1039             try_coercions status ~localise metasenv subst context
1040               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
1041               `Prod
1042               (RefineFailure (lazy (localise orig_he, Printf.sprintf
1043                ("The term %s is here applied to %d arguments but expects " ^^
1044                "only %d arguments") (status#ppterm ~metasenv ~subst ~context he)
1045                (List.length args) (List.length args_so_far))))
1046           in
1047            aux metasenv subst [] newhead newheadty (arg :: tl)
1048   (*D*)in outside true; rc with exc -> outside false; raise exc
1049   in
1050    (* We need to reverse the order of the new created metas since they
1051       are pushed on top of the metasenv in the wrong order *)
1052    let highest_meta = NCicMetaSubst.maxmeta () in
1053    let metasenv, subst, newhead, newheadty = 
1054     aux metasenv subst [] he ty_he args in
1055    let metasenv_old,metasenv_new =
1056     List.partition (fun (i,_) -> i <= highest_meta) metasenv
1057    in
1058     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
1059   (*D*)in outside true; rc with exc -> outside false; raise exc
1060 ;;
1061
1062 let rec first f l1 l2 =
1063   match l1,l2 with
1064   | x1::tl1, x2::tl2 -> 
1065       (try f x1 x2 with Not_found -> first f tl1 tl2)
1066   | _ -> raise Not_found
1067 ;;
1068
1069 let rec find add dt t =
1070   if dt == add then t
1071   else
1072     let dl, l = 
1073       match dt, t with
1074       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
1075       | C.Appl dl,C.Appl l -> dl,l
1076       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
1077       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
1078       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
1079       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
1080       | _ -> raise Not_found
1081     in
1082       first (find add) dl l
1083 ;;
1084
1085 let relocalise old_localise dt t add = 
1086   old_localise 
1087     (try find add dt t with Not_found -> assert false)
1088 ;;
1089
1090 let undebruijnate status inductive ref t rev_fl =
1091   let len = List.length rev_fl in 
1092   NCicSubstitution.psubst status (fun x -> x) 
1093    (HExtlib.list_mapi 
1094       (fun (_,_,rno,_,_,_) i -> 
1095          let i = len - i - 1 in
1096          NCic.Const 
1097            (if inductive then NReference.mk_fix i rno ref
1098             else NReference.mk_cofix i ref))
1099       rev_fl)
1100     t
1101 ;; 
1102
1103
1104 let typeof_obj 
1105   status ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
1106
1107   match obj with 
1108   | C.Constant (relevance, name, bo, ty, attr) ->
1109        let metasenv, subst, ty = 
1110          check_type status ~localise metasenv subst [] ty in
1111        let metasenv, subst, bo, ty, height = 
1112          match bo with
1113          | Some bo ->
1114              let metasenv, subst, bo, ty = 
1115                typeof status ~localise metasenv subst [] bo (Some ty) in
1116              let height = (* XXX recalculate *) height in
1117                metasenv, subst, Some bo, ty, height
1118          | None -> metasenv, subst, None, ty, 0
1119        in
1120        uri, height, metasenv, subst, 
1121          C.Constant (relevance, name, bo, ty, attr)
1122   | C.Fixpoint (inductive, fl, attr) -> 
1123       let len = List.length fl in
1124       let types, metasenv, subst, rev_fl =
1125         List.fold_left
1126          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
1127            let metasenv, subst, ty = 
1128              check_type status ~localise metasenv subst [] ty in
1129            let dbo = NCicTypeChecker.debruijn status uri len [] ~subst bo in
1130            let localise = relocalise localise dbo bo in
1131             (name,C.Decl ty)::types,
1132               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
1133          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
1134       in
1135       let metasenv, subst, fl = 
1136         List.fold_left 
1137           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
1138             let metasenv, subst, dbo, ty = 
1139               typeof status ~localise metasenv subst types dbo (Some ty)
1140             in
1141             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
1142           (metasenv, subst, []) rev_fl
1143       in
1144       let height = (* XXX recalculate *) height in
1145       let fl =
1146         List.map 
1147           (fun (relevance,name,k,ty,dbo) ->
1148             let bo = 
1149               undebruijnate status inductive 
1150                (NReference.reference_of_spec uri 
1151                  (if inductive then NReference.Fix (0,k,0) 
1152                   else NReference.CoFix 0)) dbo rev_fl
1153             in
1154               relevance,name,k,ty,bo)
1155           fl
1156       in
1157        uri, height, metasenv, subst, 
1158          C.Fixpoint (inductive, fl, attr)
1159   | C.Inductive (ind, leftno, itl, attr) ->
1160      let len = List.length itl in
1161      let metasenv,subst,rev_itl,tys =
1162       List.fold_left
1163        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
1164           let metasenv, subst, ty = 
1165             check_type status ~localise metasenv subst [] ty in
1166           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
1167        ) (metasenv,subst,[],[]) itl in
1168      let metasenv,subst,itl,_ =
1169       List.fold_left
1170        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
1171          let context,ty_sort = NCicReduction.split_prods status ~subst [] ~-1 ty in
1172          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
1173          let metasenv,subst,cl =
1174           List.fold_right
1175            (fun (k_relev,n,te) (metasenv,subst,res) ->
1176              let k_relev =
1177               try snd (HExtlib.split_nth leftno k_relev)
1178               with Failure _ -> k_relev in
1179              let te = NCicTypeChecker.debruijn status uri len [] ~subst te in
1180              let metasenv, subst, te = 
1181                check_type status ~localise metasenv subst tys te in
1182              let context,te = NCicReduction.split_prods status ~subst tys leftno te in
1183              let _,chopped_context_rev =
1184               HExtlib.split_nth (List.length tys) (List.rev context) in
1185              let sx_context_te_rev,_ =
1186               HExtlib.split_nth leftno chopped_context_rev in
1187              let metasenv,subst,_ =
1188               try
1189                List.fold_left2
1190                 (fun (metasenv,subst,context) item1 item2 ->
1191                   let (metasenv,subst),convertible =
1192                    try
1193                     match item1,item2 with
1194                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
1195                         if n1 = n2 then
1196                          NCicUnification.unify status ~test_eq_only:true metasenv
1197                           subst context ty1 ty2,true
1198                         else
1199                          (metasenv,subst),false
1200                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
1201                         if n1 = n2 then
1202                          let metasenv,subst =
1203                           NCicUnification.unify status ~test_eq_only:true metasenv
1204                            subst context ty1 ty2
1205                          in
1206                           NCicUnification.unify status ~test_eq_only:true metasenv
1207                            subst context bo1 bo2,true
1208                         else
1209                          (metasenv,subst),false
1210                     | _,_ -> (metasenv,subst),false
1211                    with
1212                    | NCicUnification.Uncertain _
1213                    | NCicUnification.UnificationFailure _ ->
1214                       (metasenv,subst),false
1215                   in
1216                    let term2 =
1217                     match item2 with
1218                        _,C.Decl t -> t
1219                      | _,C.Def (b,_) -> b in
1220                    if not convertible then
1221                     raise (RefineFailure (lazy (localise term2,
1222                      ("Mismatch between the left parameters of the constructor " ^
1223                       "and those of its inductive type"))))
1224                    else
1225                     metasenv,subst,item1::context
1226                 ) (metasenv,subst,tys) sx_context_ty_rev sx_context_te_rev
1227               with Invalid_argument "List.fold_left2" -> assert false in
1228              let metasenv, subst =
1229                 let rec aux context (metasenv,subst) = function
1230                   | NCic.Meta _ -> metasenv, subst
1231                   | NCic.Implicit _ -> metasenv, subst
1232                   | NCic.Appl (NCic.Rel i :: args) as t
1233                       when i > List.length context - len ->
1234                       let lefts, _ = HExtlib.split_nth leftno args in
1235                       let ctxlen = List.length context in
1236                       let (metasenv, subst), _ = 
1237                         List.fold_left
1238                         (fun ((metasenv, subst),l) arg ->
1239                           NCicUnification.unify status 
1240                            ~test_eq_only:true metasenv subst context arg 
1241                              (NCic.Rel (ctxlen - len - l)), l+1
1242                           )
1243                         ((metasenv, subst), 0) lefts
1244                       in
1245                       metasenv, subst
1246                   | t -> NCicUtils.fold (fun e c -> e::c) context aux
1247                   (metasenv,subst) t
1248                 in
1249                aux context (metasenv,subst) te
1250              in
1251              let con_sort= NCicTypeChecker.typeof status ~subst ~metasenv context te in
1252               (match
1253                 NCicReduction.whd status ~subst context con_sort,
1254                 NCicReduction.whd status ~subst [] ty_sort
1255                with
1256                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
1257                    if not (NCicEnvironment.universe_leq u1 u2) then
1258                     raise
1259                      (RefineFailure
1260                        (lazy(localise te, "The type " ^
1261                          status#ppterm ~metasenv ~subst ~context s1 ^
1262                          " of the constructor is not included in the inductive"^
1263                          " type sort " ^
1264                          status#ppterm ~metasenv ~subst ~context s2)))
1265                 | C.Sort _, C.Sort C.Prop
1266                 | C.Sort _, C.Sort C.Type _ -> ()
1267                 | _, _ ->
1268                    raise
1269                     (RefineFailure
1270                       (lazy (localise te,
1271                         "Wrong constructor or inductive arity shape"))));
1272               (* let's check also the positivity conditions *)
1273               if 
1274                not
1275                (NCicTypeChecker.are_all_occurrences_positive status
1276                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
1277               then
1278                 raise
1279                   (RefineFailure
1280                     (lazy (localise te,
1281                       "Non positive occurence in " ^
1282                         status#ppterm ~metasenv ~subst ~context te)))
1283               else
1284                let relsno = List.length itl + leftno in
1285                let te = 
1286                  NCicSubstitution.psubst status
1287                   (fun i ->
1288                     if i <= leftno  then
1289                      NCic.Rel i
1290                     else
1291                      NCic.Const (NReference.reference_of_spec uri
1292                       (NReference.Ind (ind,relsno - i,leftno))))
1293                   (HExtlib.list_seq 1 (relsno+1))
1294                    te in
1295                let te =
1296                 List.fold_right
1297                  (fun (name,decl) te ->
1298                    match decl with
1299                       NCic.Decl ty -> NCic.Prod (name,ty,te)
1300                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
1301                  ) sx_context_te_rev te
1302                in
1303                 metasenv,subst,(k_relev,n,te)::res
1304               ) cl (metasenv,subst,[])
1305          in
1306           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
1307        ) (metasenv,subst,[],1) rev_itl
1308      in
1309       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
1310 ;;
1311
1312 (* vim:set foldmethod=marker: *)