]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_refiner/nCicRefiner.ml
7cdeb875e19d585baad9e65c3df1482f5cae410d
[helm.git] / matitaB / 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 status 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 
493   metasenv subst context t orig_t infty expty exc 
494 =
495   let cs_subst = NCicSubstitution.subst status ~avoid_beta_redexes:true in
496   try 
497    (match expty with
498        `Type expty ->
499          pp (lazy "WWW: trying coercions -- preliminary unification");
500          let metasenv, subst = 
501            NCicUnification.unify status metasenv subst context infty expty
502          in metasenv, subst, t, expty
503      | _ -> raise (Failure "Special case Prod or Sort"))
504   with
505   | exn ->
506   (* we try with a coercion *)
507   let rec first exc = function
508   | [] ->   
509       pp (lazy "WWW: no more coercions!");      
510       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
511         "The term\n%s\nhas type\n%s\nbut is here used with type\n%s"
512         (status#ppterm ~metasenv ~subst ~context t)
513         (status#ppterm ~metasenv ~subst ~context infty)
514         expty)) exc)
515   | (_,metasenv, newterm, newtype, meta)::tl ->
516       try 
517           pp (lazy("K=" ^ status#ppterm ~metasenv ~subst ~context newterm));
518           pp (lazy ( "UNIFICATION in CTX:\n"^ 
519             status#ppcontext ~metasenv ~subst context
520             ^ "\nMENV: " ^
521             status#ppmetasenv metasenv ~subst
522             ^ "\nOF: " ^
523             status#ppterm ~metasenv ~subst ~context t ^  " === " ^
524             status#ppterm ~metasenv ~subst ~context meta ^ "\n"));
525         let metasenv, subst = 
526           NCicUnification.unify status metasenv subst context t meta in
527         match expty with
528            `Type expty ->
529              pp (lazy ( "UNIFICATION in CTX:\n"^ 
530                status#ppcontext ~metasenv ~subst context
531                ^ "\nMENV: " ^
532                status#ppmetasenv metasenv ~subst
533                ^ "\nOF: " ^
534                status#ppterm ~metasenv ~subst ~context newtype ^  " === " ^
535                status#ppterm ~metasenv ~subst ~context expty ^ "\n"));
536              let metasenv,subst =
537                NCicUnification.unify status metasenv subst context newtype expty
538              in
539               metasenv, subst, newterm, newtype
540          | `Sort ->
541              (match NCicReduction.whd status ~subst context newtype with
542                  NCic.Sort _ -> metasenv,subst,newterm,newtype
543                | _ -> first exc tl)
544          | `Prod ->
545              (match NCicReduction.whd status ~subst context newtype with
546                  NCic.Prod _ -> metasenv,subst,newterm,newtype
547                | _ -> first exc tl)
548       with 
549       | NCicUnification.UnificationFailure _ -> first exc tl
550       | NCicUnification.Uncertain _ as exc -> first exc tl
551   in
552   
553   try 
554     pp (lazy "WWW: trying coercions -- inner check");
555     match infty, expty, t with
556     (* `Sort|`Prod + Match not implemented *) 
557     | _,`Type expty, NCic.Match (Ref.Ref (_,Ref.Ind (_,tyno,leftno)) as r,outty,m,pl) ->
558         (*{{{*) pp (lazy "CASE");
559         (* {{{ helper functions *)
560         let get_cl_and_left_p refit outty =
561           match refit with
562           | NReference.Ref (uri, NReference.Ind (_,tyno,leftno)) ->
563              let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys status r in
564              let _, _, ty, cl = List.nth itl tyno in
565              let constructorsno = List.length cl in
566               let count_pis t =
567                 let rec aux ctx t = 
568                   match NCicReduction.whd status ~subst ~delta:max_int ctx t with
569                   | NCic.Prod (name,src,tgt) ->
570                       let ctx = (name, (NCic.Decl src)) :: ctx in
571                       1 + aux ctx tgt
572                   | _ -> 0
573                 in
574                   aux [] t
575               in
576               let rec skip_lambda_delifting t n =
577                 match t,n with
578                 | _,0 -> t
579                 | NCic.Lambda (_,_,t),n ->
580                     pp (lazy ("WWW: failing term? "^ status#ppterm ~subst:[] ~metasenv:[] ~context:[] t)); 
581                     skip_lambda_delifting
582                       (* substitute dangling indices with a dummy *)
583                       (NCicSubstitution.subst status (NCic.Sort NCic.Prop) t) (n - 1)
584                 | _ -> assert false
585               in
586               let get_l_r_p n = function
587                 | NCic.Lambda (_,NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))),_) -> [],[]
588                 | NCic.Lambda (_,NCic.Appl 
589                     (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) :: args),_) ->
590                     HExtlib.split_nth n args
591                 | _ -> assert false
592               in
593               let pis = count_pis ty in
594               let rno = pis - leftno in
595               let t = skip_lambda_delifting outty rno in
596               let left_p, _ = get_l_r_p leftno t in
597               let instantiate_with_left cl =
598                 List.map 
599                   (fun ty -> 
600                     List.fold_left 
601                       (fun t p -> match t with
602                         | NCic.Prod (_,_,t) ->
603                             cs_subst p t
604                         | _-> assert false)
605                       ty left_p) 
606                   cl 
607               in
608               let cl = instantiate_with_left (List.map (fun (_,_,x) -> x) cl) in
609               cl, left_p, leftno, rno
610           | _ -> raise exn
611         in
612         (*{{{*) pp (lazy "CASE");
613         let rec keep_lambdas_and_put_expty ctx t bo right_p matched n =
614           match t,n with
615           | _,0 ->
616             let rec mkr n = function 
617               | [] -> [] | _::tl -> NCic.Rel n :: mkr (n+1) tl
618             in
619             pp (lazy ("input replace: " ^ status#ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
620             let bo =
621             NCicRefineUtil.replace_lifting status
622               ~equality:(fun _ -> NCicRefineUtil.alpha_equivalence status)
623               ~context:ctx
624               ~what:(matched::right_p)
625               ~with_what:(NCic.Rel 1::List.rev (mkr 2 right_p))
626               ~where:bo
627             in
628             pp (lazy ("output replace: " ^ status#ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
629             bo
630           | NCic.Lambda (name, src, tgt),_ ->
631               NCic.Lambda (name, src,
632                keep_lambdas_and_put_expty 
633                 ((name, NCic.Decl src)::ctx) tgt (NCicSubstitution.lift status 1 bo)
634                 (List.map (NCicSubstitution.lift status 1) right_p) (NCicSubstitution.lift status 1 matched) (n-1))
635           | _ -> assert false
636         in
637         (*let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.ind(1,0,2)")) in
638         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.con(0,1,2)")) in*)
639         let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/basics/jmeq/jmeq.ind(1,0,2)")) in
640         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/basics/jmeq/jmeq.con(0,1,2)")) in
641         let add_params 
642           metasenv subst context cty outty mty m i 
643         =
644           let rec aux context outty par j mty m = function
645             | NCic.Prod (name, src, tgt) ->
646                 let t,k = 
647                   aux 
648                     ((name, NCic.Decl src) :: context)
649                     (NCicSubstitution.lift status 1 outty) (NCic.Rel j::par) (j+1) 
650                     (NCicSubstitution.lift status 1 mty) (NCicSubstitution.lift status 1 m) tgt
651                 in
652                 NCic.Prod (name, src, t), k
653             | NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r) ->
654                 let k = 
655                   let k = NCic.Const(Ref.mk_constructor i r) in
656                   NCicUntrusted.mk_appl k par
657                 in
658                 (* the type has no parameters, so kty = mty
659                 let kty = 
660                   try NCicTypechecker.typeof ~subst ~metasenv context k
661                   with NCicTypeChecker.TypeCheckerFailure _ -> assert false
662                 in *)
663                 NCic.Prod ("p", 
664                  NCic.Appl [eq; mty; m; mty; k],
665                  (NCicSubstitution.lift status 1
666                   (NCicReduction.head_beta_reduce status ~delta:max_int 
667                    (NCicUntrusted.mk_appl outty [k])))),[mty,m,mty,k]
668             | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r)::pl) ->
669                 let left_p,right_p = HExtlib.split_nth leftno pl in
670                 let has_rights = right_p <> [] in
671                 let k = 
672                   let k = NCic.Const(Ref.mk_constructor i r) in
673                   NCicUntrusted.mk_appl k (left_p@par)
674                 in
675                 let right_p = 
676                   try match 
677                     NCicTypeChecker.typeof status ~subst ~metasenv context k
678                   with
679                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
680                       snd (HExtlib.split_nth leftno args)
681                   | _ -> assert false
682                   with NCicTypeChecker.TypeCheckerFailure _-> assert false
683                 in
684                 let orig_right_p =
685                   match mty with
686                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
687                       snd (HExtlib.split_nth leftno args)
688                   | _ -> assert false
689                 in
690                 List.fold_right2 
691                   (fun x y (tacc,pacc) ->
692                     let xty = 
693                     try NCicTypeChecker.typeof status ~subst ~metasenv context x
694                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
695                     in
696                     let yty = 
697                     try NCicTypeChecker.typeof status ~subst ~metasenv context y
698                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
699                     in
700                     NCic.Prod ("_", NCic.Appl [eq;xty;x;yty;y],
701                      NCicSubstitution.lift status 1 tacc), (xty,x,yty,y)::pacc) 
702                   (orig_right_p @ [m]) (right_p @ [k]) 
703                   (NCicReduction.head_beta_reduce status ~delta:max_int
704                       (NCicUntrusted.mk_appl outty (right_p@[k])), [])  
705
706   (*              if has_rights then
707                   NCicReduction.head_beta_reduce status ~delta:max_int
708                     (NCic.Appl (outty ::right_p @ [k])),k
709                 else
710                   NCic.Prod ("p", 
711                    NCic.Appl [eq; mty; m; k],
712                    (NCicSubstitution.lift status 1
713                     (NCicReduction.head_beta_reduce status ~delta:max_int 
714                      (NCic.Appl (outty ::right_p @ [k]))))),k*)
715             | _ -> assert false
716           in
717             aux context outty [] 1 mty m cty
718         in
719         let add_lambda_for_refl_m pbo eqs cty =
720           (* k lives in the right context *)
721           (* if rno <> 0 then pbo else *)
722           let rec aux = function 
723             | NCic.Lambda (name,src,bo), NCic.Prod (_,_,ty) ->
724                 NCic.Lambda (name,src,
725                 (aux (bo,ty)))
726             | t,_ -> snd (List.fold_right
727                 (fun (xty,x,yty,y) (n,acc) -> n+1, NCic.Lambda ("p" ^ string_of_int n,
728                   NCic.Appl [eq; xty; x; yty; y],
729                   NCicSubstitution.lift status 1 acc)) eqs (1,t))
730                 (*NCic.Lambda ("p",
731                   NCic.Appl [eq; mty; m; k],NCicSubstitution.lift status 1 t)*)
732           in
733           aux (pbo,cty)
734         in
735         let add_pi_for_refl_m context new_outty mty m lno rno =
736           (*if rno <> 0 then new_outty else*)
737             let rec aux context mty m = function
738               | NCic.Lambda (name, src, tgt) ->
739                   let context = (name, NCic.Decl src)::context in
740                   NCic.Lambda (name, src, aux context (NCicSubstitution.lift status 1 mty) (NCicSubstitution.lift status 1 m) tgt)
741               | t -> 
742                   let lhs =
743                     match mty with
744                     | NCic.Appl (_::params) -> (snd (HExtlib.split_nth lno params))@[m]
745                     | _ -> [m]
746                   in
747                   let rhs = 
748                     List.map (fun x -> NCic.Rel x) 
749                       (List.rev (HExtlib.list_seq 1 (rno+2))) in
750                   List.fold_right2
751                     (fun x y acc ->
752                       let xty = 
753                     try NCicTypeChecker.typeof status ~subst ~metasenv context x
754                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
755                       in
756                       let yty = 
757                     try NCicTypeChecker.typeof status ~subst ~metasenv context y
758                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
759                       in
760                       NCic.Prod
761                       ("_", NCic.Appl [eq;xty;x;yty;y],
762                        (NCicSubstitution.lift status 1 acc)))
763                     lhs rhs t
764   (*                NCic.Prod 
765                     ("_", NCic.Appl [eq;mty;m;NCic.Rel 1],
766                     NCicSubstitution.lift status 1 t)*)
767             in
768               aux context mty m new_outty
769         in (* }}} end helper functions *)
770         (* constructors types with left params already instantiated *)
771         let outty = NCicUntrusted.apply_subst status subst context outty in
772         let cl, left_p, leftno,rno = 
773           get_cl_and_left_p r outty
774         in
775         let right_p, mty = 
776           try
777             match 
778               NCicTypeChecker.typeof status ~subst ~metasenv context m
779             with
780             | (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) | NCic.Meta _) as mty -> [], mty
781             | NCic.Appl ((NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))|NCic.Meta _)::args) as mty ->
782                 snd (HExtlib.split_nth leftno args), mty
783             | _ -> assert false
784           with NCicTypeChecker.TypeCheckerFailure _ -> 
785              raise (AssertFailure(lazy "already ill-typed matched term"))
786         in
787         let mty = NCicUntrusted.apply_subst status subst context mty in
788         let outty = NCicUntrusted.apply_subst status subst context outty in
789         let expty = NCicUntrusted.apply_subst status subst context expty in
790         let new_outty =
791          keep_lambdas_and_put_expty context outty expty right_p m (rno+1)
792         in
793         pp 
794           (lazy ("CASE: new_outty: " ^ status#ppterm 
795            ~context ~metasenv ~subst new_outty));
796         let _,pl,subst,metasenv = 
797           List.fold_right2
798             (fun cty pbo (i, acc, s, menv) -> 
799                pp (lazy ("begin iteration"));
800               (* Pi k_par, (Pi H:m=(K_i left_par k_par)), 
801                *   (new_)outty right_par (K_i left_par k_par) *)
802                let infty_pbo, _ = 
803                  add_params menv s context cty outty mty m i in
804                pp 
805                 (lazy ("CASE: infty_pbo: "^ status#ppterm
806                  ~context ~metasenv ~subst infty_pbo));
807                let expty_pbo, eqs = (* k is (K_i left_par k_par) *)
808                  add_params menv s context cty new_outty mty m i in
809                pp 
810                 (lazy ("CASE: expty_pbo: "^ status#ppterm
811                  ~context ~metasenv ~subst expty_pbo));
812                let pbo = add_lambda_for_refl_m pbo eqs cty in
813                pp 
814                  (lazy ("CASE: pbo: " ^ status#ppterm
815                  ~context ~metasenv ~subst pbo));
816                let metasenv, subst, pbo, _ =
817                  try_coercions status ~localise menv s context pbo 
818                  orig_t (*??*) infty_pbo (`Type expty_pbo) exc
819                in
820                pp 
821                  (lazy ("CASE: pbo2: " ^ status#ppterm 
822                  ~context ~metasenv ~subst pbo));
823                (i-1, pbo::acc, subst, metasenv))
824             cl pl (List.length pl, [], subst, metasenv)
825         in
826         (*let metasenv, subst = 
827           try 
828             NCicUnification.unify status metasenv subst context outty new_outty 
829           with _ -> raise (RefineFailure (lazy (localise orig_t, "try_coercions")))
830         in*)
831         let new_outty = add_pi_for_refl_m context new_outty mty m leftno rno in
832         pp (lazy ("CASE: new_outty: " ^ (status#ppterm 
833            ~metasenv ~subst ~context new_outty)));
834         let right_tys = 
835           List.map 
836             (fun t -> NCicTypeChecker.typeof status ~subst ~metasenv context t) right_p in
837         let eqs = 
838           List.map2 (fun x y -> NCic.Appl[eq_refl;x;y]) (right_tys@[mty]) 
839             (right_p@[m]) in
840         let t = NCic.Appl (NCic.Match(r,new_outty,m,pl) :: eqs) 
841         in
842         metasenv, subst, t, expty (*}}}*)
843     | _,`Type expty,NCic.LetIn(name,ty,t,bo) -> 
844         pp (lazy "LETIN");
845         let name' = mk_fresh_name context name in
846         let context_bo = (name', NCic.Def (t,ty)) :: context in
847         let metasenv, subst, bo2, _ = 
848           try_coercions status ~localise metasenv subst context_bo
849            bo orig_t (NCicSubstitution.lift status 1 infty)
850            (`Type (NCicSubstitution.lift status 1 expty)) exc
851         in
852         let coerced = NCic.LetIn (name',ty,t,bo2) in
853         pp (lazy ("LETIN: coerced = " ^ status#ppterm ~metasenv ~subst ~context coerced));
854         metasenv, subst, coerced, expty
855     | NCic.Prod (nameprod, src, ty),`Type (NCic.Prod (_, src2, ty2) as expty), _ -> 
856         (*{{{*) pp (lazy "LAM");
857         pp (lazy ("LAM: t = " ^ status#ppterm ~metasenv ~subst ~context t));
858         let namename = match t with NCic.Lambda (n,_,_) -> n | _ -> nameprod in
859         let name_con = mk_fresh_name context namename in
860         let context_src2 = ((name_con, NCic.Decl src2) :: context) in
861         (* contravariant part: the argument of f:src->ty *)
862         let metasenv, subst, rel1, _ = 
863           try_coercions status ~localise metasenv subst context_src2
864            (NCic.Rel 1) orig_t (NCicSubstitution.lift status 1 src2) 
865            (`Type (NCicSubstitution.lift status 1 src)) exc
866         in
867         (* covariant part: the result of f(c x); x:src2; (c x):src *)
868         let name_t, bo = 
869           match t with
870           | NCic.Lambda (n,_,bo) -> n, cs_subst rel1 (NCicSubstitution.lift_from status 2 1 bo)
871           | _ -> name_con, NCicUntrusted.mk_appl (NCicSubstitution.lift status 1 t) [rel1]
872         in
873         (* we fix the possible dependency problem in the source ty *)
874         let ty = cs_subst rel1 (NCicSubstitution.lift_from status 2 1 ty) in
875         let metasenv, subst, bo, _ = 
876           try_coercions status ~localise metasenv subst context_src2
877             bo orig_t ty (`Type ty2) exc
878         in
879         let coerced = NCic.Lambda (name_t,src2, bo) in
880         pp (lazy ("LAM: coerced = " ^ status#ppterm ~metasenv ~subst ~context coerced));
881         metasenv, subst, coerced, expty (*}}}*)
882     | _ -> raise exc
883   with exc2 ->    
884   let expty =
885    match expty with
886       `Type expty -> expty
887     | `Sort ->
888         NCic.Sort (NCic.Type 
889          (match NCicEnvironment.get_universes () with
890            | x::_ -> x 
891            | _ -> assert false))
892     | `Prod -> NCic.Prod ("_",NCic.Implicit `Type,NCic.Implicit `Type)
893   in
894   pp(lazy("try_coercion " ^ 
895     status#ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
896     status#ppterm ~metasenv ~subst ~context expty));
897     first exc
898       (NCicCoercion.look_for_coercion 
899         status metasenv subst context infty expty)
900
901 and force_to_sort status metasenv subst context t orig_t localise ty =
902   try 
903     let metasenv, subst, ty = 
904       NCicUnification.sortfy status (Failure "sortfy") metasenv subst context ty in
905       metasenv, subst, t, ty
906   with
907       Failure _ -> 
908         let msg =
909          (lazy (localise orig_t, 
910            "The type of " ^ status#ppterm ~metasenv ~subst ~context t ^
911            " is not a sort: " ^ status#ppterm ~metasenv ~subst ~context ty)) in
912         let ty = NCicReduction.whd status ~subst context ty in
913         let exn =
914          if NCicUnification.could_reduce status ~subst context ty then
915           Uncertain msg
916          else
917           RefineFailure msg
918         in
919           try_coercions status ~localise metasenv subst context
920             t orig_t ty `Sort exn
921
922 and sort_of_prod status localise metasenv subst context orig_s orig_t (name,s)
923  t (t1, t2) 
924 =
925    (* force to sort is done in the Prod case in typeof *)
926    match t1, t2 with
927    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
928    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
929         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
930    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
931    | C.Meta _, C.Sort _ 
932    | C.Meta _, C.Meta (_,(_,_))
933    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
934    | x, (C.Sort _ | C.Meta _) | _, x -> 
935       let y, context, orig = 
936         if x == t1 then s, context, orig_s 
937         else t, ((name,C.Decl s)::context), orig_t
938       in
939       raise (RefineFailure (lazy (localise orig,Printf.sprintf
940         "%s is expected to be a type, but its type is %s that is not a sort" 
941          (status#ppterm ~subst ~metasenv ~context y) 
942          (status#ppterm ~subst ~metasenv ~context x))))
943
944 and guess_name status subst ctx ty = 
945   let aux initial = "#" ^ String.make 1 initial in
946   match ty with
947   | C.Const (NReference.Ref (u,_))
948   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
949       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
950   | C.Prod _ -> aux 'f' 
951   | C.Meta (n,lc) -> 
952       (try
953          let _,_,t,_ = NCicUtils.lookup_subst n subst in
954          guess_name status subst ctx (NCicSubstitution.subst_meta status lc t)
955       with NCicUtils.Subst_not_found _ -> aux 'M')
956   | _ -> aux 'H' 
957
958 and eat_prods status ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
959   (*D*)inside 'E'; try let rc = 
960   let rec aux metasenv subst args_so_far he ty_he xxx =
961   (*D*)inside 'V'; try let rc = 
962    match xxx with
963   | [] ->
964      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
965      pp(lazy("FORCE FINAL APPL: " ^ 
966        status#ppterm ~metasenv ~subst ~context res ^
967        " of type " ^ status#ppterm ~metasenv ~subst ~context ty_he
968        ^ " to type " ^ match expty with None -> "None" | Some x -> 
969        status#ppterm ~metasenv ~subst ~context x));
970      (* whatever the term is, we force the type. in case of ((Lambda..) ?...)
971       * the application may also be a lambda! *)
972      force_ty false false metasenv subst context orig_t res ty_he expty
973   | NCic.Implicit `Vector::tl ->
974       let has_some_more_pis x =
975         match NCicReduction.whd status ~subst context x with
976         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
977         | _ -> true
978       in
979      (try
980        aux metasenv subst args_so_far he ty_he tl
981       with
982       | Uncertain _
983       | RefineFailure _ as exc when has_some_more_pis ty_he ->
984           (try
985            aux metasenv subst args_so_far he ty_he
986             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
987           with
988            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc))
989      | RefineFailure msg when not (has_some_more_pis ty_he) ->
990         (* instantiating the head could change the has_some_more_pis flag *)
991         raise (Uncertain msg))
992   | arg::tl ->
993       match NCicReduction.whd status ~subst context ty_he with 
994       | C.Prod (_,s,t) ->
995           let metasenv, subst, arg, _ = 
996             typeof status ~localise metasenv subst context arg (Some s) in
997           let t = NCicSubstitution.subst status ~avoid_beta_redexes:true arg t in
998           aux metasenv subst (arg :: args_so_far) he t tl
999       | C.Meta _
1000       | C.Appl (C.Meta _ :: _) as t ->
1001           let metasenv, subst, arg, ty_arg = 
1002             typeof status ~localise metasenv subst context arg None in
1003           let name = guess_name status subst context ty_arg in
1004           let metasenv, _, meta, _ = 
1005             NCicMetaSubst.mk_meta metasenv 
1006               ((name,C.Decl ty_arg) :: context) `IsType
1007           in
1008           let flex_prod = C.Prod (name, ty_arg, meta) in
1009           (* next line grants that ty_args is a type *)
1010           let metasenv,subst, flex_prod, _ =
1011            typeof status ~localise metasenv subst context flex_prod None in
1012 (*
1013           pp (lazy ( "UNIFICATION in CTX:\n"^ 
1014             status#ppcontext ~metasenv ~subst context
1015             ^ "\nOF: " ^
1016             status#ppterm ~metasenv ~subst ~context t ^  " === " ^
1017             status#ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
1018 *)
1019           let metasenv, subst =
1020              try NCicUnification.unify status metasenv subst context t flex_prod 
1021              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
1022               ("The term %s has an inferred type %s, but is applied to the" ^^
1023                " argument %s of type %s")
1024               (status#ppterm ~metasenv ~subst ~context he)
1025               (status#ppterm ~metasenv ~subst ~context t)
1026               (status#ppterm ~metasenv ~subst ~context arg)
1027               (status#ppterm ~metasenv ~subst ~context ty_arg))) 
1028                  (match exc with
1029                  | NCicUnification.UnificationFailure m -> 
1030                      NCicUnification.Uncertain m
1031                  | x -> x))
1032               (* XXX coerce to funclass *)
1033           in
1034           let meta = NCicSubstitution.subst status ~avoid_beta_redexes:true arg meta in
1035           aux metasenv subst (arg :: args_so_far) he meta tl
1036       | C.Match (_,_,C.Meta _,_) 
1037       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
1038       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
1039           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
1040             ("The term %s is here applied to %d arguments but expects " ^^
1041             "only %d arguments") (status#ppterm ~metasenv ~subst ~context he)
1042             (List.length args) (List.length args_so_far))))
1043       | ty ->
1044           let metasenv, subst, newhead, newheadty = 
1045             try_coercions status ~localise metasenv subst context
1046               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
1047               `Prod
1048               (RefineFailure (lazy (localise orig_he, Printf.sprintf
1049                ("The term %s is here applied to %d arguments but expects " ^^
1050                "only %d arguments") (status#ppterm ~metasenv ~subst ~context he)
1051                (List.length args) (List.length args_so_far))))
1052           in
1053            aux metasenv subst [] newhead newheadty (arg :: tl)
1054   (*D*)in outside true; rc with exc -> outside false; raise exc
1055   in
1056    (* We need to reverse the order of the new created metas since they
1057       are pushed on top of the metasenv in the wrong order *)
1058    let highest_meta = NCicMetaSubst.maxmeta () in
1059    let metasenv, subst, newhead, newheadty = 
1060     aux metasenv subst [] he ty_he args in
1061    let metasenv_old,metasenv_new =
1062     List.partition (fun (i,_) -> i <= highest_meta) metasenv
1063    in
1064     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
1065   (*D*)in outside true; rc with exc -> outside false; raise exc
1066 ;;
1067
1068 let rec first f l1 l2 =
1069   match l1,l2 with
1070   | x1::tl1, x2::tl2 -> 
1071       (try f x1 x2 with Not_found -> first f tl1 tl2)
1072   | _ -> raise Not_found
1073 ;;
1074
1075 let rec find add dt t =
1076   if dt == add then t
1077   else
1078     let dl, l = 
1079       match dt, t with
1080       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
1081       | C.Appl dl,C.Appl l -> dl,l
1082       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
1083       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
1084       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
1085       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
1086       | _ -> raise Not_found
1087     in
1088       first (find add) dl l
1089 ;;
1090
1091 let relocalise old_localise dt t add = 
1092   old_localise 
1093     (try find add dt t with Not_found -> assert false)
1094 ;;
1095
1096 let undebruijnate status inductive ref t rev_fl =
1097   let len = List.length rev_fl in 
1098   NCicSubstitution.psubst status (fun x -> x) 
1099    (HExtlib.list_mapi 
1100       (fun (_,_,rno,_,_,_) i -> 
1101          let i = len - i - 1 in
1102          NCic.Const 
1103            (if inductive then NReference.mk_fix i rno ref
1104             else NReference.mk_cofix i ref))
1105       rev_fl)
1106     t
1107 ;; 
1108
1109
1110 let typeof_obj 
1111   status ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
1112
1113   match obj with 
1114   | C.Constant (relevance, name, bo, ty, attr) ->
1115        let metasenv, subst, ty = 
1116          check_type status ~localise metasenv subst [] ty in
1117        let metasenv, subst, bo, ty, height = 
1118          match bo with
1119          | Some bo ->
1120              let metasenv, subst, bo, ty = 
1121                typeof status ~localise metasenv subst [] bo (Some ty) in
1122              let height = (* XXX recalculate *) height in
1123                metasenv, subst, Some bo, ty, height
1124          | None -> metasenv, subst, None, ty, 0
1125        in
1126        uri, height, metasenv, subst, 
1127          C.Constant (relevance, name, bo, ty, attr)
1128   | C.Fixpoint (inductive, fl, attr) -> 
1129       let len = List.length fl in
1130       let types, metasenv, subst, rev_fl =
1131         List.fold_left
1132          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
1133            let metasenv, subst, ty = 
1134              check_type status ~localise metasenv subst [] ty in
1135            let dbo = NCicTypeChecker.debruijn status uri len [] ~subst bo in
1136            let localise = relocalise localise dbo bo in
1137             (name,C.Decl ty)::types,
1138               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
1139          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
1140       in
1141       let metasenv, subst, fl = 
1142         List.fold_left 
1143           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
1144             let metasenv, subst, dbo, ty = 
1145               typeof status ~localise metasenv subst types dbo (Some ty)
1146             in
1147             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
1148           (metasenv, subst, []) rev_fl
1149       in
1150       let height = (* XXX recalculate *) height in
1151       let fl =
1152         List.map 
1153           (fun (relevance,name,k,ty,dbo) ->
1154             let bo = 
1155               undebruijnate status inductive 
1156                (NReference.reference_of_spec uri 
1157                  (if inductive then NReference.Fix (0,k,0) 
1158                   else NReference.CoFix 0)) dbo rev_fl
1159             in
1160               relevance,name,k,ty,bo)
1161           fl
1162       in
1163        uri, height, metasenv, subst, 
1164          C.Fixpoint (inductive, fl, attr)
1165   | C.Inductive (ind, leftno, itl, attr) ->
1166      let len = List.length itl in
1167      let metasenv,subst,rev_itl,tys =
1168       List.fold_left
1169        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
1170           let metasenv, subst, ty = 
1171             check_type status ~localise metasenv subst [] ty in
1172           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
1173        ) (metasenv,subst,[],[]) itl in
1174      let metasenv,subst,itl,_ =
1175       List.fold_left
1176        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
1177          let context,ty_sort = NCicReduction.split_prods status ~subst [] ~-1 ty in
1178          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
1179          let metasenv,subst,cl =
1180           List.fold_right
1181            (fun (k_relev,n,te) (metasenv,subst,res) ->
1182              let k_relev =
1183               try snd (HExtlib.split_nth leftno k_relev)
1184               with Failure _ -> k_relev in
1185              let te = NCicTypeChecker.debruijn status uri len [] ~subst te in
1186              let metasenv, subst, te = 
1187                check_type status ~localise metasenv subst tys te in
1188              let context,te = NCicReduction.split_prods status ~subst tys leftno te in
1189              let _,chopped_context_rev =
1190               HExtlib.split_nth (List.length tys) (List.rev context) in
1191              let sx_context_te_rev,_ =
1192               HExtlib.split_nth leftno chopped_context_rev in
1193              let metasenv,subst,_ =
1194               try
1195                List.fold_left2
1196                 (fun (metasenv,subst,context) item1 item2 ->
1197                   let (metasenv,subst),convertible =
1198                    try
1199                     match item1,item2 with
1200                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
1201                         if n1 = n2 then
1202                          NCicUnification.unify status ~test_eq_only:true metasenv
1203                           subst context ty1 ty2,true
1204                         else
1205                          (metasenv,subst),false
1206                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
1207                         if n1 = n2 then
1208                          let metasenv,subst =
1209                           NCicUnification.unify status ~test_eq_only:true metasenv
1210                            subst context ty1 ty2
1211                          in
1212                           NCicUnification.unify status ~test_eq_only:true metasenv
1213                            subst context bo1 bo2,true
1214                         else
1215                          (metasenv,subst),false
1216                     | _,_ -> (metasenv,subst),false
1217                    with
1218                    | NCicUnification.Uncertain _
1219                    | NCicUnification.UnificationFailure _ ->
1220                       (metasenv,subst),false
1221                   in
1222                    let term2 =
1223                     match item2 with
1224                        _,C.Decl t -> t
1225                      | _,C.Def (b,_) -> b in
1226                    if not convertible then
1227                     raise (RefineFailure (lazy (localise term2,
1228                      ("Mismatch between the left parameters of the constructor " ^
1229                       "and those of its inductive type"))))
1230                    else
1231                     metasenv,subst,item1::context
1232                 ) (metasenv,subst,tys) sx_context_ty_rev sx_context_te_rev
1233               with Invalid_argument "List.fold_left2" -> assert false in
1234              let metasenv, subst =
1235                 let rec aux context (metasenv,subst) = function
1236                   | NCic.Meta _ -> metasenv, subst
1237                   | NCic.Implicit _ -> metasenv, subst
1238                   | NCic.Appl (NCic.Rel i :: args) as t
1239                       when i > List.length context - len ->
1240                       let lefts, _ = HExtlib.split_nth leftno args in
1241                       let ctxlen = List.length context in
1242                       let (metasenv, subst), _ = 
1243                         List.fold_left
1244                         (fun ((metasenv, subst),l) arg ->
1245                           NCicUnification.unify status 
1246                            ~test_eq_only:true metasenv subst context arg 
1247                              (NCic.Rel (ctxlen - len - l)), l+1
1248                           )
1249                         ((metasenv, subst), 0) lefts
1250                       in
1251                       metasenv, subst
1252                   | t -> NCicUtils.fold (fun e c -> e::c) context aux
1253                   (metasenv,subst) t
1254                 in
1255                aux context (metasenv,subst) te
1256              in
1257              let con_sort= NCicTypeChecker.typeof status ~subst ~metasenv context te in
1258               (match
1259                 NCicReduction.whd status ~subst context con_sort,
1260                 NCicReduction.whd status ~subst [] ty_sort
1261                with
1262                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
1263                    if not (NCicEnvironment.universe_leq u1 u2) then
1264                     raise
1265                      (RefineFailure
1266                        (lazy(localise te, "The type " ^
1267                          status#ppterm ~metasenv ~subst ~context s1 ^
1268                          " of the constructor is not included in the inductive"^
1269                          " type sort " ^
1270                          status#ppterm ~metasenv ~subst ~context s2)))
1271                 | C.Sort _, C.Sort C.Prop
1272                 | C.Sort _, C.Sort C.Type _ -> ()
1273                 | _, _ ->
1274                    raise
1275                     (RefineFailure
1276                       (lazy (localise te,
1277                         "Wrong constructor or inductive arity shape"))));
1278               (* let's check also the positivity conditions *)
1279               if 
1280                not
1281                (NCicTypeChecker.are_all_occurrences_positive status
1282                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
1283               then
1284                 raise
1285                   (RefineFailure
1286                     (lazy (localise te,
1287                       "Non positive occurence in " ^
1288                         status#ppterm ~metasenv ~subst ~context te)))
1289               else
1290                let relsno = List.length itl + leftno in
1291                let te = 
1292                  NCicSubstitution.psubst status
1293                   (fun i ->
1294                     if i <= leftno  then
1295                      NCic.Rel i
1296                     else
1297                      NCic.Const (NReference.reference_of_spec uri
1298                       (NReference.Ind (ind,relsno - i,leftno))))
1299                   (HExtlib.list_seq 1 (relsno+1))
1300                    te in
1301                let te =
1302                 List.fold_right
1303                  (fun (name,decl) te ->
1304                    match decl with
1305                       NCic.Decl ty -> NCic.Prod (name,ty,te)
1306                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
1307                  ) sx_context_te_rev te
1308                in
1309                 metasenv,subst,(k_relev,n,te)::res
1310               ) cl (metasenv,subst,[])
1311          in
1312           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
1313        ) (metasenv,subst,[],1) rev_itl
1314      in
1315       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
1316 ;;
1317
1318 (* vim:set foldmethod=marker: *)