]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
09b1f3d2e77d923b3345eba41da1aa76a6897062
[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 name, ctx, ty = NCicUtils.lookup_meta n metasenv in
204   let metasenv, subst, t = 
205     match ty with 
206     | NCic.Implicit (`Typeof _) ->
207        (match NCicReduction.whd ~subst context t with
208           NCic.Sort _ -> metasenv,subst,t
209         | NCic.Meta (i,_) when
210            let _,_,ty = NCicUtils.lookup_meta i metasenv in
211             (match ty with
212                 NCic.Implicit (`Typeof _) -> true
213               | _ -> false)
214            -> metasenv,subst,t
215         | NCic.Meta (i,_) ->
216            let rec remove_and_hope i =
217             let _,ctx,ty = NCicUtils.lookup_meta i metasenv in
218             match ty with
219                NCic.Implicit _ -> List.filter (fun i',_ -> i <> i') metasenv
220              | _ ->
221                match NCicReduction.whd ~subst ctx ty with
222                   NCic.Meta (j,_) ->
223                    let metasenv = remove_and_hope j in
224                     List.filter (fun i',_ -> i <> i') metasenv
225                 | _ -> assert false (* NON POSSO RESTRINGERE *)
226            in
227            let metasenv = remove_and_hope i in
228            let metasenv =
229             (i,([],[],NCic.Implicit (`Typeof i)))::
230              List.filter (fun i',_ -> i <> i') metasenv
231            in
232             metasenv,subst,t
233         | NCic.Appl (NCic.Meta _::_) ->
234            raise (Uncertain (lazy "Trying to instantiate a metavariable that represents a sort with a term"))
235         | t when could_reduce t -> 
236            raise (Uncertain (lazy "Trying to instantiate a metavariable that represents a sort with a term"))
237         | _ ->
238            raise (UnificationFailure (lazy "Trying to instantiate a metavariable that represents a sort with a term")))
239     | _ ->
240        pp (lazy (
241                "typeof: " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^
242           ppcontext ~metasenv ~subst context ^ 
243           ppmetasenv ~subst metasenv));
244        let exc_to_be = fail_exc metasenv subst context (NCic.Meta (n,lc)) t in
245        let t, ty_t = 
246          try t, NCicTypeChecker.typeof ~subst ~metasenv context t 
247          with 
248          | NCicTypeChecker.AssertFailure msg -> 
249            (pp (lazy "fine typeof (fallimento)");
250            let ft = fix_sorts swap exc_to_be t in
251            if ft == t then 
252              (prerr_endline ( ("ILLTYPED: " ^ 
253                 NCicPp.ppterm ~metasenv ~subst ~context t
254             ^ "\nBECAUSE:" ^ Lazy.force msg ^ 
255             ppcontext ~metasenv ~subst context ^ 
256             ppmetasenv ~subst metasenv
257             ));
258                      assert false)
259            else
260             try 
261               pp (lazy ("typeof: " ^ 
262                 NCicPp.ppterm ~metasenv ~subst ~context ft));
263               ft, NCicTypeChecker.typeof ~subst ~metasenv context ft 
264             with NCicTypeChecker.AssertFailure _ -> 
265               assert false)
266          | NCicTypeChecker.TypeCheckerFailure msg ->
267               prerr_endline (Lazy.force msg);
268        prerr_endline (
269                "typeof: " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^
270           ppcontext ~metasenv ~subst context ^ 
271           ppmetasenv ~subst metasenv);
272               pp msg; assert false
273        in
274        let lty = NCicSubstitution.subst_meta lc ty in
275        match ty_t with
276        | NCic.Implicit _ -> 
277            raise (UnificationFailure 
278              (lazy "trying to unify a term with a type"))
279        | ty_t -> 
280           pp (lazy ("On the types: " ^
281            NCicPp.ppterm ~metasenv ~subst ~context:ctx ty ^ " ~~~ " ^
282            NCicPp.ppterm ~metasenv ~subst ~context lty ^ " === "
283             ^ NCicPp.ppterm ~metasenv ~subst ~context ty_t)); 
284           let metasenv,subst = 
285            try
286             unify test_eq_only metasenv subst context lty ty_t
287            with NCicEnvironment.BadConstraint _ as exc ->
288             let ty_t = fix_sorts swap exc_to_be ty_t in 
289              try unify test_eq_only metasenv subst context lty ty_t
290              with _ -> raise exc in
291           metasenv, subst, t
292   in
293          pp (lazy(string_of_int n ^ " := 111 = "^
294            NCicPp.ppterm ~metasenv ~subst ~context t));
295   let (metasenv, subst), t = 
296     try 
297       NCicMetaSubst.delift 
298        ~unify:(fun m s c t1 t2 -> 
299          let ind = !indent in
300          let res = 
301            try Some (unify test_eq_only m s c t1 t2 )
302            with UnificationFailure _ | Uncertain _ -> None
303          in
304          indent := ind; res) 
305        metasenv subst context n lc t
306     with NCicMetaSubst.Uncertain msg -> 
307          pp (lazy ("delift fails: " ^ Lazy.force msg));
308          raise (Uncertain msg)
309     | NCicMetaSubst.MetaSubstFailure msg -> 
310          pp (lazy ("delift fails: " ^ Lazy.force msg));
311          raise (UnificationFailure msg)
312   in
313          pp (lazy(string_of_int n ^ " := 222 = "^
314            NCicPp.ppterm ~metasenv ~subst ~context:ctx t
315          ^ ppmetasenv ~subst metasenv));
316   (* Unifying the types may have already instantiated n. *)
317   try
318     let _, _,oldt,_ = NCicUtils.lookup_subst n subst in
319     let oldt = NCicSubstitution.subst_meta lc oldt in
320     let t = NCicSubstitution.subst_meta lc t in
321     (* conjecture: always fail --> occur check *)
322     unify test_eq_only metasenv subst context oldt t
323   with NCicUtils.Subst_not_found _ -> 
324     (* by cumulativity when unify(?,Type_i) 
325      * we could ? := Type_j with j <= i... *)
326     let subst = (n, (name, ctx, t, ty)) :: subst in
327     pp (lazy ("?"^string_of_int n^" := "^NCicPp.ppterm
328       ~metasenv ~subst ~context (NCicSubstitution.subst_meta lc t)));
329     let metasenv = 
330       List.filter (fun (m,_) -> not (n = m)) metasenv 
331     in
332     metasenv, subst
333  (*D*)  in outside true; rc with exn -> outside false; raise exn 
334
335 and unify rdb test_eq_only metasenv subst context t1 t2 =
336  (*D*) inside 'U'; try let rc =
337    let fo_unif test_eq_only metasenv subst t1 t2 =
338     (*D*) inside 'F'; try let rc =  
339      pp (lazy("  " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
340          NCicPp.ppterm ~metasenv ~subst ~context t2 ^ ppmetasenv
341          ~subst metasenv));
342      if t1 === t2 then
343        metasenv, subst
344      else
345        match (t1,t2) with
346        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
347        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
348            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
349            assert false 
350        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
351            if NCicEnvironment.universe_leq a b then metasenv, subst
352            else raise (fail_exc metasenv subst context t1 t2)
353        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
354            if NCicEnvironment.universe_eq a b then metasenv, subst
355            else raise (fail_exc metasenv subst context t1 t2)
356        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
357            if (not test_eq_only) then metasenv, subst
358            else raise (fail_exc metasenv subst context t1 t2)
359
360        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
361        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
362            let metasenv, subst = unify rdb true metasenv subst context s1 s2 in
363            unify rdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
364        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
365            let metasenv,subst=unify rdb test_eq_only metasenv subst context ty1 ty2 in
366            let metasenv,subst=unify rdb test_eq_only metasenv subst context s1 s2 in
367            let context = (name1, C.Def (s1,ty1))::context in
368            unify rdb test_eq_only metasenv subst context t1 t2
369
370        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
371           (try 
372            let l1 = NCicUtils.expand_local_context l1 in
373            let l2 = NCicUtils.expand_local_context l2 in
374            let metasenv, subst, to_restrict, _ =
375             List.fold_right2 
376              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
377                 try 
378                   let metasenv, subst = 
379                    unify rdb test_eq_only metasenv subst context 
380                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
381                   in
382                   metasenv, subst, to_restrict, i-1  
383                 with UnificationFailure _ | Uncertain _ ->
384                   metasenv, subst, i::to_restrict, i-1)
385              l1 l2 (metasenv, subst, [], List.length l1)
386            in
387            if to_restrict <> [] then
388              let metasenv, subst, _ = 
389                NCicMetaSubst.restrict metasenv subst n1 to_restrict
390              in
391                metasenv, subst
392            else metasenv, subst
393           with 
394            | Invalid_argument _ -> assert false
395            | NCicMetaSubst.MetaSubstFailure msg ->
396               try 
397                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
398                 let term1 = NCicSubstitution.subst_meta lc1 term in
399                 let term2 = NCicSubstitution.subst_meta lc2 term in
400                   unify rdb test_eq_only metasenv subst context term1 term2
401               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
402        
403        | _, NCic.Meta (n, _) when is_locked n subst ->
404            (let (metasenv, subst), i = 
405               match NCicReduction.whd ~subst context t1 with
406               | NCic.Appl (NCic.Meta (i,l)::args) ->
407                  let metasenv, subst, lambda_Mj =
408                    lambda_intros rdb metasenv subst context t1 args
409                  in
410                    unify rdb test_eq_only metasenv subst context 
411                     (C.Meta (i,l)) lambda_Mj,
412                    i
413               | NCic.Meta (i,_) -> (metasenv, subst), i
414               | _ ->
415                  raise (UnificationFailure (lazy "Locked term vs non
416                   flexible term; probably not saturated enough yet!"))
417              in
418               let t1 = NCicReduction.whd ~subst context t1 in
419               let j, lj = 
420                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
421               in
422               let metasenv, subst = 
423                 instantiate rdb test_eq_only metasenv subst context j lj t2 true
424               in
425               (* We need to remove the out_scope_tags to avoid propagation of
426                  them that triggers again the ad-hoc case *)
427               let subst =
428                List.map (fun (i,(tag,ctx,bo,ty)) ->
429                 let tag =
430                  List.filter
431                   (function `InScope | `OutScope _ -> false | _ -> true) tag
432                 in
433                   i,(tag,ctx,bo,ty)
434                 ) subst
435               in
436               (try
437                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
438                 let term = eta_reduce subst term in
439                 let subst = List.filter (fun (j,_) -> j <> i) subst in
440                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
441               with Not_found -> assert false))
442
443        | C.Meta (n,lc), t -> 
444            (try 
445              let _,_,term,_ = NCicUtils.lookup_subst n subst in
446              let term = NCicSubstitution.subst_meta lc term in
447                unify rdb test_eq_only metasenv subst context term t
448            with NCicUtils.Subst_not_found _-> 
449              instantiate rdb test_eq_only metasenv subst context n lc 
450                (NCicReduction.head_beta_reduce ~subst t) false)
451
452        | t, C.Meta (n,lc) -> 
453            (try 
454              let _,_,term,_ = NCicUtils.lookup_subst n subst in
455              let term = NCicSubstitution.subst_meta lc term in
456                unify rdb test_eq_only metasenv subst context t term
457            with NCicUtils.Subst_not_found _-> 
458              instantiate rdb test_eq_only metasenv subst context n lc 
459               (NCicReduction.head_beta_reduce ~subst t) true)
460
461        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
462             let _,_,term,_ = NCicUtils.lookup_subst i subst in
463             let term = NCicSubstitution.subst_meta l term in
464               unify rdb test_eq_only metasenv subst context 
465                 (mk_appl ~upto:(List.length args) term args) t2
466
467        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
468             let _,_,term,_ = NCicUtils.lookup_subst i subst in
469             let term = NCicSubstitution.subst_meta l term in
470               unify rdb test_eq_only metasenv subst context t1 
471                 (mk_appl ~upto:(List.length args) term args)
472
473        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
474           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
475             (try
476               List.fold_left2 
477                 (fun (metasenv, subst) t1 t2 ->
478                   unify rdb test_eq_only metasenv subst context t1 t2)
479                 (metasenv,subst) l1 l2
480             with Invalid_argument _ -> 
481               raise (fail_exc metasenv subst context t1 t2))
482
483        | NCic.Appl (NCic.Meta (i,l)::args), _ ->
484           let metasenv, subst, lambda_Mj =
485             lambda_intros rdb metasenv subst context t1 args
486           in
487           let metasenv, subst = 
488             unify rdb test_eq_only metasenv subst context 
489               (C.Meta (i,l)) lambda_Mj
490           in
491           let metasenv, subst = 
492             unify rdb test_eq_only metasenv subst context t1 t2 
493           in
494           (try
495             let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
496             let term = eta_reduce subst term in
497             let subst = List.filter (fun (j,_) -> j <> i) subst in
498             metasenv, ((i, (name, ctx, term, ty)) :: subst)
499           with Not_found -> assert false)
500
501        | _, NCic.Appl (NCic.Meta (i,l)::args) ->
502          let metasenv, subst, lambda_Mj =
503            lambda_intros rdb metasenv subst context t2 args
504          in
505          let metasenv, subst =
506            unify rdb test_eq_only metasenv subst context 
507             lambda_Mj (C.Meta (i,l))
508          in
509          let metasenv, subst = 
510            unify rdb test_eq_only metasenv subst context t1 t2 
511          in
512          (try
513            let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
514            let term = eta_reduce subst term in
515            let subst = List.filter (fun (j,_) -> j <> i) subst in
516            metasenv, ((i, (name, ctx, term, ty)) :: subst)
517          with Not_found -> assert false)
518
519        (* processing this case here we avoid a useless small delta step *)
520        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
521          when Ref.eq r1 r2 ->
522            let relevance = NCicEnvironment.get_relevance r1 in
523            let relevance = match r1 with
524              | Ref.Ref (_,Ref.Con (_,_,lno)) ->
525                  let relevance =
526                   try snd (HExtlib.split_nth lno relevance)
527                   with Failure _ -> []
528                  in
529                    HExtlib.mk_list false lno @ relevance
530              | _ -> relevance
531            in
532            let metasenv, subst, _ = 
533              try
534                List.fold_left2 
535                  (fun (metasenv, subst, relevance) t1 t2 ->
536                     let b, relevance = 
537                       match relevance with b::tl -> b,tl | _ -> true, [] in
538                     let metasenv, subst = 
539                       try unify rdb test_eq_only metasenv subst context t1 t2
540                       with UnificationFailure _ | Uncertain _ when not b ->
541                         metasenv, subst
542                     in
543                       metasenv, subst, relevance)
544                  (metasenv, subst, relevance) tl1 tl2
545              with Invalid_argument _ -> 
546                raise (uncert_exc metasenv subst context t1 t2)
547            in 
548              metasenv, subst
549
550        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
551           C.Match (ref2,outtype2,term2,pl2)) ->
552            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
553            let _,_,ty,_ = List.nth itl tyno in
554            let rec remove_prods ~subst context ty = 
555              let ty = NCicReduction.whd ~subst context ty in
556              match ty with
557              | C.Sort _ -> ty
558              | C.Prod (name,so,ta) -> 
559                    remove_prods ~subst ((name,(C.Decl so))::context) ta
560              | _ -> assert false
561            in
562            let is_prop = 
563              match remove_prods ~subst [] ty with
564              | C.Sort C.Prop -> true
565              | _ -> false 
566            in
567            if not (Ref.eq ref1 ref2) then 
568              raise (uncert_exc metasenv subst context t1 t2) 
569            else
570              let metasenv, subst = 
571               unify rdb test_eq_only metasenv subst context outtype1 outtype2 in
572              let metasenv, subst = 
573                try unify rdb test_eq_only metasenv subst context term1 term2 
574                with UnificationFailure _ | Uncertain _ when is_prop -> 
575                  metasenv, subst
576              in
577              (try
578               List.fold_left2 
579                (fun (metasenv,subst) -> 
580                   unify rdb test_eq_only metasenv subst context)
581                (metasenv, subst) pl1 pl2
582              with Invalid_argument _ -> assert false)
583        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
584        | _ when NCicUntrusted.metas_of_term subst context t1 = [] && 
585                 NCicUntrusted.metas_of_term subst context t2 = [] -> 
586                   raise (fail_exc metasenv subst context t1 t2)
587        | _ -> raise (uncert_exc metasenv subst context t1 t2)
588      (*D*)  in outside true; rc with exn -> outside false; raise exn 
589     in
590     let try_hints metasenv subst t1 t2 (* exc*) =
591     (*D*) inside 'H'; try let rc =  
592 (*
593       prerr_endline ("\nProblema:\n" ^
594         NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
595         NCicPp.ppterm ~metasenv ~subst ~context t2);
596 *)
597       let candidates = 
598         NCicUnifHint.look_for_hint rdb metasenv subst context t1 t2
599       in
600       let rec cand_iter = function
601         | [] -> None (* raise exc *)
602         | (metasenv,(c1,c2),premises)::tl -> 
603             pp (lazy ("\nProvo il candidato:\n" ^ 
604               String.concat "\n"
605                 (List.map 
606                   (fun (a,b) ->
607                    NCicPp.ppterm ~metasenv ~subst ~context a ^  " =?= " ^
608                    NCicPp.ppterm ~metasenv ~subst ~context b) premises) ^
609               "\n-------------------------------------------\n"^
610               NCicPp.ppterm ~metasenv ~subst ~context c1 ^  " = " ^
611               NCicPp.ppterm ~metasenv ~subst ~context c2));
612             try 
613     (*D*) inside 'K'; try let rc =  
614               let metasenv,subst = 
615                 fo_unif test_eq_only metasenv subst t1 c1 in
616               let metasenv,subst = 
617                 fo_unif test_eq_only metasenv subst c2 t2 in
618               let metasenv,subst = 
619                 List.fold_left 
620                   (fun (metasenv, subst) (x,y) ->
621                      unify rdb test_eq_only metasenv subst context x y)
622                   (metasenv, subst) premises
623               in
624               Some (metasenv, subst)
625      (*D*)  in outside true; rc with exn -> outside false; raise exn 
626             with
627               UnificationFailure _ | Uncertain _ ->
628                 cand_iter tl
629       in
630         cand_iter candidates
631      (*D*)  in outside true; rc with exn -> outside false; raise exn 
632     in
633     let height_of = function
634      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
635      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
636      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
637      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
638      | _ -> 0
639     in
640     let put_in_whd m1 m2 =
641       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
642       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
643     in
644     let small_delta_step ~subst  
645       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
646     =
647      assert (not (norm1 && norm2));
648      if norm1 then
649       x1,NCicReduction.reduce_machine ~delta:(height_of t2 -1) ~subst context m2
650      else if norm2 then
651       NCicReduction.reduce_machine ~delta:(height_of t1 -1) ~subst context m1,x2
652      else 
653       let h1 = height_of t1 in 
654       let h2 = height_of t2 in
655       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
656       NCicReduction.reduce_machine ~delta ~subst context m1,
657       NCicReduction.reduce_machine ~delta ~subst context m2
658     in
659     let rec unif_machines metasenv subst = 
660       function
661       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
662      (*D*) inside 'M'; try let rc = 
663          pp (lazy("UM: " ^
664            NCicPp.ppterm ~metasenv ~subst ~context 
665              (NCicReduction.unwind (k1,e1,t1,s1)) ^
666            " === " ^ 
667            NCicPp.ppterm ~metasenv ~subst ~context 
668              (NCicReduction.unwind (k2,e2,t2,s2))));
669 pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
670           let relevance = [] (* TO BE UNDERSTOOD 
671             match t1 with
672             | C.Const r -> NCicEnvironment.get_relevance r
673             | _ -> [] *) in
674           let unif_from_stack t1 t2 b metasenv subst =
675               try
676                 let t1 = NCicReduction.from_stack ~delta:max_int t1 in
677                 let t2 = NCicReduction.from_stack ~delta:max_int t2 in
678                 unif_machines metasenv subst (put_in_whd t1 t2)
679               with UnificationFailure _ | Uncertain _ when not b ->
680                 metasenv, subst
681           in
682           let rec check_stack l1 l2 r todo =
683             match l1,l2,r with
684             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
685             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
686             | l1, l2, _ -> 
687                NCicReduction.unwind (k1,e1,t1,List.rev l1),
688                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
689                 todo
690           in
691         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
692         try
693          let metasenv,subst = fo_unif test_eq_only metasenv subst hh1 hh2 in
694          List.fold_left
695           (fun (metasenv,subst) (x1,x2,r) ->
696             unif_from_stack x1 x2 r metasenv subst
697           ) (metasenv,subst) todo
698         with UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
699             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
700       (*D*)  in outside true; rc with exn -> outside false; raise exn 
701      in
702      try fo_unif test_eq_only metasenv subst t1 t2
703      with 
704      | UnificationFailure msg as exn ->
705           (try 
706             unif_machines metasenv subst 
707              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
708           with 
709           | UnificationFailure _ -> raise (UnificationFailure msg)
710           | Uncertain _ -> raise exn)
711      | Uncertain msg as exn -> 
712        match try_hints metasenv subst t1 t2 with
713        | Some x -> x
714        | None -> 
715           try 
716             unif_machines metasenv subst 
717              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
718           with 
719           | UnificationFailure _ -> raise (UnificationFailure msg)
720           | Uncertain _ -> raise exn
721  (*D*)  in outside true; rc with exn -> outside false; raise exn 
722
723 and delift_type_wrt_terms rdb metasenv subst context t args =
724   let (metasenv, subst), t =
725    try
726     NCicMetaSubst.delift 
727       ~unify:(fun m s c t1 t2 -> 
728          let ind = !indent in
729          let res = 
730            try Some (unify rdb false m s c t1 t2 )
731            with UnificationFailure _ | Uncertain _ -> None
732          in
733          indent := ind; res)
734       metasenv subst context 0 (0,NCic.Ctx (args @ 
735         List.rev (mk_irl (List.length context)))) t
736    with NCicMetaSubst.MetaSubstFailure _ -> (metasenv, subst), t
737   in
738    metasenv, subst, t
739 ;;
740
741
742 let unify rdb ?(test_eq_only=false) = 
743   indent := "";      
744   unify rdb test_eq_only;;
745
746 let fix_sorts = fix_sorts true (UnificationFailure (lazy "no sup"));;