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