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