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