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