]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
09d9ede475cd12bc1a88e34fbf5be307527f1024
[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 "NU 1" (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 indent = ref "";;
82 let inside c = indent := !indent ^ String.make 1 c;;
83 let outside () = indent := String.sub !indent 0 (String.length !indent -1);;
84
85 let pp s = 
86   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
87 ;;  
88
89 let pp _ = ();;
90
91 let fix_sorts swap metasenv subst context meta t =
92   let rec aux () = function
93     | NCic.Sort (NCic.Type u) as orig ->
94         if swap then
95          match NCicEnvironment.sup u with
96          | None -> prerr_endline "no sup for" ;
97             raise (fail_exc metasenv subst context meta t)
98          | Some u1 -> if u = u1 then orig else NCic.Sort (NCic.Type u1)
99         else
100          NCic.Sort (NCic.Type (
101            match NCicEnvironment.sup NCicEnvironment.type0 with 
102            | Some x -> x
103            | _ -> assert false))
104     | NCic.Meta _ as orig -> orig
105     | t -> NCicUtils.map (fun _ _ -> ()) () aux t
106   in
107     aux () t
108 ;;
109
110 let is_locked n subst =
111    try
112      match NCicUtils.lookup_subst n subst with
113      | Some tag, _,_,_ when NCicMetaSubst.is_out_scope_tag tag -> true
114      | _ -> false
115    with NCicUtils.Subst_not_found _ -> false
116 ;;
117
118
119 let rec lambda_intros metasenv subst context t args =
120  let tty = NCicTypeChecker.typeof ~metasenv ~subst context t in
121  let argsty = List.map (NCicTypeChecker.typeof ~metasenv ~subst context) args in
122  let rec mk_lambda context n = function
123    | [] -> 
124        let metasenv, _, bo, _ = 
125          NCicMetaSubst.mk_meta metasenv context 
126            (`WithType (NCicSubstitution.lift n tty))
127        in
128        metasenv, bo
129    | ty::tail -> 
130        let name = "HBeta"^string_of_int n in
131        let ty = NCicSubstitution.lift n ty in
132        let metasenv, bo = mk_lambda ((name,NCic.Decl ty)::context) (n+1) tail in
133        metasenv, NCic.Lambda (name, ty, bo)
134  in
135    mk_lambda context 0 argsty
136
137 and instantiate hdb test_eq_only metasenv subst context n lc t swap =
138  (*D*)  inside 'I'; try let rc =  
139          pp (lazy(string_of_int n ^ " :=?= "^
140            NCicPp.ppterm ~metasenv ~subst ~context t));
141   let unify test_eq_only m s c t1 t2 = 
142     if swap then unify hdb test_eq_only m s c t2 t1 
143     else unify hdb test_eq_only m s c t1 t2
144   in
145   let name, ctx, ty = NCicUtils.lookup_meta n metasenv in
146   let metasenv, subst, t = 
147     match ty with 
148     | NCic.Implicit (`Typeof _) -> 
149        metasenv,subst, t
150          (* fix_sorts swap metasenv subst context (NCic.Meta(n,lc)) t *)
151     | _ ->
152        pp (lazy (
153          "typeof: " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^ "\nctx:\n"^
154           NCicPp.ppcontext ~metasenv ~subst context ^ "\nmenv:\n"^
155           NCicPp.ppmetasenv ~subst metasenv));
156        let t, ty_t = 
157          try t, NCicTypeChecker.typeof ~subst ~metasenv context t 
158          with 
159          | NCicTypeChecker.AssertFailure msg -> 
160            (pp (lazy "fine typeof (fallimento)");
161            let ft=fix_sorts swap metasenv subst context (NCic.Meta (n,lc)) t in
162            if ft == t then 
163              (prerr_endline ( ("ILLTYPED: " ^ 
164                 NCicPp.ppterm ~metasenv ~subst ~context t
165             ^ "\nBECAUSE:" ^ Lazy.force msg ^ "\nCONTEXT:\n" ^
166             NCicPp.ppcontext ~metasenv ~subst context ^ "\nMENV:\n" ^
167             NCicPp.ppmetasenv ~subst metasenv
168             ));
169                      assert false)
170            else
171             try 
172               pp (lazy ("typeof: " ^ 
173                 NCicPp.ppterm ~metasenv ~subst ~context ft));
174               ft, NCicTypeChecker.typeof ~subst ~metasenv context ft 
175             with NCicTypeChecker.AssertFailure _ -> 
176               assert false)
177          | NCicTypeChecker.TypeCheckerFailure msg ->
178               prerr_endline (Lazy.force msg);
179               pp msg; assert false
180        in
181        let lty = NCicSubstitution.subst_meta lc ty in
182        match ty_t with
183        | NCic.Implicit _ -> 
184            raise (UnificationFailure 
185              (lazy "trying to unify a term with a type"))
186        | ty_t -> 
187           pp (lazy ("On the types: " ^
188            NCicPp.ppterm ~metasenv ~subst ~context:ctx ty ^ " ~~~ " ^
189            NCicPp.ppterm ~metasenv ~subst ~context lty ^ " === "
190             ^ NCicPp.ppterm ~metasenv ~subst ~context ty_t)); 
191           let metasenv,subst = 
192             unify test_eq_only metasenv subst context lty ty_t in
193           metasenv, subst, t
194   in
195          pp (lazy(string_of_int n ^ " := 111 = "^
196            NCicPp.ppterm ~metasenv ~subst ~context t));
197   let (metasenv, subst), t = 
198     try 
199       NCicMetaSubst.delift 
200        ~unify:(fun m s c t1 t2 -> 
201          let ind = !indent in
202          let res = 
203            try Some (unify test_eq_only m s c t1 t2 )
204            with UnificationFailure _ | Uncertain _ -> None
205          in
206          indent := ind; res) 
207        metasenv subst context n lc t
208     with NCicMetaSubst.Uncertain msg -> 
209          pp (lazy ("delift fails: " ^ Lazy.force msg));
210          raise (Uncertain msg)
211     | NCicMetaSubst.MetaSubstFailure msg -> 
212          pp (lazy ("delift fails: " ^ Lazy.force msg));
213          raise (UnificationFailure msg)
214   in
215          pp (lazy(string_of_int n ^ " := 222 = "^
216            NCicPp.ppterm ~metasenv ~subst ~context:ctx t
217          ^ "\n" ^ NCicPp.ppmetasenv ~subst metasenv));
218   (* Unifying the types may have already instantiated n. *)
219   try
220     let _, _,oldt,_ = NCicUtils.lookup_subst n subst in
221     let oldt = NCicSubstitution.subst_meta lc oldt in
222     let t = NCicSubstitution.subst_meta lc t in
223     (* conjecture: always fail --> occur check *)
224     unify test_eq_only metasenv subst context oldt t
225   with NCicUtils.Subst_not_found _ -> 
226     (* by cumulativity when unify(?,Type_i) 
227      * we could ? := Type_j with j <= i... *)
228     let subst = (n, (name, ctx, t, ty)) :: subst in
229     pp (lazy ("?"^string_of_int n^" := "^NCicPp.ppterm
230       ~metasenv ~subst ~context (NCicSubstitution.subst_meta lc t)));
231     let metasenv = 
232       List.filter (fun (m,_) -> not (n = m)) metasenv 
233     in
234     metasenv, subst
235  (*D*)  in outside(); rc with exn -> outside (); raise exn 
236
237 and unify hdb test_eq_only metasenv subst context t1 t2 =
238  (*D*) inside 'U'; try let rc =
239    let fo_unif test_eq_only metasenv subst t1 t2 =
240     (*D*) inside 'F'; try let rc =  
241      pp (lazy("  " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
242          NCicPp.ppterm ~metasenv ~subst ~context t2 ^ "\n" ^ NCicPp.ppmetasenv
243          ~subst metasenv));
244      if t1 === t2 then
245        metasenv, subst
246      else
247        match (t1,t2) with
248        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
249        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
250            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
251            assert false 
252        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
253            if NCicEnvironment.universe_leq a b then metasenv, subst
254            else raise (fail_exc metasenv subst context t1 t2)
255        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
256            if NCicEnvironment.universe_eq a b then metasenv, subst
257            else raise (fail_exc metasenv subst context t1 t2)
258        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
259            if (not test_eq_only) then metasenv, subst
260            else raise (fail_exc metasenv subst context t1 t2)
261
262        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
263        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
264            let metasenv, subst = unify hdb true metasenv subst context s1 s2 in
265            unify hdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
266        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
267            let metasenv,subst=unify hdb test_eq_only metasenv subst context ty1 ty2 in
268            let metasenv,subst=unify hdb test_eq_only metasenv subst context s1 s2 in
269            let context = (name1, C.Def (s1,ty1))::context in
270            unify hdb test_eq_only metasenv subst context t1 t2
271
272        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
273           (try 
274            let l1 = NCicUtils.expand_local_context l1 in
275            let l2 = NCicUtils.expand_local_context l2 in
276            let metasenv, subst, to_restrict, _ =
277             List.fold_right2 
278              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
279                 try 
280                   let metasenv, subst = 
281                    unify hdb test_eq_only metasenv subst context 
282                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
283                   in
284                   metasenv, subst, to_restrict, i-1  
285                 with UnificationFailure _ | Uncertain _ ->
286                   metasenv, subst, i::to_restrict, i-1)
287              l1 l2 (metasenv, subst, [], List.length l1)
288            in
289            if to_restrict <> [] then
290              let metasenv, subst, _ = 
291                NCicMetaSubst.restrict metasenv subst n1 to_restrict
292              in
293                metasenv, subst
294            else metasenv, subst
295           with 
296            | Invalid_argument _ -> assert false
297            | NCicMetaSubst.MetaSubstFailure msg ->
298               try 
299                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
300                 let term1 = NCicSubstitution.subst_meta lc1 term in
301                 let term2 = NCicSubstitution.subst_meta lc2 term in
302                   unify hdb test_eq_only metasenv subst context term1 term2
303               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
304        
305        | _, NCic.Meta (n, _) when is_locked n subst ->
306            (let (metasenv, subst), i = 
307               match NCicReduction.whd ~subst context t1 with
308               | NCic.Appl (NCic.Meta (i,l)::args) when
309                   not (NCicMetaSubst.flexible subst args) 
310                 ->
311                  let metasenv, lambda_Mj =
312                    lambda_intros metasenv subst context t1 args
313                  in
314                    unify hdb test_eq_only metasenv subst context 
315                     (C.Meta (i,l)) lambda_Mj,
316                    i
317               | NCic.Meta (i,_) -> (metasenv, subst), i
318               | _ -> assert false
319              in
320               let t1 = NCicReduction.whd ~subst context t1 in
321               let j, lj = 
322                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
323               in
324               let metasenv, subst = 
325                 instantiate hdb test_eq_only metasenv subst context j lj t2 true
326               in
327               (try
328                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
329                 let term = eta_reduce subst term in
330                 let subst = List.filter (fun (j,_) -> j <> i) subst in
331                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
332               with Not_found -> assert false))
333
334        | C.Meta (n,lc), t -> 
335            (try 
336              let _,_,term,_ = NCicUtils.lookup_subst n subst in
337              let term = NCicSubstitution.subst_meta lc term in
338                unify hdb test_eq_only metasenv subst context term t
339            with NCicUtils.Subst_not_found _-> 
340              instantiate hdb test_eq_only metasenv subst context n lc 
341                (NCicReduction.head_beta_reduce ~subst t) false)
342
343        | t, C.Meta (n,lc) -> 
344            (try 
345              let _,_,term,_ = NCicUtils.lookup_subst n subst in
346              let term = NCicSubstitution.subst_meta lc term in
347                unify hdb test_eq_only metasenv subst context t term
348            with NCicUtils.Subst_not_found _-> 
349              instantiate hdb test_eq_only metasenv subst context n lc 
350               (NCicReduction.head_beta_reduce ~subst t) true)
351
352        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
353             let _,_,term,_ = NCicUtils.lookup_subst i subst in
354             let term = NCicSubstitution.subst_meta l term in
355               unify hdb test_eq_only metasenv subst context 
356                 (mk_appl ~upto:(List.length args) term args) t2
357
358        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
359             let _,_,term,_ = NCicUtils.lookup_subst i subst in
360             let term = NCicSubstitution.subst_meta l term in
361               unify hdb test_eq_only metasenv subst context t1 
362                 (mk_appl ~upto:(List.length args) term args)
363
364        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
365           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
366             (try
367               List.fold_left2 
368                 (fun (metasenv, subst) t1 t2 ->
369                   unify hdb test_eq_only metasenv subst context t1 t2)
370                 (metasenv,subst) l1 l2
371             with Invalid_argument _ -> 
372               raise (fail_exc metasenv subst context t1 t2))
373
374        | NCic.Appl (NCic.Meta (i,l)::args), _ when 
375          not (NCicMetaSubst.flexible subst args) ->
376            (* we verify that none of the args is a Meta, 
377               since beta expanding w.r.t a metavariable makes no sense  *)
378               let metasenv, lambda_Mj =
379                 lambda_intros metasenv subst context t1 args
380               in
381               let metasenv, subst = 
382                 unify hdb test_eq_only metasenv subst context 
383                   (C.Meta (i,l)) lambda_Mj
384               in
385               let metasenv, subst = 
386                 unify hdb test_eq_only metasenv subst context t1 t2 
387               in
388               (try
389                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
390                 let term = eta_reduce subst term in
391                 let subst = List.filter (fun (j,_) -> j <> i) subst in
392                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
393               with Not_found -> assert false)
394
395        | _, NCic.Appl (NCic.Meta (i,l)::args) when 
396          not(NCicMetaSubst.flexible subst args) ->
397               let metasenv, lambda_Mj =
398                 lambda_intros metasenv subst context t2 args
399               in
400               let metasenv, subst =
401                 unify hdb test_eq_only metasenv subst context 
402                  lambda_Mj (C.Meta (i,l))
403               in
404               let metasenv, subst = 
405                 unify hdb test_eq_only metasenv subst context t1 t2 
406               in
407               (try
408                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
409                 let term = eta_reduce subst term in
410                 let subst = List.filter (fun (j,_) -> j <> i) subst in
411                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
412               with Not_found -> assert false)
413
414        (* processing this case here we avoid a useless small delta step *)
415        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
416          when Ref.eq r1 r2 ->
417            let relevance = NCicEnvironment.get_relevance r1 in
418            let relevance = match r1 with
419              | Ref.Ref (_,Ref.Con (_,_,lno)) ->
420                  let relevance =
421                   try snd (HExtlib.split_nth "NU 2" lno relevance)
422                   with Failure _ -> []
423                  in
424                    HExtlib.mk_list false lno @ relevance
425              | _ -> relevance
426            in
427            let metasenv, subst, _ = 
428              try
429                List.fold_left2 
430                  (fun (metasenv, subst, relevance) t1 t2 ->
431                     let b, relevance = 
432                       match relevance with b::tl -> b,tl | _ -> true, [] in
433                     let metasenv, subst = 
434                       try unify hdb test_eq_only metasenv subst context t1 t2
435                       with UnificationFailure _ | Uncertain _ when not b ->
436                         metasenv, subst
437                     in
438                       metasenv, subst, relevance)
439                  (metasenv, subst, relevance) tl1 tl2
440              with Invalid_argument _ -> 
441                raise (uncert_exc metasenv subst context t1 t2)
442            in 
443              metasenv, subst
444
445        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
446           C.Match (ref2,outtype2,term2,pl2)) ->
447            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
448            let _,_,ty,_ = List.nth itl tyno in
449            let rec remove_prods ~subst context ty = 
450              let ty = NCicReduction.whd ~subst context ty in
451              match ty with
452              | C.Sort _ -> ty
453              | C.Prod (name,so,ta) -> 
454                    remove_prods ~subst ((name,(C.Decl so))::context) ta
455              | _ -> assert false
456            in
457            let is_prop = 
458              match remove_prods ~subst [] ty with
459              | C.Sort C.Prop -> true
460              | _ -> false 
461            in
462            if not (Ref.eq ref1 ref2) then 
463              raise (uncert_exc metasenv subst context t1 t2) 
464            else
465              let metasenv, subst = 
466               unify hdb test_eq_only metasenv subst context outtype1 outtype2 in
467              let metasenv, subst = 
468                try unify hdb test_eq_only metasenv subst context term1 term2 
469                with UnificationFailure _ | Uncertain _ when is_prop -> 
470                  metasenv, subst
471              in
472              (try
473               List.fold_left2 
474                (fun (metasenv,subst) -> 
475                   unify hdb test_eq_only metasenv subst context)
476                (metasenv, subst) pl1 pl2
477              with Invalid_argument _ -> 
478                raise (uncert_exc metasenv subst context t1 t2))
479        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
480        | _ when NCicUntrusted.metas_of_term subst context t1 = [] && 
481                 NCicUntrusted.metas_of_term subst context t2 = [] -> 
482                   raise (fail_exc metasenv subst context t1 t2)
483        | _ -> raise (uncert_exc metasenv subst context t1 t2)
484      (*D*)  in outside(); rc with exn -> outside (); raise exn 
485     in
486     let try_hints metasenv subst t1 t2 (* exc*) =
487 (*
488       prerr_endline ("\nProblema:\n" ^
489         NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
490         NCicPp.ppterm ~metasenv ~subst ~context t2);
491 *)
492       let candidates = 
493         NCicUnifHint.look_for_hint hdb metasenv subst context t1 t2
494       in
495       let rec cand_iter = function
496         | [] -> None (* raise exc *)
497         | (metasenv,(c1,c2),premises)::tl -> 
498 (*
499             prerr_endline ("\nProvo il candidato:\n" ^ 
500               String.concat "\n"
501                 (List.map 
502                   (fun (a,b) ->
503                    NCicPp.ppterm ~metasenv ~subst ~context a ^  " =?= " ^
504                    NCicPp.ppterm ~metasenv ~subst ~context b) premises) ^
505               "\n-------------------------------------------\n"^
506               NCicPp.ppterm ~metasenv ~subst ~context c1 ^  " = " ^
507               NCicPp.ppterm ~metasenv ~subst ~context c2);
508 *)
509             try 
510               let metasenv,subst = 
511                 fo_unif test_eq_only metasenv subst t1 c1 in
512               let metasenv,subst = 
513                 fo_unif test_eq_only metasenv subst c2 t2 in
514               let metasenv,subst = 
515                 List.fold_left 
516                   (fun (metasenv, subst) (x,y) ->
517                      unify hdb test_eq_only metasenv subst context x y)
518                   (metasenv, subst) premises
519               in
520               Some (metasenv, subst)
521             with
522               UnificationFailure _ | Uncertain _ ->
523                 cand_iter tl
524       in
525         cand_iter candidates
526     in
527     let height_of = function
528      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
529      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
530      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
531      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
532      | _ -> 0
533     in
534     let put_in_whd m1 m2 =
535       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
536       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
537     in
538     let small_delta_step ~subst  
539       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
540     =
541      assert (not (norm1 && norm2));
542      if norm1 then
543       x1,NCicReduction.reduce_machine ~delta:(height_of t2 -1) ~subst context m2
544      else if norm2 then
545       NCicReduction.reduce_machine ~delta:(height_of t1 -1) ~subst context m1,x2
546      else 
547       let h1 = height_of t1 in 
548       let h2 = height_of t2 in
549       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
550       NCicReduction.reduce_machine ~delta ~subst context m1,
551       NCicReduction.reduce_machine ~delta ~subst context m2
552     in
553     let rec unif_machines metasenv subst = 
554       function
555       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
556      (*D*) inside 'M'; try let rc = 
557          pp (lazy("UM: " ^
558            NCicPp.ppterm ~metasenv ~subst ~context 
559              (NCicReduction.unwind (k1,e1,t1,s1)) ^
560            " === " ^ 
561            NCicPp.ppterm ~metasenv ~subst ~context 
562              (NCicReduction.unwind (k2,e2,t2,s2))));
563 pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
564           let relevance = [] (* TO BE UNDERSTOOD 
565             match t1 with
566             | C.Const r -> NCicEnvironment.get_relevance r
567             | _ -> [] *) in
568           let unif_from_stack t1 t2 b metasenv subst =
569               try
570                 let t1 = NCicReduction.from_stack t1 in
571                 let t2 = NCicReduction.from_stack t2 in
572                 unif_machines metasenv subst (put_in_whd t1 t2)
573               with UnificationFailure _ | Uncertain _ when not b ->
574                 metasenv, subst
575           in
576           let rec check_stack l1 l2 r todo =
577             match l1,l2,r with
578             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
579             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
580             | l1, l2, _ -> 
581                NCicReduction.unwind (k1,e1,t1,List.rev l1),
582                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
583                 todo
584           in
585         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
586         try
587          let metasenv,subst = fo_unif test_eq_only metasenv subst hh1 hh2 in
588          List.fold_left
589           (fun (metasenv,subst) (x1,x2,r) ->
590             unif_from_stack x1 x2 r metasenv subst
591           ) (metasenv,subst) todo
592         with UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
593             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
594       (*D*)  in outside(); rc with exn -> outside (); raise exn 
595      in
596      try fo_unif test_eq_only metasenv subst t1 t2
597      with 
598      | UnificationFailure msg as exn ->
599           (try 
600             unif_machines metasenv subst 
601              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
602           with 
603           | UnificationFailure _ -> raise (UnificationFailure msg)
604           | Uncertain _ -> raise exn)
605      | Uncertain msg as exn -> 
606        match try_hints metasenv subst t1 t2 with
607        | Some x -> x
608        | None -> 
609           try 
610             unif_machines metasenv subst 
611              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
612           with 
613           | UnificationFailure _ -> raise (UnificationFailure msg)
614           | Uncertain _ -> raise exn
615  (*D*)  in outside(); rc with exn -> outside (); raise exn 
616 ;;
617
618 let unify hdb ?(test_eq_only=false) = 
619   indent := "";      
620   unify hdb test_eq_only;;