]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
71b790a26cf3c0e874963ec6ee7b530c57d9d393
[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 exception KeepReducing of string Lazy.t;;
18 exception KeepReducingThis of 
19   string Lazy.t * (NCicReduction.machine * bool) * 
20                   (NCicReduction.machine * bool) ;;
21
22 let (===) x y = Pervasives.compare x y = 0 ;;
23
24 let mk_msg metasenv subst context t1 t2 =
25  (lazy (
26   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
27   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2))
28
29 let mk_appl ~upto hd tl =
30   NCicReduction.head_beta_reduce ~upto
31     (match hd with
32     | NCic.Appl l -> NCic.Appl (l@tl)
33     | _ -> NCic.Appl (hd :: tl))
34 ;;
35
36 exception WrongShape;;
37
38 let eta_reduce subst t = 
39   let delift_if_not_occur body =
40     try 
41         Some (NCicSubstitution.psubst ~avoid_beta_redexes:true
42           (fun () -> raise WrongShape) [()] body)
43     with WrongShape -> None
44   in 
45   let rec eat_lambdas ctx = function
46     | NCic.Lambda (name, src, tgt) -> 
47         eat_lambdas ((name, src) :: ctx) tgt
48     | NCic.Meta (i,lc) as t->
49         (try 
50           let _,_,t,_ = NCicUtils.lookup_subst i subst in
51           let t = NCicSubstitution.subst_meta lc t in
52           eat_lambdas ctx t
53         with Not_found -> ctx, t)
54     | t -> ctx, t
55   in
56   let context_body = eat_lambdas [] t in
57   let rec aux = function
58     | [],body -> body
59     | (name, src)::ctx, (NCic.Appl (hd::[NCic.Rel 1]) as bo) -> 
60         (match delift_if_not_occur hd with
61         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
62         | Some bo -> aux (ctx,bo))
63     | (name, src)::ctx, (NCic.Appl args as bo) 
64       when HExtlib.list_last args = NCic.Rel 1 -> 
65         let args, _ = HExtlib.split_nth (List.length args - 1) args in
66         (match delift_if_not_occur (NCic.Appl args) with
67         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
68         | Some bo -> aux (ctx,bo))
69     | (name, src) :: ctx, t ->
70         aux (ctx,NCic.Lambda(name,src, t)) 
71   in
72     aux context_body
73 ;;
74
75 module C = NCic;;
76 module Ref = NReference;;
77
78 let debug = ref false;;
79 let indent = ref "";;
80 let times = ref [];;
81 let pp s =
82  if !debug then
83   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
84 ;;
85 let inside c =
86  if !debug then
87   begin
88    let time1 = Unix.gettimeofday () in
89    indent := !indent ^ String.make 1 c;
90    times := time1 :: !times;
91    prerr_endline ("{{{" ^ !indent ^ " ")
92   end
93 ;;
94 let outside exc_opt =
95  if !debug then
96   begin
97    let time2 = Unix.gettimeofday () in
98    let time1 =
99     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
100    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
101    (match exc_opt with
102    | Some e ->  prerr_endline ("exception raised: " ^ Printexc.to_string e)
103    | None -> ());
104    try
105     indent := String.sub !indent 0 (String.length !indent -1)
106    with
107     Invalid_argument _ -> indent := "??"; ()
108   end
109 ;;
110
111 let ppcontext ~metasenv ~subst c = 
112       "\nctx:\n"^ NCicPp.ppcontext ~metasenv ~subst c
113 ;;
114 let ppmetasenv ~subst m = "\nmenv:\n" ^ NCicPp.ppmetasenv ~subst m;;
115
116 let ppcontext ~metasenv:_metasenv ~subst:_subst _context = "";;
117 let ppmetasenv ~subst:_subst _metasenv = "";;
118 let ppterm ~metasenv ~subst ~context = NCicPp.ppterm ~metasenv ~subst ~context;;
119 (* let ppterm ~metasenv:_ ~subst:_ ~context:_ _ = "";; *)
120
121 let is_locked n subst =
122    try
123      match NCicUtils.lookup_subst n subst with
124      | tag, _,_,_ when NCicMetaSubst.is_out_scope_tag tag -> true
125      | _ -> false
126    with NCicUtils.Subst_not_found _ -> false
127 ;;
128
129 let rec mk_irl stop base =
130   if base > stop then []
131   else (NCic.Rel base) :: mk_irl stop (base+1) 
132 ;;
133
134 (* the argument must be a term in whd *)
135 let rec could_reduce =
136  function
137   | C.Meta _ -> true
138   | C.Appl (C.Const (Ref.Ref (_,Ref.Fix (_,recno,_)))::args)
139      when List.length args > recno -> could_reduce (List.nth args recno)
140   | C.Match (_,_,arg,_) -> could_reduce arg
141   | C.Appl (he::_) -> could_reduce he
142   | C.Sort _ | C.Rel _ | C.Prod _ | C.Lambda _ | C.Const _ -> false
143   | C.Appl [] | C.LetIn _ | C.Implicit _ -> assert false
144 ;;
145
146 let rec lambda_intros rdb metasenv subst context argsno ty =
147  pp (lazy ("LAMBDA INTROS: " ^ ppterm ~metasenv ~subst ~context ty));
148  match argsno with
149     0 -> 
150        let metasenv, _, bo, _ = 
151          NCicMetaSubst.mk_meta metasenv context ~with_type:ty `IsTerm
152        in
153        metasenv, bo
154   | _ ->
155      (match NCicReduction.whd ~subst context ty with
156          C.Prod (n,so,ta) ->
157           let metasenv,bo =
158            lambda_intros rdb metasenv subst
159             ((n,C.Decl so)::context) (argsno - 1) ta
160           in
161            metasenv,C.Lambda (n,so,bo)
162        | _ -> assert false)
163 ;;
164   
165 let unopt exc = function None -> raise exc | Some x -> x ;;
166
167 let fix metasenv subst is_sup test_eq_only exc t =
168   let rec aux test_eq_only metasenv = function
169     | NCic.Prod (n,so,ta) ->
170        let metasenv,so = aux true metasenv so in
171        let metasenv,ta = aux test_eq_only metasenv ta in
172         metasenv,NCic.Prod (n,so,ta)
173     | NCic.Sort (NCic.Type [(`CProp|`Type),_]) as orig when test_eq_only ->
174        metasenv,orig
175     | NCic.Sort (NCic.Type _) when test_eq_only -> raise exc
176     | NCic.Sort (NCic.Type u) when is_sup ->
177        metasenv, NCic.Sort (NCic.Type (unopt exc (NCicEnvironment.sup u)))
178     | NCic.Sort (NCic.Type u) ->
179        metasenv, NCic.Sort (NCic.Type 
180          (unopt exc (NCicEnvironment.inf ~strict:false u)))
181     | NCic.Meta (n,_) as orig ->
182         (try 
183           let _,_,_,_ = NCicUtils.lookup_subst n subst in metasenv,orig
184          with NCicUtils.Subst_not_found _ -> 
185           let metasenv, _ = NCicMetaSubst.extend_meta metasenv n in
186            metasenv, orig)
187     | t ->
188       NCicUntrusted.map_term_fold_a (fun _ x -> x) test_eq_only aux metasenv t
189   in
190    aux test_eq_only metasenv t
191 ;;
192
193 let rec sortfy exc metasenv subst = function
194   | NCic.Sort _ as orig -> metasenv, orig
195   | NCic.Meta (n,lc) -> 
196       let attrs, context, ty = NCicUtils.lookup_meta n metasenv in
197       let kind = NCicUntrusted.kind_of_meta attrs in
198       kindfy exc metasenv subst context n lc ty kind `IsSort
199   | NCic.Implicit _ -> assert false
200   | _ -> raise exc
201
202 and kindfy exc metasenv subst context n lc ty kind kind2 = 
203   match kind, ty, kind2 with
204   | `IsSort, _, _ -> assert(snd lc = NCic.Irl 0); metasenv, NCic.Meta(n,lc)
205   | k1, NCic.Implicit (`Typeof _), (`IsType|`IsTerm as k2) -> 
206      let k = NCicUntrusted.max_kind k1 k2 in
207      let metasenv = 
208        NCicUntrusted.replace_in_metasenv n
209          (fun attrs,cc,ty -> NCicUntrusted.set_kind k attrs, cc, ty) metasenv 
210      in
211      metasenv, NCic.Meta(n,lc)
212   | _, NCic.Implicit (`Typeof _), `IsSort ->
213      let metasenv = 
214        NCicUntrusted.replace_in_metasenv n
215         (fun attrs,_,ty-> NCicUntrusted.set_kind `IsSort attrs,[],ty) metasenv 
216      in
217      metasenv, NCic.Meta (n,(0,NCic.Irl 0))
218   | _, ty, `IsSort ->
219      let metasenv, ty = 
220        sortfy exc metasenv subst (NCicReduction.whd ~subst context ty) 
221      in
222      let metasenv = 
223        NCicUntrusted.replace_in_metasenv n
224         (fun attrs,_,_-> NCicUntrusted.set_kind `IsSort attrs,[],ty) metasenv 
225      in
226      metasenv, NCic.Meta (n,(0,NCic.Irl 0))
227   | k1, _, k2 when NCicUntrusted.max_kind k1 k2 = k1-> metasenv, NCic.Meta(n,lc)
228   | `IsTerm, ty, `IsType ->
229      let metasenv, ty = 
230        sortfy exc metasenv subst (NCicReduction.whd ~subst context ty) 
231      in
232      let metasenv = 
233        NCicUntrusted.replace_in_metasenv n
234         (fun attrs,cc,_-> NCicUntrusted.set_kind `IsType attrs,cc,ty) metasenv 
235      in
236      metasenv, NCic.Meta (n,lc)
237   | _ -> assert false (* XXX *)
238
239 and instantiate rdb test_eq_only metasenv subst context n lc t swap =
240  (*D*)  inside 'I'; try let rc =  
241   pp (lazy(string_of_int n^" :=?= "^ppterm ~metasenv ~subst ~context t));
242   let exc = 
243     UnificationFailure (mk_msg metasenv subst context (NCic.Meta (n,lc)) t) in
244   let move_to_subst i attrs cc t ty metasenv subst =
245     let metasenv = List.remove_assoc i metasenv in
246     pp (lazy(string_of_int n ^ " :==> "^ 
247       ppterm ~metasenv ~subst ~context:cc t));
248     metasenv, (i,(attrs, cc, t, ty)) :: subst
249   in
250   let delift_to_subst test_eq_only n lc attrs cc t ty context metasenv subst =
251     pp (lazy(string_of_int n ^ " := 111 = "^ 
252       ppterm ~metasenv ~subst ~context t));
253     let (metasenv, subst), t = 
254       try 
255         NCicMetaSubst.delift 
256          ~unify:(fun m s c t1 t2 -> 
257            let ind = !indent in
258            let res = 
259                    try Some (unify rdb test_eq_only m s c t1 t2 )
260              with UnificationFailure _ | Uncertain _ -> None
261            in
262            indent := ind; res) 
263          metasenv subst context n lc t
264       with NCicMetaSubst.Uncertain msg -> 
265            pp (lazy ("delift is uncertain: " ^ Lazy.force msg));
266            raise (Uncertain msg)
267       | NCicMetaSubst.MetaSubstFailure msg -> 
268            pp (lazy ("delift fails: " ^ Lazy.force msg));
269            raise (UnificationFailure msg)
270     in
271     pp (lazy(string_of_int n ^ " := 222 = "^
272       ppterm ~metasenv ~subst ~context:cc t^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 rdb test_eq_only metasenv subst context t oldt
280     with NCicUtils.Subst_not_found _ -> 
281       move_to_subst n attrs cc t ty metasenv subst
282   in
283   let attrs, cc, ty = NCicUtils.lookup_meta n metasenv in
284   match NCicUntrusted.kind_of_meta attrs, ty, t, swap with
285   | `IsSort, (NCic.Implicit (`Typeof _) as bot), NCic.Sort (NCic.Type u),false->
286       pp(lazy("1"));
287       let u = NCicEnvironment.inf ~strict:false u in
288       let t = NCic.Sort (NCic.Type (unopt exc u)) in
289       move_to_subst n attrs cc t bot metasenv subst  
290   | `IsSort, (NCic.Implicit (`Typeof _) as bot), NCic.Sort (NCic.Type u),true ->
291       pp(lazy("2"));
292       let u = NCicEnvironment.sup u in
293       let t = NCic.Sort (NCic.Type (unopt exc u)) in
294       move_to_subst n attrs cc t bot metasenv subst  
295   | `IsSort, (NCic.Sort(NCic.Type u1) as ty), NCic.Sort (NCic.Type u2), false ->
296       pp(lazy("3"));
297       let u = 
298         NCicEnvironment.inf ~strict:false (u1 @
299           unopt exc (NCicEnvironment.inf ~strict:true u2)) 
300       in
301       let t = NCic.Sort (NCic.Type (unopt exc u)) in
302       move_to_subst n attrs cc t ty metasenv subst  
303   | `IsSort, (NCic.Sort(NCic.Type u1) as ty), NCic.Sort (NCic.Type u2), true ->
304       pp(lazy("4"));
305       let u = unopt exc (NCicEnvironment.sup u2) in
306       if NCicEnvironment.universe_lt u u1 then
307         let t = NCic.Sort (NCic.Type u) in
308         move_to_subst n attrs cc t ty metasenv subst  
309       else (raise exc)
310   | kind, ty, NCic.Meta(m,lcm), _ when List.mem_assoc m subst ->
311       let at,ccm,bo,tym = NCicUtils.lookup_subst m subst in
312        if NCicMetaSubst.is_out_scope_tag at then
313         begin
314          (* Case meta vs out-scope *)
315          pp(lazy("4.1"));
316          let ty_t, ccm, kindm = 
317            NCicSubstitution.subst_meta lcm tym, ccm,
318             NCicUntrusted.kind_of_meta at in
319          let lty = NCicSubstitution.subst_meta lc ty in
320          pp (lazy ("On the types: " ^
321            ppterm ~metasenv ~subst ~context lty ^
322            (if test_eq_only then " === " else "=<=") ^
323            ppterm ~metasenv ~subst ~context ty_t)); 
324          let metasenv, subst = 
325            unify rdb test_eq_only metasenv subst context ty_t lty in
326          (*CSC: here I should call kindfy, but it fails since the second
327            meta in in the susbt, not the metasenv! *)
328       (*  let metasenv,t = kindfy exc metasenv subst ccm m lcm ty_t kindm kind in *)
329          delift_to_subst test_eq_only n lc attrs cc t ty context metasenv subst 
330         end
331        else
332         let bo = NCicSubstitution.subst_meta lcm bo in
333         instantiate rdb test_eq_only metasenv subst context n lc bo swap
334   | kind, (NCic.Implicit (`Typeof _) as bot),  NCic.Meta(m,lcm), _ ->
335       pp(lazy("5"));
336       let attrsm, ccm, tym = NCicUtils.lookup_meta m metasenv in
337       let kindm = NCicUntrusted.kind_of_meta attrsm in
338       let metasenv, t = kindfy exc metasenv subst ccm m lcm tym kindm kind in
339       move_to_subst n attrs cc t bot metasenv subst  
340   | kind, ty,  (NCic.Meta(m,_) as t), _ when 
341     let _, _, tym = NCicUtils.lookup_meta m metasenv in
342     (match tym with NCic.Implicit (`Typeof _) -> true | _ -> false) ->
343       pp(lazy("6"));
344       let attrsm, _, _ = NCicUtils.lookup_meta m metasenv in
345       let kindm = NCicUntrusted.kind_of_meta attrsm in
346       let metasenv, _ = kindfy exc metasenv subst cc n lc ty kind kindm in
347       let attrs, cc, ty = NCicUtils.lookup_meta n metasenv in
348       let metasenv = NCicUntrusted.replace_in_metasenv m
349         (fun _,_,_ -> attrs,cc,ty) metasenv
350       in
351       (* XXX *)move_to_subst n attrs cc t ty metasenv subst  
352   | kind, ty,  NCic.Meta(m,lcm), _ ->
353       pp(lazy("7"));
354       let ty_t, ccm, kindm = 
355         let at, ccm, tym = NCicUtils.lookup_meta m metasenv in
356         NCicSubstitution.subst_meta lcm tym, ccm, NCicUntrusted.kind_of_meta at
357       in
358       let lty = NCicSubstitution.subst_meta lc ty in
359       pp (lazy ("On the types: " ^
360         ppterm ~metasenv ~subst ~context lty ^
361         (if test_eq_only then " === " else "=<=") ^
362         ppterm ~metasenv ~subst ~context ty_t)); 
363       let metasenv, subst = 
364         unify rdb test_eq_only metasenv subst context ty_t lty
365       in
366       let metasenv, t = kindfy exc metasenv subst ccm m lcm ty_t kindm kind in
367       delift_to_subst test_eq_only n lc attrs cc t ty context metasenv subst 
368   | _, (NCic.Implicit (`Typeof _) as bot), t, swap ->
369       pp(lazy("8"));
370       let metasenv, t = fix metasenv subst swap test_eq_only exc t in
371 (*       let ty_t = NCicTypeChecker.typeof ~metasenv ~subst context t in *)
372       (* ty andrebbe deliftato *)
373       delift_to_subst test_eq_only n lc attrs cc t bot context metasenv subst 
374   | _, ty, t, swap ->
375       pp(lazy("9"));
376       let lty = NCicSubstitution.subst_meta lc ty in
377       let metasenv, t = fix metasenv subst swap test_eq_only exc t in
378       let ty_t = NCicTypeChecker.typeof ~metasenv ~subst context t in
379       pp (lazy ("On the types: " ^
380         ppterm ~metasenv ~subst ~context lty ^
381         (if test_eq_only then " === " else "=<=") ^
382         ppterm ~metasenv ~subst ~context ty_t)); 
383       let metasenv, subst = 
384         unify rdb test_eq_only metasenv subst context ty_t lty
385       in
386       delift_to_subst test_eq_only n lc attrs cc t ty context metasenv subst 
387  (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
388
389 and unify rdb test_eq_only metasenv subst context t1 t2 =
390  (*D*) inside 'U'; try let rc =
391    let fo_unif test_eq_only metasenv subst (norm1,t1) (norm2,t2) =
392     (*D*) inside 'F'; try let rc =  
393      pp (lazy("  " ^ ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
394          ppterm ~metasenv ~subst ~context t2 ^ ppmetasenv
395          ~subst metasenv));
396      pp (lazy("  " ^ ppterm ~metasenv ~subst:[] ~context t1 ^ " ==??== " ^ 
397          ppterm ~metasenv ~subst:[] ~context t2 ^ ppmetasenv
398          ~subst metasenv));
399      if t1 === t2 then
400        metasenv, subst
401 (* CSC: To speed up Oliboni's stuff. Why is it necessary, anyway?
402      else if
403       NCicUntrusted.metas_of_term subst context t1 = [] &&
404       NCicUntrusted.metas_of_term subst context t2 = []
405      then
406       if NCicReduction.are_convertible ~metasenv ~subst context t1 t2 then
407        metasenv,subst
408       else
409        raise (UnificationFailure (lazy "Closed terms not convertible"))
410 *)
411      else
412        match (t1,t2) with
413        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
414        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
415            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
416            assert false 
417        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
418            if NCicEnvironment.universe_leq a b then metasenv, subst
419            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
420        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
421            if NCicEnvironment.universe_eq a b then metasenv, subst
422            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
423        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
424            if (not test_eq_only) then metasenv, subst
425            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
426
427        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
428        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
429            let metasenv, subst = unify rdb true metasenv subst context s1 s2 in
430            unify rdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
431        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
432            let metasenv,subst=unify rdb test_eq_only metasenv subst context ty1 ty2 in
433            let metasenv,subst=unify rdb test_eq_only metasenv subst context s1 s2 in
434            let context = (name1, C.Def (s1,ty1))::context in
435            unify rdb test_eq_only metasenv subst context t1 t2
436
437        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
438           (try 
439            let l1 = NCicUtils.expand_local_context l1 in
440            let l2 = NCicUtils.expand_local_context l2 in
441            let metasenv, subst, to_restrict, _ =
442             List.fold_right2 
443              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
444                 try 
445                   let metasenv, subst = 
446                    unify rdb test_eq_only metasenv subst context 
447                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
448                   in
449                   metasenv, subst, to_restrict, i-1  
450                 with UnificationFailure _ | Uncertain _ ->
451                   metasenv, subst, i::to_restrict, i-1)
452              l1 l2 (metasenv, subst, [], List.length l1)
453            in
454            if to_restrict <> [] then
455              let metasenv, subst, _ = 
456                NCicMetaSubst.restrict metasenv subst n1 to_restrict
457              in
458                metasenv, subst
459            else metasenv, subst
460           with 
461            | Invalid_argument _ -> assert false
462            | NCicMetaSubst.MetaSubstFailure msg ->
463               try 
464                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
465                 let term1 = NCicSubstitution.subst_meta lc1 term in
466                 let term2 = NCicSubstitution.subst_meta lc2 term in
467                   unify rdb test_eq_only metasenv subst context term1 term2
468               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
469
470        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
471           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
472             (try
473               List.fold_left2 
474                 (fun (metasenv, subst) t1 t2 ->
475                   unify rdb test_eq_only metasenv subst context t1 t2)
476                 (metasenv,subst) l1 l2
477             with Invalid_argument _ -> 
478               raise (UnificationFailure (mk_msg metasenv subst context t1 t2)))
479        
480        | _, NCic.Meta (n, _) when is_locked n subst ->
481            (let (metasenv, subst), i = 
482               match NCicReduction.whd ~subst context t1 with
483               | NCic.Appl (NCic.Meta (i,l) as meta :: args) ->
484                  let metasenv, lambda_Mj =
485                    lambda_intros rdb metasenv subst context (List.length args)
486                     (NCicTypeChecker.typeof ~metasenv ~subst context meta)
487                  in
488                    unify rdb test_eq_only metasenv subst context 
489                     (C.Meta (i,l)) lambda_Mj,
490                    i
491               | NCic.Meta (i,_) -> (metasenv, subst), i
492               | _ ->
493                  raise (UnificationFailure (lazy "Locked term vs non
494                   flexible term; probably not saturated enough yet!"))
495              in
496               let t1 = NCicReduction.whd ~subst context t1 in
497               let j, lj = 
498                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
499               in
500               let metasenv, subst = 
501                 instantiate rdb test_eq_only metasenv subst context j lj t2 true
502               in
503               (* We need to remove the out_scope_tags to avoid propagation of
504                  them that triggers again the ad-hoc case *)
505               let subst =
506                List.map (fun (i,(tag,ctx,bo,ty)) ->
507                 let tag =
508                  List.filter
509                   (function `InScope | `OutScope _ -> false | _ -> true) tag
510                 in
511                   i,(tag,ctx,bo,ty)
512                 ) subst
513               in
514               (try
515                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
516                 let term = eta_reduce subst term in
517                 let subst = List.filter (fun (j,_) -> j <> i) subst in
518                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
519               with Not_found -> assert false))
520
521        | C.Meta (n,lc), t when List.mem_assoc n subst -> 
522           let _,_,term,_ = NCicUtils.lookup_subst n subst in
523           let term = NCicSubstitution.subst_meta lc term in
524             unify rdb test_eq_only metasenv subst context term t
525
526        | t, C.Meta (n,lc) when List.mem_assoc n subst -> 
527           let _,_,term,_ = NCicUtils.lookup_subst n subst in
528           let term = NCicSubstitution.subst_meta lc term in
529             unify rdb test_eq_only metasenv subst context t term
530
531        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
532             let _,_,term,_ = NCicUtils.lookup_subst i subst in
533             let term = NCicSubstitution.subst_meta l term in
534               unify rdb test_eq_only metasenv subst context 
535                 (mk_appl ~upto:(List.length args) term args) t2
536
537        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
538             let _,_,term,_ = NCicUtils.lookup_subst i subst in
539             let term = NCicSubstitution.subst_meta l term in
540               unify rdb test_eq_only metasenv subst context t1 
541                 (mk_appl ~upto:(List.length args) term args)
542
543        | C.Meta (n,lc), t -> 
544           instantiate rdb test_eq_only metasenv subst context n lc 
545             (NCicReduction.head_beta_reduce ~subst t) false
546
547        | t, C.Meta (n,lc) -> 
548           instantiate rdb test_eq_only metasenv subst context n lc 
549            (NCicReduction.head_beta_reduce ~subst t) true
550
551        | NCic.Appl (NCic.Meta (i,l) as meta :: args), _ ->
552           let metasenv, lambda_Mj =
553             lambda_intros rdb metasenv subst context (List.length args)
554              (NCicTypeChecker.typeof ~metasenv ~subst context meta)
555           in
556           let metasenv, subst = 
557            try
558             unify rdb test_eq_only metasenv subst context 
559               (C.Meta (i,l)) lambda_Mj
560            with UnificationFailure msg | Uncertain msg when not norm2->
561             (* failure: let's try again argument vs argument *)
562             raise (KeepReducing msg)
563           in
564           let metasenv, subst = 
565             unify rdb test_eq_only metasenv subst context t1 t2 
566           in
567           (try
568             let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
569             let term = eta_reduce subst term in
570             let subst = List.filter (fun (j,_) -> j <> i) subst in
571             metasenv, ((i, (name, ctx, term, ty)) :: subst)
572           with Not_found -> assert false)
573
574        | _, NCic.Appl (NCic.Meta (i,l) as meta :: args) ->
575          let metasenv, lambda_Mj =
576            lambda_intros rdb metasenv subst context (List.length args)
577              (NCicTypeChecker.typeof ~metasenv ~subst context meta)
578          in
579          let metasenv, subst =
580           try
581            unify rdb test_eq_only metasenv subst context 
582             lambda_Mj (C.Meta (i,l))
583           with UnificationFailure msg | Uncertain msg when not norm1 ->
584            (* failure: let's try again argument vs argument *)
585            raise (KeepReducing msg)
586          in
587          let metasenv, subst = 
588            unify rdb test_eq_only metasenv subst context t1 t2 
589          in
590          (try
591            let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
592            let term = eta_reduce subst term in
593            let subst = List.filter (fun (j,_) -> j <> i) subst in
594            metasenv, ((i, (name, ctx, term, ty)) :: subst)
595          with Not_found -> assert false)
596
597        (* processing this case here we avoid a useless small delta step *)
598        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
599          when Ref.eq r1 r2 ->
600            let relevance = NCicEnvironment.get_relevance r1 in
601            let metasenv, subst, _ = 
602              try
603                List.fold_left2 
604                  (fun (metasenv, subst, relevance) t1 t2 ->
605                     let b, relevance = 
606                       match relevance with b::tl -> b,tl | _ -> true, [] in
607                     let metasenv, subst = 
608                       try unify rdb test_eq_only metasenv subst context t1 t2
609                       with UnificationFailure _ | Uncertain _ when not b ->
610                         metasenv, subst
611                     in
612                       metasenv, subst, relevance)
613                  (metasenv, subst, relevance) tl1 tl2
614              with
615                 Invalid_argument _ -> 
616                  raise (Uncertain (mk_msg metasenv subst context t1 t2))
617               | UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
618                  raise (KeepReducing (mk_msg metasenv subst context t1 t2))
619               | KeepReducing _ | KeepReducingThis _ -> assert false
620            in 
621              metasenv, subst
622
623        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
624           C.Match (ref2,outtype2,term2,pl2)) ->
625            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
626            let _,_,ty,_ = List.nth itl tyno in
627            let rec remove_prods ~subst context ty = 
628              let ty = NCicReduction.whd ~subst context ty in
629              match ty with
630              | C.Sort _ -> ty
631              | C.Prod (name,so,ta) -> 
632                    remove_prods ~subst ((name,(C.Decl so))::context) ta
633              | _ -> assert false
634            in
635            let is_prop = 
636              match remove_prods ~subst [] ty with
637              | C.Sort C.Prop -> true
638              | _ -> false 
639            in
640            if not (Ref.eq ref1 ref2) then 
641              raise (Uncertain (mk_msg metasenv subst context t1 t2))
642            else
643              let metasenv, subst = 
644               unify rdb test_eq_only metasenv subst context outtype1 outtype2 in
645              let metasenv, subst = 
646                try unify rdb test_eq_only metasenv subst context term1 term2 
647                with UnificationFailure _ | Uncertain _ when is_prop -> 
648                  metasenv, subst
649              in
650              (try
651               List.fold_left2 
652                (fun (metasenv,subst) -> 
653                   unify rdb test_eq_only metasenv subst context)
654                (metasenv, subst) pl1 pl2
655              with Invalid_argument _ -> assert false)
656        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
657        | _ when norm1 && norm2 ->
658            if (could_reduce t1 || could_reduce t2) then
659             raise (Uncertain (mk_msg metasenv subst context t1 t2))
660            else
661             raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
662        | _ -> raise (KeepReducing (mk_msg metasenv subst context t1 t2))
663      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
664     in
665     let try_hints metasenv subst (_,t1 as mt1) (_,t2 as mt2) (* exc*) =
666     (*D*) inside 'H'; try let rc =  
667      pp(lazy ("\nProblema:\n" ^
668         ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
669         ppterm ~metasenv ~subst ~context t2));
670       let candidates = 
671         NCicUnifHint.look_for_hint rdb metasenv subst context t1 t2
672       in
673       let rec cand_iter = function
674         | [] -> None (* raise exc *)
675         | (metasenv,(c1,c2),premises)::tl -> 
676             pp (lazy ("\nProvo il candidato:\n" ^ 
677               String.concat "\n"
678                 (List.map 
679                   (fun (a,b) ->
680                    ppterm ~metasenv ~subst ~context a ^  " =?= " ^
681                    ppterm ~metasenv ~subst ~context b) premises) ^
682               "\n-------------------------------------------\n"^
683               ppterm ~metasenv ~subst ~context c1 ^  " = " ^
684               ppterm ~metasenv ~subst ~context c2));
685             try 
686     (*D*) inside 'K'; try let rc =  
687               let metasenv,subst = 
688                 fo_unif test_eq_only metasenv subst mt1 (false,c1) in
689               let metasenv,subst = 
690                 fo_unif test_eq_only metasenv subst (false,c2) mt2 in
691               let metasenv,subst = 
692                 List.fold_left 
693                   (fun (metasenv, subst) (x,y) ->
694                      unify rdb test_eq_only metasenv subst context x y)
695                   (metasenv, subst) premises
696               in
697               pp(lazy("FUNZIONA!"));
698               Some (metasenv, subst)
699      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
700             with
701              KeepReducing _ | UnificationFailure _ | Uncertain _ -> cand_iter tl
702            | KeepReducingThis _ -> assert false
703       in
704         cand_iter candidates
705      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
706     in
707     let put_in_whd m1 m2 =
708       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
709       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
710     in
711     let fo_unif_w_hints test_eq_only metasenv subst (_,t1 as m1) (_,t2 as m2) =
712       try fo_unif test_eq_only metasenv subst m1 m2
713       with 
714       | UnificationFailure _ as exn -> raise exn
715       | KeepReducing _ | Uncertain _ as exn ->
716         let (t1,norm1 as tm1),(t2,norm2 as tm2) =
717          put_in_whd (0,[],t1,[]) (0,[],t2,[])
718         in
719          match 
720            try_hints metasenv subst 
721             (norm1,NCicReduction.unwind t1) (norm2,NCicReduction.unwind t2)
722          with
723           | Some x -> x
724           | None -> 
725               match exn with 
726               | KeepReducing msg -> raise (KeepReducingThis (msg,tm1,tm2))
727               | Uncertain _ as exn -> raise exn
728               | _ -> assert false
729     in
730     let height_of = function
731      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
732      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
733      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
734      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
735      | _ -> 0
736     in
737     let small_delta_step ~subst  
738       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
739     =
740      assert (not (norm1 && norm2));
741      if norm1 then
742       x1,NCicReduction.reduce_machine ~delta:0 ~subst context m2
743      else if norm2 then
744       NCicReduction.reduce_machine ~delta:0 ~subst context m1,x2
745      else 
746       let h1 = height_of t1 in 
747       let h2 = height_of t2 in
748       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
749       NCicReduction.reduce_machine ~delta ~subst context m1,
750       NCicReduction.reduce_machine ~delta ~subst context m2
751     in
752     let rec unif_machines metasenv subst = 
753       function
754       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
755      (*D*) inside 'M'; try let rc = 
756          pp (lazy("UM: " ^
757            ppterm ~metasenv ~subst ~context 
758              (NCicReduction.unwind (k1,e1,t1,s1)) ^
759            " === " ^ 
760            ppterm ~metasenv ~subst ~context 
761              (NCicReduction.unwind (k2,e2,t2,s2))));
762          pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
763           let relevance = [] (* TO BE UNDERSTOOD 
764             match t1 with
765             | C.Const r -> NCicEnvironment.get_relevance r
766             | _ -> [] *) in
767           let unif_from_stack t1 t2 b metasenv subst =
768               try
769                 let t1 = NCicReduction.from_stack ~delta:max_int t1 in
770                 let t2 = NCicReduction.from_stack ~delta:max_int t2 in
771                 unif_machines metasenv subst (put_in_whd t1 t2)
772               with UnificationFailure _ | Uncertain _ when not b ->
773                 metasenv, subst
774           in
775           let rec check_stack l1 l2 r todo =
776             match l1,l2,r with
777             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
778             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
779             | l1, l2, _ -> 
780                NCicReduction.unwind (k1,e1,t1,List.rev l1),
781                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
782                 todo
783           in
784         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
785         try
786          let metasenv,subst =
787           fo_unif_w_hints test_eq_only metasenv subst (norm1,hh1) (norm2,hh2) in
788          List.fold_left
789           (fun (metasenv,subst) (x1,x2,r) ->
790             unif_from_stack x1 x2 r metasenv subst
791           ) (metasenv,subst) todo
792         with
793          | KeepReducing _ -> assert false
794          | KeepReducingThis _ ->
795             assert (not (norm1 && norm2));
796             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
797          | UnificationFailure _ | Uncertain _ when (not (norm1 && norm2))
798            -> unif_machines metasenv subst (small_delta_step ~subst m1 m2)
799          | UnificationFailure msg
800            when could_reduce (NCicReduction.unwind (fst m1))
801              || could_reduce (NCicReduction.unwind (fst m2))
802            -> raise (Uncertain msg)
803       (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
804      in
805      try fo_unif_w_hints test_eq_only metasenv subst (false,t1) (false,t2)
806      with
807       | KeepReducingThis (msg,tm1,tm2) ->
808          (try 
809            unif_machines metasenv subst (tm1,tm2)
810           with 
811           | UnificationFailure _ -> raise (UnificationFailure msg)
812           | Uncertain _ -> raise (Uncertain msg)
813           | KeepReducing _ -> assert false)
814       | KeepReducing _ -> assert false
815
816  (*D*)  in outside None; rc with KeepReducing _ -> assert false | exn -> outside (Some exn); raise exn 
817
818 and delift_type_wrt_terms rdb metasenv subst context t args =
819   let lc = List.rev args @ mk_irl (List.length context) (List.length args+1) in
820   let (metasenv, subst), t =
821    try
822     NCicMetaSubst.delift 
823       ~unify:(fun m s c t1 t2 -> 
824          let ind = !indent in
825          let res = 
826            try Some (unify rdb false m s c t1 t2 )
827            with UnificationFailure _ | Uncertain _ -> None
828          in
829          indent := ind; res)
830       metasenv subst context 0 (0,NCic.Ctx lc) t
831    with
832       NCicMetaSubst.MetaSubstFailure _
833     | NCicMetaSubst.Uncertain _ -> (metasenv, subst), t
834   in
835    metasenv, subst, t
836 ;;
837
838
839 let unify rdb ?(test_eq_only=false) = 
840   indent := "";      
841   unify rdb test_eq_only;;
842
843 let fix_sorts m s =
844   fix m s true false (UnificationFailure (lazy "no sup"))
845 ;;