]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
added sortification for (? args), untested code
[helm.git] / helm / software / components / ng_refiner / nCicUnification.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 UnificationFailure of string Lazy.t;;
15 exception Uncertain of string Lazy.t;;
16 exception AssertFailure of string Lazy.t;;
17
18 let (===) x y = Pervasives.compare x y = 0 ;;
19
20 let uncert_exc metasenv subst context t1 t2 = 
21   Uncertain (lazy (
22   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
23   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2))
24 ;;
25
26 let fail_exc metasenv subst context t1 t2 = 
27   UnificationFailure (lazy (
28   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
29   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2));
30 ;;
31
32 let mk_appl ~upto hd tl =
33   NCicReduction.head_beta_reduce ~upto
34     (match hd with
35     | NCic.Appl l -> NCic.Appl (l@tl)
36     | _ -> NCic.Appl (hd :: tl))
37 ;;
38
39 exception WrongShape;;
40
41 let eta_reduce subst t = 
42   let delift_if_not_occur body =
43     try 
44         Some (NCicSubstitution.psubst ~avoid_beta_redexes:true
45           (fun () -> raise WrongShape) [()] body)
46     with WrongShape -> None
47   in 
48   let rec eat_lambdas ctx = function
49     | NCic.Lambda (name, src, tgt) -> 
50         eat_lambdas ((name, src) :: ctx) tgt
51     | NCic.Meta (i,lc) as t->
52         (try 
53           let _,_,t,_ = NCicUtils.lookup_subst i subst in
54           let t = NCicSubstitution.subst_meta lc t in
55           eat_lambdas ctx t
56         with Not_found -> ctx, t)
57     | t -> ctx, t
58   in
59   let context_body = eat_lambdas [] t in
60   let rec aux = function
61     | [],body -> body
62     | (name, src)::ctx, (NCic.Appl (hd::[NCic.Rel 1]) as bo) -> 
63         (match delift_if_not_occur hd with
64         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
65         | Some bo -> aux (ctx,bo))
66     | (name, src)::ctx, (NCic.Appl args as bo) 
67       when HExtlib.list_last args = NCic.Rel 1 -> 
68         let args, _ = HExtlib.split_nth (List.length args - 1) args in
69         (match delift_if_not_occur (NCic.Appl args) with
70         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
71         | Some bo -> aux (ctx,bo))
72     | (name, src) :: ctx, t ->
73         aux (ctx,NCic.Lambda(name,src, t)) 
74   in
75     aux context_body
76 ;;
77
78 module C = NCic;;
79 module Ref = NReference;;
80
81 let debug = false;;
82 let indent = ref "";;
83 let pp =
84  if debug then
85   fun s -> prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
86  else 
87   fun _ -> ()
88 ;;
89 let inside c =
90  indent := !indent ^ String.make 1 c;
91  if debug then prerr_endline ("{{{" ^ !indent ^ " ")
92 ;;
93 let outside ok =
94  if debug then prerr_endline "}}}";
95  if not ok then pp (lazy "exception raised!");
96  try
97   indent := String.sub !indent 0 (String.length !indent -1)
98  with
99   Invalid_argument _ -> indent := "??"; ()
100 ;;
101
102 let ppcontext ~metasenv ~subst c = 
103       "\nctx:\n"^ NCicPp.ppcontext ~metasenv ~subst c
104 ;;
105 let ppmetasenv ~subst m = "\nmenv:\n" ^ NCicPp.ppmetasenv ~subst m;;
106
107 let ppcontext ~metasenv:_metasenv ~subst:_subst _context = "";;
108 let ppmetasenv ~subst:_subst _metasenv = "";;
109
110 let fix_sorts swap exc t =
111   let rec aux () = function
112     | NCic.Sort (NCic.Type u) as orig ->
113         if swap then
114          match NCicEnvironment.sup u with
115          | None ->
116             prerr_endline ("no sup for " ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] orig) ;
117             raise exc
118          | Some u1 -> if u = u1 then orig else NCic.Sort (NCic.Type u1)
119         else
120          NCic.Sort (NCic.Type (
121            match NCicEnvironment.sup NCicEnvironment.type0 with 
122            | Some x -> x
123            | _ -> assert false))
124     | NCic.Meta _ as orig -> orig
125     | t -> NCicUtils.map (fun _ _ -> ()) () aux t
126   in
127     aux () t
128 ;;
129
130 let is_locked n subst =
131    try
132      match NCicUtils.lookup_subst n subst with
133      | tag, _,_,_ when NCicMetaSubst.is_out_scope_tag tag -> true
134      | _ -> false
135    with NCicUtils.Subst_not_found _ -> false
136 ;;
137
138 let rec mk_irl =
139  function
140     0 -> []
141   | n -> NCic.Rel n :: mk_irl (n-1)
142 ;;
143
144 (* the argument must be a term in whd *)
145 let rec could_reduce =
146  function
147   | C.Meta _ -> true
148   | C.Appl (C.Const (Ref.Ref (_,Ref.Fix (_,recno,_)))::args)
149      when List.length args > recno -> could_reduce (List.nth args recno)
150   | C.Match (_,_,arg,_) -> could_reduce arg
151   | C.Appl (he::_) -> could_reduce he
152   | C.Sort _ | C.Rel _ | C.Prod _ | C.Lambda _ | C.Const _ -> false
153   | C.Appl [] | C.LetIn _ | C.Implicit _ -> assert false
154 ;;
155
156 let rec lambda_intros rdb metasenv subst context t args =
157  let tty = NCicTypeChecker.typeof ~metasenv ~subst context t in
158  let argsty =
159   List.map
160   (fun arg -> arg, NCicTypeChecker.typeof ~metasenv ~subst context arg) args in
161  let context_of_args = context in
162  let rec mk_lambda metasenv subst context n processed_args = function
163    | [] ->
164        let metasenv, _, bo, _ = 
165          NCicMetaSubst.mk_meta metasenv context 
166            (`WithType (NCicSubstitution.lift n tty))
167        in
168        metasenv, subst, bo
169    | (arg,ty)::tail ->
170        pp(lazy("arg{ " ^ 
171          NCicPp.ppterm ~metasenv ~subst ~context:context_of_args arg ^  ":" ^
172          NCicPp.ppterm ~metasenv ~subst ~context:context_of_args ty));
173        let metasenv, subst, telescopic_ty = 
174          if processed_args = [] then metasenv, subst, ty else
175          let _ = pp(lazy("delift")) in
176          delift_type_wrt_terms rdb metasenv subst context_of_args ty 
177            (List.rev processed_args)
178        in
179        pp(lazy("arg}"));
180        let name = "HBeta"^string_of_int n in
181        let metasenv, subst, bo =
182         mk_lambda metasenv subst ((name,NCic.Decl telescopic_ty)::context) (n+1)
183          (arg::processed_args) tail
184        in
185         metasenv, subst, NCic.Lambda (name, telescopic_ty, bo)
186  in
187  pp(lazy("LAMBDA_INTROS{ " ^ 
188    NCicPp.ppterm ~metasenv ~subst ~context t ^  ":" ^
189    NCicPp.ppterm ~metasenv ~subst ~context tty ^ " over " ^ 
190    String.concat "," (List.map (NCicPp.ppterm ~metasenv ~subst ~context)args)));
191  let rc = mk_lambda metasenv subst context 0 [] argsty in
192  pp(lazy("LAMBDA_INTROS}"));
193  rc
194
195 and instantiate rdb test_eq_only metasenv subst context n lc t swap =
196  (*D*)  inside 'I'; try let rc =  
197          pp (lazy(string_of_int n ^ " :=?= "^
198            NCicPp.ppterm ~metasenv ~subst ~context t));
199   let unify test_eq_only m s c t1 t2 = 
200     if swap then unify rdb test_eq_only m s c t2 t1 
201     else unify rdb test_eq_only m s c t1 t2
202   in
203   let has_tag = List.exists in
204   let tags, _, ty = NCicUtils.lookup_meta n metasenv in
205   (* on the types *)
206   let metasenv, subst, t = 
207     match ty with 
208     | NCic.Implicit (`Typeof _) -> 
209          pp(lazy("meta with no type"));
210          assert(has_tag ((=)`IsSort) tags); 
211          metasenv, subst, t
212     | _ ->
213        let exc_to_be = fail_exc metasenv subst context (NCic.Meta (n,lc)) t in
214        let t, ty_t = 
215          try t, NCicTypeChecker.typeof ~subst ~metasenv context t 
216          with 
217          | NCicTypeChecker.AssertFailure msg as exn -> 
218               pp(lazy("we try to fix the sort\n"^
219                 Lazy.force msg^"\n"^NCicPp.ppmetasenv ~subst metasenv));
220               let ft = fix_sorts swap exc_to_be t in
221               pp(lazy("unable to fix the sort"));
222               if ft == t then raise exn;
223               (try ft, NCicTypeChecker.typeof ~subst ~metasenv context ft 
224                with NCicTypeChecker.AssertFailure _ -> raise exn)
225          | NCicTypeChecker.TypeCheckerFailure msg ->
226               prerr_endline (Lazy.force msg);
227               prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);
228               prerr_endline (ppcontext ~metasenv ~subst context); 
229               prerr_endline (ppmetasenv ~subst metasenv);
230               assert false
231        in
232        match ty_t with
233        | NCic.Implicit (`Typeof _) -> 
234            raise (UnificationFailure(lazy "trying to unify a term with a type"))
235        | _ -> 
236           let lty = NCicSubstitution.subst_meta lc ty in
237           pp (lazy ("On the types: " ^
238               NCicPp.ppterm ~metasenv ~subst ~context lty ^ " === " ^ 
239               NCicPp.ppterm ~metasenv ~subst ~context ty_t)); 
240           let metasenv,subst = 
241            try unify test_eq_only metasenv subst context lty ty_t
242            with NCicEnvironment.BadConstraint _ as exc ->
243             let ty_t = fix_sorts swap exc_to_be ty_t in 
244              try unify test_eq_only metasenv subst context lty ty_t
245              with 
246              | NCicEnvironment.BadConstraint _ 
247              | UnificationFailure _ -> raise exc 
248           in
249            metasenv, subst, t
250   in 
251   (* viral sortification *)
252   let is_sort metasenv subst context t = 
253     match NCicReduction.whd ~subst context t with
254     | NCic.Meta (i,_) ->
255          let tags, _, _ = NCicUtils.lookup_meta i metasenv in
256          has_tag ((=) `IsSort) tags
257     | NCic.Sort _ -> true
258     | _ -> false
259   in
260   let rec sortify metasenv subst = function
261     | NCic.Implicit (`Typeof _) -> assert false 
262     | NCic.Sort _ as t -> metasenv, subst, t, 0
263     | NCic.Meta (i,_) as t -> 
264          let tags, context, ty = NCicUtils.lookup_meta i metasenv in
265          if has_tag ((=) `IsSort) tags then metasenv, subst, t, i
266          else
267            let ty = NCicReduction.whd ~subst context ty in
268            let metasenv, subst, ty, _ = sortify metasenv subst ty in
269            let metasenv, j, m, _ = 
270              NCicMetaSubst.mk_meta metasenv ~attrs:[`IsSort] [] (`WithType ty)
271            in
272            pp(lazy("rimpiazzo " ^ string_of_int i^" con "^string_of_int j));
273            let subst_entry = i, (tags, context, m, ty) in
274            let subst = subst_entry :: subst in
275            let metasenv = List.filter (fun x,_ -> i <> x) metasenv in
276            metasenv, subst, m, j 
277     | NCic.Appl (NCic.Meta _ as hd :: args) as t -> 
278            let metasenv, subst, lambda_Mj =
279              lambda_intros rdb metasenv subst context t args
280            in
281            let metasenv,subst= unify true metasenv subst context hd lambda_Mj in
282            let t = NCicReduction.whd ~subst context t in
283            let _result = sortify metasenv subst t in       
284            (* untested, maybe dead, code *) assert false;
285     | t -> 
286          if could_reduce t then raise (Uncertain(lazy "not a sort"))
287          else raise (UnificationFailure(lazy "not a sort"))
288   in
289   let metasenv, subst, _, n = 
290     if has_tag ((=) `IsSort) tags then
291       let m,s,x,_ = sortify metasenv subst (NCicReduction.whd ~subst context t)
292       in m,s,x,n
293     else if is_sort metasenv subst context t then
294       sortify metasenv subst (NCic.Meta (n,lc))
295     else
296       metasenv, subst, NCic.Rel ~-1,n
297   in
298   let tags, ctx, ty = NCicUtils.lookup_meta n metasenv in
299   (* instantiation *)
300   pp (lazy(string_of_int n ^ " := 111 = "^ 
301     NCicPp.ppterm ~metasenv ~subst ~context t));
302   let (metasenv, subst), t = 
303     try 
304       NCicMetaSubst.delift 
305        ~unify:(fun m s c t1 t2 -> 
306          let ind = !indent in
307          let res = 
308            try Some (unify test_eq_only m s c t1 t2 )
309            with UnificationFailure _ | Uncertain _ -> None
310          in
311          indent := ind; res) 
312        metasenv subst context n lc t
313     with NCicMetaSubst.Uncertain msg -> 
314          pp (lazy ("delift fails: " ^ Lazy.force msg));
315          raise (Uncertain msg)
316     | NCicMetaSubst.MetaSubstFailure msg -> 
317          pp (lazy ("delift fails: " ^ Lazy.force msg));
318          raise (UnificationFailure msg)
319   in
320          pp (lazy(string_of_int n ^ " := 222 = "^
321            NCicPp.ppterm ~metasenv ~subst ~context:ctx t
322          ^ ppmetasenv ~subst metasenv));
323   (* Unifying the types may have already instantiated n. *)
324   try
325     let _, _,oldt,_ = NCicUtils.lookup_subst n subst in
326     let oldt = NCicSubstitution.subst_meta lc oldt in
327     let t = NCicSubstitution.subst_meta lc t in
328     (* conjecture: always fail --> occur check *)
329     unify test_eq_only metasenv subst context oldt t
330   with NCicUtils.Subst_not_found _ -> 
331     (* by cumulativity when unify(?,Type_i) 
332      * we could ? := Type_j with j <= i... *)
333     let subst = (n, (tags, ctx, t, ty)) :: subst in
334     pp (lazy ("?"^string_of_int n^" := "^NCicPp.ppterm
335       ~metasenv ~subst ~context (NCicSubstitution.subst_meta lc t)));
336     let metasenv = 
337       List.filter (fun (m,_) -> not (n = m)) metasenv 
338     in
339     metasenv, subst
340  (*D*)  in outside true; rc with exn -> outside false; raise exn 
341
342 and unify rdb test_eq_only metasenv subst context t1 t2 =
343  (*D*) inside 'U'; try let rc =
344    let fo_unif test_eq_only metasenv subst t1 t2 =
345     (*D*) inside 'F'; try let rc =  
346      pp (lazy("  " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
347          NCicPp.ppterm ~metasenv ~subst ~context t2 ^ ppmetasenv
348          ~subst metasenv));
349      if t1 === t2 then
350        metasenv, subst
351      else
352        match (t1,t2) with
353        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
354        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
355            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
356            assert false 
357        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
358            if NCicEnvironment.universe_leq a b then metasenv, subst
359            else raise (fail_exc metasenv subst context t1 t2)
360        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
361            if NCicEnvironment.universe_eq a b then metasenv, subst
362            else raise (fail_exc metasenv subst context t1 t2)
363        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
364            if (not test_eq_only) then metasenv, subst
365            else raise (fail_exc metasenv subst context t1 t2)
366
367        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
368        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
369            let metasenv, subst = unify rdb true metasenv subst context s1 s2 in
370            unify rdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
371        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
372            let metasenv,subst=unify rdb test_eq_only metasenv subst context ty1 ty2 in
373            let metasenv,subst=unify rdb test_eq_only metasenv subst context s1 s2 in
374            let context = (name1, C.Def (s1,ty1))::context in
375            unify rdb test_eq_only metasenv subst context t1 t2
376
377        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
378           (try 
379            let l1 = NCicUtils.expand_local_context l1 in
380            let l2 = NCicUtils.expand_local_context l2 in
381            let metasenv, subst, to_restrict, _ =
382             List.fold_right2 
383              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
384                 try 
385                   let metasenv, subst = 
386                    unify rdb test_eq_only metasenv subst context 
387                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
388                   in
389                   metasenv, subst, to_restrict, i-1  
390                 with UnificationFailure _ | Uncertain _ ->
391                   metasenv, subst, i::to_restrict, i-1)
392              l1 l2 (metasenv, subst, [], List.length l1)
393            in
394            if to_restrict <> [] then
395              let metasenv, subst, _ = 
396                NCicMetaSubst.restrict metasenv subst n1 to_restrict
397              in
398                metasenv, subst
399            else metasenv, subst
400           with 
401            | Invalid_argument _ -> assert false
402            | NCicMetaSubst.MetaSubstFailure msg ->
403               try 
404                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
405                 let term1 = NCicSubstitution.subst_meta lc1 term in
406                 let term2 = NCicSubstitution.subst_meta lc2 term in
407                   unify rdb test_eq_only metasenv subst context term1 term2
408               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
409        
410        | _, NCic.Meta (n, _) when is_locked n subst ->
411            (let (metasenv, subst), i = 
412               match NCicReduction.whd ~subst context t1 with
413               | NCic.Appl (NCic.Meta (i,l)::args) ->
414                  let metasenv, subst, lambda_Mj =
415                    lambda_intros rdb metasenv subst context t1 args
416                  in
417                    unify rdb test_eq_only metasenv subst context 
418                     (C.Meta (i,l)) lambda_Mj,
419                    i
420               | NCic.Meta (i,_) -> (metasenv, subst), i
421               | _ ->
422                  raise (UnificationFailure (lazy "Locked term vs non
423                   flexible term; probably not saturated enough yet!"))
424              in
425               let t1 = NCicReduction.whd ~subst context t1 in
426               let j, lj = 
427                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
428               in
429               let metasenv, subst = 
430                 instantiate rdb test_eq_only metasenv subst context j lj t2 true
431               in
432               (* We need to remove the out_scope_tags to avoid propagation of
433                  them that triggers again the ad-hoc case *)
434               let subst =
435                List.map (fun (i,(tag,ctx,bo,ty)) ->
436                 let tag =
437                  List.filter
438                   (function `InScope | `OutScope _ -> false | _ -> true) tag
439                 in
440                   i,(tag,ctx,bo,ty)
441                 ) subst
442               in
443               (try
444                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
445                 let term = eta_reduce subst term in
446                 let subst = List.filter (fun (j,_) -> j <> i) subst in
447                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
448               with Not_found -> assert false))
449
450        | C.Meta (n,lc), t -> 
451            (try 
452              let _,_,term,_ = NCicUtils.lookup_subst n subst in
453              let term = NCicSubstitution.subst_meta lc term in
454                unify rdb test_eq_only metasenv subst context term t
455            with NCicUtils.Subst_not_found _-> 
456              instantiate rdb test_eq_only metasenv subst context n lc 
457                (NCicReduction.head_beta_reduce ~subst t) false)
458
459        | t, C.Meta (n,lc) -> 
460            (try 
461              let _,_,term,_ = NCicUtils.lookup_subst n subst in
462              let term = NCicSubstitution.subst_meta lc term in
463                unify rdb test_eq_only metasenv subst context t term
464            with NCicUtils.Subst_not_found _-> 
465              instantiate rdb test_eq_only metasenv subst context n lc 
466               (NCicReduction.head_beta_reduce ~subst t) true)
467
468        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
469             let _,_,term,_ = NCicUtils.lookup_subst i subst in
470             let term = NCicSubstitution.subst_meta l term in
471               unify rdb test_eq_only metasenv subst context 
472                 (mk_appl ~upto:(List.length args) term args) t2
473
474        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
475             let _,_,term,_ = NCicUtils.lookup_subst i subst in
476             let term = NCicSubstitution.subst_meta l term in
477               unify rdb test_eq_only metasenv subst context t1 
478                 (mk_appl ~upto:(List.length args) term args)
479
480        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
481           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
482             (try
483               List.fold_left2 
484                 (fun (metasenv, subst) t1 t2 ->
485                   unify rdb test_eq_only metasenv subst context t1 t2)
486                 (metasenv,subst) l1 l2
487             with Invalid_argument _ -> 
488               raise (fail_exc metasenv subst context t1 t2))
489
490        | NCic.Appl (NCic.Meta (i,l)::args), _ ->
491           let metasenv, subst, lambda_Mj =
492             lambda_intros rdb metasenv subst context t1 args
493           in
494           let metasenv, subst = 
495             unify rdb test_eq_only metasenv subst context 
496               (C.Meta (i,l)) lambda_Mj
497           in
498           let metasenv, subst = 
499             unify rdb test_eq_only metasenv subst context t1 t2 
500           in
501           (try
502             let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
503             let term = eta_reduce subst term in
504             let subst = List.filter (fun (j,_) -> j <> i) subst in
505             metasenv, ((i, (name, ctx, term, ty)) :: subst)
506           with Not_found -> assert false)
507
508        | _, NCic.Appl (NCic.Meta (i,l)::args) ->
509          let metasenv, subst, lambda_Mj =
510            lambda_intros rdb metasenv subst context t2 args
511          in
512          let metasenv, subst =
513            unify rdb test_eq_only metasenv subst context 
514             lambda_Mj (C.Meta (i,l))
515          in
516          let metasenv, subst = 
517            unify rdb test_eq_only metasenv subst context t1 t2 
518          in
519          (try
520            let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
521            let term = eta_reduce subst term in
522            let subst = List.filter (fun (j,_) -> j <> i) subst in
523            metasenv, ((i, (name, ctx, term, ty)) :: subst)
524          with Not_found -> assert false)
525
526        (* processing this case here we avoid a useless small delta step *)
527        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
528          when Ref.eq r1 r2 ->
529            let relevance = NCicEnvironment.get_relevance r1 in
530            let relevance = match r1 with
531              | Ref.Ref (_,Ref.Con (_,_,lno)) ->
532                  let relevance =
533                   try snd (HExtlib.split_nth lno relevance)
534                   with Failure _ -> []
535                  in
536                    HExtlib.mk_list false lno @ relevance
537              | _ -> relevance
538            in
539            let metasenv, subst, _ = 
540              try
541                List.fold_left2 
542                  (fun (metasenv, subst, relevance) t1 t2 ->
543                     let b, relevance = 
544                       match relevance with b::tl -> b,tl | _ -> true, [] in
545                     let metasenv, subst = 
546                       try unify rdb test_eq_only metasenv subst context t1 t2
547                       with UnificationFailure _ | Uncertain _ when not b ->
548                         metasenv, subst
549                     in
550                       metasenv, subst, relevance)
551                  (metasenv, subst, relevance) tl1 tl2
552              with Invalid_argument _ -> 
553                raise (uncert_exc metasenv subst context t1 t2)
554            in 
555              metasenv, subst
556
557        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
558           C.Match (ref2,outtype2,term2,pl2)) ->
559            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
560            let _,_,ty,_ = List.nth itl tyno in
561            let rec remove_prods ~subst context ty = 
562              let ty = NCicReduction.whd ~subst context ty in
563              match ty with
564              | C.Sort _ -> ty
565              | C.Prod (name,so,ta) -> 
566                    remove_prods ~subst ((name,(C.Decl so))::context) ta
567              | _ -> assert false
568            in
569            let is_prop = 
570              match remove_prods ~subst [] ty with
571              | C.Sort C.Prop -> true
572              | _ -> false 
573            in
574            if not (Ref.eq ref1 ref2) then 
575              raise (uncert_exc metasenv subst context t1 t2) 
576            else
577              let metasenv, subst = 
578               unify rdb test_eq_only metasenv subst context outtype1 outtype2 in
579              let metasenv, subst = 
580                try unify rdb test_eq_only metasenv subst context term1 term2 
581                with UnificationFailure _ | Uncertain _ when is_prop -> 
582                  metasenv, subst
583              in
584              (try
585               List.fold_left2 
586                (fun (metasenv,subst) -> 
587                   unify rdb test_eq_only metasenv subst context)
588                (metasenv, subst) pl1 pl2
589              with Invalid_argument _ -> assert false)
590        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
591        | _ when NCicUntrusted.metas_of_term subst context t1 = [] && 
592                 NCicUntrusted.metas_of_term subst context t2 = [] -> 
593                   raise (fail_exc metasenv subst context t1 t2)
594        | _ -> raise (uncert_exc metasenv subst context t1 t2)
595      (*D*)  in outside true; rc with exn -> outside false; raise exn 
596     in
597     let try_hints metasenv subst t1 t2 (* exc*) =
598     (*D*) inside 'H'; try let rc =  
599 (*
600       prerr_endline ("\nProblema:\n" ^
601         NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
602         NCicPp.ppterm ~metasenv ~subst ~context t2);
603 *)
604       let candidates = 
605         NCicUnifHint.look_for_hint rdb metasenv subst context t1 t2
606       in
607       let rec cand_iter = function
608         | [] -> None (* raise exc *)
609         | (metasenv,(c1,c2),premises)::tl -> 
610             pp (lazy ("\nProvo il candidato:\n" ^ 
611               String.concat "\n"
612                 (List.map 
613                   (fun (a,b) ->
614                    NCicPp.ppterm ~metasenv ~subst ~context a ^  " =?= " ^
615                    NCicPp.ppterm ~metasenv ~subst ~context b) premises) ^
616               "\n-------------------------------------------\n"^
617               NCicPp.ppterm ~metasenv ~subst ~context c1 ^  " = " ^
618               NCicPp.ppterm ~metasenv ~subst ~context c2));
619             try 
620     (*D*) inside 'K'; try let rc =  
621               let metasenv,subst = 
622                 fo_unif test_eq_only metasenv subst t1 c1 in
623               let metasenv,subst = 
624                 fo_unif test_eq_only metasenv subst c2 t2 in
625               let metasenv,subst = 
626                 List.fold_left 
627                   (fun (metasenv, subst) (x,y) ->
628                      unify rdb test_eq_only metasenv subst context x y)
629                   (metasenv, subst) premises
630               in
631               Some (metasenv, subst)
632      (*D*)  in outside true; rc with exn -> outside false; raise exn 
633             with
634               UnificationFailure _ | Uncertain _ ->
635                 cand_iter tl
636       in
637         cand_iter candidates
638      (*D*)  in outside true; rc with exn -> outside false; raise exn 
639     in
640     let height_of = function
641      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
642      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
643      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
644      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
645      | _ -> 0
646     in
647     let put_in_whd m1 m2 =
648       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
649       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
650     in
651     let small_delta_step ~subst  
652       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
653     =
654      assert (not (norm1 && norm2));
655      if norm1 then
656       x1,NCicReduction.reduce_machine ~delta:(height_of t2 -1) ~subst context m2
657      else if norm2 then
658       NCicReduction.reduce_machine ~delta:(height_of t1 -1) ~subst context m1,x2
659      else 
660       let h1 = height_of t1 in 
661       let h2 = height_of t2 in
662       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
663       NCicReduction.reduce_machine ~delta ~subst context m1,
664       NCicReduction.reduce_machine ~delta ~subst context m2
665     in
666     let rec unif_machines metasenv subst = 
667       function
668       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
669      (*D*) inside 'M'; try let rc = 
670          pp (lazy("UM: " ^
671            NCicPp.ppterm ~metasenv ~subst ~context 
672              (NCicReduction.unwind (k1,e1,t1,s1)) ^
673            " === " ^ 
674            NCicPp.ppterm ~metasenv ~subst ~context 
675              (NCicReduction.unwind (k2,e2,t2,s2))));
676 pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
677           let relevance = [] (* TO BE UNDERSTOOD 
678             match t1 with
679             | C.Const r -> NCicEnvironment.get_relevance r
680             | _ -> [] *) in
681           let unif_from_stack t1 t2 b metasenv subst =
682               try
683                 let t1 = NCicReduction.from_stack ~delta:max_int t1 in
684                 let t2 = NCicReduction.from_stack ~delta:max_int t2 in
685                 unif_machines metasenv subst (put_in_whd t1 t2)
686               with UnificationFailure _ | Uncertain _ when not b ->
687                 metasenv, subst
688           in
689           let rec check_stack l1 l2 r todo =
690             match l1,l2,r with
691             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
692             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
693             | l1, l2, _ -> 
694                NCicReduction.unwind (k1,e1,t1,List.rev l1),
695                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
696                 todo
697           in
698         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
699         try
700          let metasenv,subst = fo_unif test_eq_only metasenv subst hh1 hh2 in
701          List.fold_left
702           (fun (metasenv,subst) (x1,x2,r) ->
703             unif_from_stack x1 x2 r metasenv subst
704           ) (metasenv,subst) todo
705         with UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
706             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
707       (*D*)  in outside true; rc with exn -> outside false; raise exn 
708      in
709      try fo_unif test_eq_only metasenv subst t1 t2
710      with 
711      | UnificationFailure msg as exn ->
712           (try 
713             unif_machines metasenv subst 
714              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
715           with 
716           | UnificationFailure _ -> raise (UnificationFailure msg)
717           | Uncertain _ -> raise exn)
718      | Uncertain msg as exn -> 
719        match try_hints metasenv subst t1 t2 with
720        | Some x -> x
721        | None -> 
722           try 
723             unif_machines metasenv subst 
724              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
725           with 
726           | UnificationFailure _ -> raise (UnificationFailure msg)
727           | Uncertain _ -> raise exn
728  (*D*)  in outside true; rc with exn -> outside false; raise exn 
729
730 and delift_type_wrt_terms rdb metasenv subst context t args =
731   let (metasenv, subst), t =
732    try
733     NCicMetaSubst.delift 
734       ~unify:(fun m s c t1 t2 -> 
735          let ind = !indent in
736          let res = 
737            try Some (unify rdb false m s c t1 t2 )
738            with UnificationFailure _ | Uncertain _ -> None
739          in
740          indent := ind; res)
741       metasenv subst context 0 (0,NCic.Ctx (args @ 
742         List.rev (mk_irl (List.length context)))) t
743    with NCicMetaSubst.MetaSubstFailure _ -> (metasenv, subst), t
744   in
745    metasenv, subst, t
746 ;;
747
748
749 let unify rdb ?(test_eq_only=false) = 
750   indent := "";      
751   unify rdb test_eq_only;;
752
753 let fix_sorts = fix_sorts true (UnificationFailure (lazy "no sup"));;