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