]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/lambda4.ml
8a5797ce1297491837bec242c6565b7a7481c767
[fireball-separation.git] / ocaml / lambda4.ml
1 open Util
2 open Util.Vars
3 open Pure
4 open Num
5
6 let bomb = ref(`Var(-1,-666));;
7
8 (*
9  The number of arguments which can applied to numbers
10  safely, depending on the encoding of numbers.
11  For Scott's encoding, two.
12 *)
13 let num_more_args = 2;;
14 let _very_verbose = false;;
15
16 let verbose s =
17  if _very_verbose then prerr_endline s
18 ;;
19
20 let convergent_dummy = `N ~-1;
21
22 type problem =
23  { freshno: int
24  ; div: i_var option (* None = bomb *)
25  ; conv: i_n_var list (* the inerts that must converge *)
26  ; ps: i_n_var list (* the n-th inert must become n *)
27  ; sigma: (int * nf) list (* the computed substitution *)
28  ; deltas: (int * nf) list ref list (* collection of all branches *)
29  ; initialSpecialK: int
30  ; label : string
31  ; var_names : string list (* names of the original free variables *)
32 };;
33
34 let label_of_problem {label} = label;;
35
36 let string_of_var l x =
37  try
38   List.nth l x
39  with Failure "nth" -> "`" ^ string_of_int x
40 ;;
41 let string_of_term p t = print ~l:p.var_names (t :> nf);;
42
43 let all_terms p =
44  (match p.div with None -> [] | Some t -> [(t :> i_n_var)])
45  @ p.conv
46  @ p.ps
47 ;;
48
49 let sum_arities p =
50  let rec aux = function
51  | `N _ -> 0
52  | `Var(_,ar) -> if ar = min_int then 0 else max 0 ar (*assert (ar >= 0); ar*)
53  | `Lam(_,t) -> aux t
54  | `I(v,args) -> aux (`Var v) + aux_many (Listx.to_list args)
55  | `Match(u,(_,ar),_,_,args) -> aux (u :> nf) + (if ar = min_int then 0 else ar - 1) + aux_many args
56  and aux_many tms = List.fold_right ((+) ++ aux) tms 0 in
57  aux_many (all_terms p :> nf list)
58  ;;
59
60 let count_fakevars p =
61  let rec aux = function
62  | `N _ -> 0
63  | `Var(_,ar) -> if ar = min_int then 1 else 0
64  | `Lam(_,t) -> aux t
65  | `I(v,args) -> aux (`Var v) + aux_many (Listx.to_list args)
66  | `Match(u,v,_,_,args) -> aux (u :> nf) + aux (`Var v) + aux_many args
67  and aux_many tms = List.fold_right ((+) ++ aux) tms 0 in
68  aux_many (all_terms p :> nf list)
69 ;;
70
71 (* let problem_measure p = count_fakevars p, sum_arities p;;
72 let string_of_measure (a,b) = "(fakevars="^string_of_int a^",sum_arities="^string_of_int b^")" *)
73
74 let problem_measure p = sum_arities p;;
75 let string_of_measure = string_of_int;;
76
77 let string_of_problem label ({freshno; div; conv; ps; deltas} as p) =
78  let deltas = String.concat ("\n#  ") (List.map (fun r -> String.concat " <> " (List.map (fun (i,_) -> string_of_int i) !r)) deltas) in
79  let l = p.var_names in
80  String.concat "\n" ([
81   "";
82   "# DISPLAY PROBLEM (" ^ label ^ ") " ^ "measure=" ^ string_of_measure (problem_measure p);
83   if List.length p.deltas > 1 then (
84    "# Discriminating sets (deltas):\n" ^
85    "#  " ^ deltas
86    ) else "# ";
87   "#";
88   "$" ^ p.label;
89   (match div with None -> "# no D" | Some div -> "D " ^ print ~l (div :> nf));
90   ]
91   @ List.map (fun t -> "C " ^ (if t = convergent_dummy then "#C" else "C " ^ print ~l (t :> nf))) conv
92   @ List.mapi (fun i t -> string_of_int i ^ " " ^ print ~l (t :> nf)) ps
93   @ [""])
94 ;;
95
96
97 let failwithProblem p reason =
98  print_endline (string_of_problem "FAIL" p);
99  failwith reason
100 ;;
101
102 let make_fresh_var p arity =
103  let freshno = p.freshno + 1 in
104  {p with freshno}, `Var(freshno,arity)
105 ;;
106
107 let make_fresh_vars p arities =
108  List.fold_right
109   (fun arity (p, vars) -> let p, var = make_fresh_var p arity in p, var::vars)
110   arities
111   (p, [])
112 ;;
113
114 let simple_expand_match ps =
115  let rec aux level = function
116   | #i_num_var as t -> (aux_i_num_var level t :> nf)
117   | `Lam(b,t) -> `Lam(b,aux (level+1) t)
118  and aux_i_num_var level = function
119   | `Match(u,v,bs_lift,bs,args) as torig ->
120     let (u : i_num_var) = aux_i_num_var level u in
121     bs := List.map (fun (n, x) -> n, aux 0 x) !bs;
122     (try
123        (match u with
124          | #i_n_var as u ->
125             let i = index_of ~eq:eta_eq (lift (-level) u) (ps :> nf list) in (* can raise Not_found *)
126             let t = cast_to_i_num_var (mk_match (`N i) v bs_lift bs (args :> nf list)) in
127             if t <> torig then
128              aux_i_num_var level t
129             else raise Not_found
130          | _ -> raise Not_found)
131       with Not_found ->
132        cast_to_i_num_var (mk_appl (`Match(u,v,bs_lift,bs,[])) (List.map (aux level) args)))
133   | `I(v,args) -> cast_to_i_num_var (mk_appl (`Var v) (List.map (aux level) (Listx.to_list args)))
134   | `N _ | `Var _ as t -> t
135  in aux_i_num_var 0
136 ;;
137
138 let fixpoint f =
139  let rec aux x = let x' = f x in if x <> x' then aux x' else x in aux
140 ;;
141
142 let rec super_simplify_ps ps =
143  fixpoint (List.map (fun x -> cast_to_i_n_var (simple_expand_match ps (x :> i_num_var))))
144 ;;
145
146 let rec super_simplify_ps_with_match ps =
147  fixpoint (List.map (cast_to_i_num_var ++ (simple_expand_match ps)))
148 ;;
149
150 let super_simplify ({div; ps; conv} as p) =
151   let ps = super_simplify_ps p.ps p.ps in
152   let conv = super_simplify_ps ps p.conv in
153   let div = option_map (fun div ->
154    let divs = super_simplify_ps p.ps ([div] :> i_n_var list) in
155     List.hd divs) div in
156   {p with div=option_map cast_to_i_var div; ps; conv}
157
158 exception ExpandedToLambda;;
159
160 let subst_in_problem x inst ({freshno; div; conv; ps; sigma} as p) =
161  let len_ps = List.length ps in
162 (*(let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
163 prerr_endline ("# INST0: " ^ string_of_var x ^ " := " ^ print ~l inst));*)
164  let rec aux ((freshno,acc_ps,acc_new_ps) as acc) =
165   function
166   | [] -> acc
167   | t::todo_ps ->
168 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
169      let t = subst false false x inst (t :> nf) in
170 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
171      let freshno,new_t,acc_new_ps =
172       expand_match (freshno,acc_ps@`Var(max_int/3,-666)::todo_ps,acc_new_ps) t
173      in
174       aux (freshno,acc_ps@[new_t],acc_new_ps) todo_ps
175
176   (* cut&paste from aux above *)
177   and aux' ps ((freshno,acc_conv,acc_new_ps) as acc) =
178    function
179    | [] -> acc
180    | t::todo_conv ->
181 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
182       (* try *)
183        let t = subst false false x inst (t :> nf) in
184 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
185        let freshno,new_t,acc_new_ps =
186         expand_match (freshno,ps,acc_new_ps) t
187        in
188         aux' ps (freshno,acc_conv@[new_t],acc_new_ps) todo_conv
189       (* with ExpandedToLambda -> aux' ps (freshno,acc_conv@[`N(-1)],acc_new_ps) todo_conv *)
190
191   (* cut&paste from aux' above *)
192   and aux'' ps (freshno,acc_new_ps) =
193    function
194    | None -> freshno, None, acc_new_ps
195    | Some t ->
196       let t = subst false false x inst (t :> nf) in
197       let freshno,new_t,acc_new_ps =
198        expand_match (freshno,ps,acc_new_ps) t
199       in
200        freshno,Some new_t,acc_new_ps
201
202   and expand_match ((freshno,acc_ps,acc_new_ps) as acc) t =
203    match t with
204    | `Match(u',orig,bs_lift,bs,args) ->
205         let freshno,u,acc_new_ps = expand_match acc (u' :> nf) in
206         let acc_new_ps,i =
207          match u with
208          | `N i -> acc_new_ps,i
209          | _ ->
210             let ps = List.map (fun t -> cast_to_i_num_var (subst false false x inst (t:> nf))) (acc_ps@acc_new_ps) in
211             let super_simplified_ps = super_simplify_ps_with_match ps ps in
212 (*prerr_endline ("CERCO u:" ^ print (fst u :> nf));
213 List.iter (fun x -> prerr_endline ("IN: " ^ print (fst x :> nf))) ps;
214 List.iter (fun x -> prerr_endline ("IN2: " ^ print (fst x :> nf))) super_simplified_ps;*)
215             match index_of_opt ~eq:eta_eq super_simplified_ps u with
216                Some i -> acc_new_ps, i
217              | None -> acc_new_ps@[u], len_ps + List.length acc_new_ps
218         in
219          let freshno=
220           if List.exists (fun (j,_) -> i=j) !bs then
221            freshno
222           else
223            let freshno,v = freshno+1, `Var (freshno+1, -666) in (* make_fresh_var freshno in *)
224            bs := !bs @ [i, v] ;
225            freshno in
226 (*prerr_endlie ("t DA RIDURRE:" ^ print (`Match(`N i,arity,bs_lift,bs,args) :> nf) ^ " more_args=" ^ string_of_int more_args);*)
227          let t = mk_match (`N i) orig bs_lift bs args in
228 (*prerr_endline ("NUOVO t:" ^ print (fst t :> nf) ^ " more_args=" ^ string_of_int (snd t));*)
229           expand_match (freshno,acc_ps,acc_new_ps) t
230    | `Lam _ -> raise ExpandedToLambda
231    | #i_n_var as x ->
232       let x = simple_expand_match (acc_ps@acc_new_ps) x in
233       freshno,cast_to_i_num_var x,acc_new_ps in
234
235  let freshno,old_ps,new_ps = aux (freshno,[],[]) (ps :> i_num_var list) in
236  let freshno,conv,new_ps = aux' old_ps (freshno,[],new_ps) (conv :> i_num_var list) in
237  let freshno,div,new_ps = aux'' old_ps (freshno,new_ps) (div :> i_num_var option) in
238  let div = option_map cast_to_i_var div in
239  let ps = List.map cast_to_i_n_var (old_ps @ new_ps) in
240  let conv = List.map cast_to_i_n_var conv in
241  let p = {p with freshno; div; conv; ps} in
242  prerr_endline ("# INST: " ^ string_of_var p.var_names x ^ " := " ^ string_of_term p inst);
243  ( (* check if double substituting a variable *)
244   if List.exists (fun (x',_) -> x = x') sigma
245    then failwithProblem p ("Variable "^ string_of_var p.var_names x ^"replaced twice")
246  );
247  let p = {p with sigma = sigma@[x,inst]} in
248  let p = super_simplify p in
249  prerr_endline (string_of_problem "instantiate" p);
250  p
251 ;;
252
253 exception Dangerous
254
255 let arity_of arities k =
256  let _,pos,y = List.find (fun (v,_,_) -> v=k) arities in
257  let arity = match y with `Var _ -> 0 | `I(_,args) -> Listx.length args | `N _ -> assert false in
258  arity + if pos = -1 then - 1 else 0
259 ;;
260
261 let rec dangerous arities showstoppers =
262  function
263     `N _
264   | `Var _
265   | `Lam _ -> ()
266   | `Match(t,_,liftno,bs,args) ->
267       (* CSC: XXX partial dependency on the encoding *)
268       (match t with
269           `N _ -> List.iter (dangerous arities showstoppers) args
270         | `Match _ as t -> dangerous arities showstoppers t ; List.iter (dangerous arities showstoppers) args
271         | `Var(x,_) -> dangerous_inert arities showstoppers x args num_more_args
272         | `I((x,_),args') -> dangerous_inert arities showstoppers x (Listx.to_list args' @ args) num_more_args
273       )
274   | `I((k,_),args) -> dangerous_inert arities showstoppers k (Listx.to_list args) 0
275
276 and dangerous_inert arities showstoppers k args more_args =
277  List.iter (dangerous arities showstoppers) args ;
278  if List.mem k showstoppers then raise Dangerous else
279  try
280   let arity = arity_of arities k in
281   if List.length args + more_args > arity then raise Dangerous else ()
282  with
283   Not_found -> ()
284
285 (* cut & paste from above *)
286 let rec dangerous_conv p arities showstoppers =
287  function
288     `N _
289   | `Var _
290   | `Lam _ -> []
291   | `Match(t,_,liftno,bs,args) ->
292       (* CSC: XXX partial dependency on the encoding *)
293       (match t with
294           `N _ -> concat_map (dangerous_conv p arities showstoppers) args
295         | `Match _ as t -> dangerous_conv p arities showstoppers t @ concat_map (dangerous_conv p arities showstoppers) args
296         | `Var(x,_) -> dangerous_inert_conv p arities showstoppers x [] args 2
297         | `I((x,_),args') -> dangerous_inert_conv p arities showstoppers x (Listx.to_list args') args 2
298       )
299   | `I((k,_),args) -> dangerous_inert_conv p arities showstoppers k (Listx.to_list args) [] 0
300
301 and dangerous_inert_conv p arities showstoppers k args match_args more_args =
302  let all_args = args @ match_args in
303  let dangerous_args = concat_map (dangerous_conv p arities showstoppers) all_args in
304  let all_args = (all_args :> nf list) in
305  if dangerous_args = [] then (
306  if List.mem k showstoppers then k :: concat_map free_vars all_args else
307  try
308   let arity = arity_of arities k in
309 prerr_endline ("dangerous_inert_conv: ar=" ^ string_of_int arity ^ " k="^string_of_var p.var_names k ^ " listlenargs=" ^ (string_of_int (List.length args)) ^ " more_args=" ^ string_of_int more_args);
310   if more_args > 0 (* match argument*) && List.length args = arity then []
311   else if List.length all_args + more_args > arity then k :: concat_map free_vars all_args else []
312  with
313   Not_found -> []
314  ) else k :: concat_map free_vars all_args
315
316 (* inefficient algorithm *)
317 let rec edible ({div; conv; ps} as p) arities showstoppers =
318  let rec aux showstoppers =
319   function
320      [] -> showstoppers
321    | x::xs when List.exists (fun y -> hd_of x = Some y) showstoppers ->
322       (* se la testa di x e' uno show-stopper *)
323       let new_showstoppers = sort_uniq (showstoppers @ free_vars (x :> nf)) in
324       (* aggiungi tutte le variabili libere di x *)
325       if List.length showstoppers <> List.length new_showstoppers then
326        aux new_showstoppers ps
327       else
328        aux showstoppers xs
329    | x::xs ->
330       match hd_of x with
331          None -> aux showstoppers xs
332        | Some h ->
333           try
334            dangerous arities showstoppers (x : i_n_var :> nf) ;
335            aux showstoppers xs
336           with
337            Dangerous ->
338             aux (sort_uniq (h::showstoppers)) ps
339   in
340     let showstoppers = sort_uniq (aux showstoppers ps) in
341     let dangerous_conv =
342      List.map (dangerous_conv p arities showstoppers) (conv :> nf list) in
343
344 prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
345 List.iter (fun l -> prerr_endline (String.concat " " (List.map (string_of_var p.var_names) l))) dangerous_conv;
346
347     let showstoppers' = showstoppers @ List.concat dangerous_conv in
348     let showstoppers' = sort_uniq (match div with
349      | None -> showstoppers'
350      | Some div ->
351        if List.exists ((=) (hd_of_i_var div)) showstoppers'
352        then showstoppers' @ free_vars (div :> nf) else showstoppers') in
353     if showstoppers <> showstoppers' then edible p arities showstoppers' else showstoppers', dangerous_conv
354 ;;
355
356 let precompute_edible_data {ps; div} xs =
357  (match div with None -> [] | Some div -> [hd_of_i_var div, -1, (div :> i_n_var)]) @
358   List.map (fun hd ->
359    let i, tm = Util.findi (fun y -> hd_of y = Some hd) ps in
360     hd, i, tm
361    ) xs
362 ;;
363
364 let critical_showstoppers p =
365   let p = super_simplify p in
366   let hd_of_div = match p.div with None -> [] | Some t -> [hd_of_i_var t] in
367   let showstoppers_step =
368   concat_map (fun bs ->
369     let heads = List.map (fun (i,_) -> List.nth p.ps i) !bs in
370     let heads = List.sort compare (hd_of_div @ filter_map hd_of heads) in
371     snd (split_duplicates heads)
372     ) p.deltas @
373      if List.exists (fun t -> [hd_of t] = List.map (fun x -> Some x) hd_of_div) p.conv
374      then hd_of_div else [] in
375   let showstoppers_step = sort_uniq showstoppers_step in
376   let showstoppers_eat =
377    let heads_and_arities =
378     List.sort (fun (k,_) (h,_) -> compare k h)
379      (filter_map (function `Var(k,_) -> Some (k,0) | `I((k,_),args) -> Some (k,Listx.length args) | _ -> None ) p.ps) in
380    let rec multiple_arities =
381     function
382        []
383      | [_] -> []
384      | (x,i)::(y,j)::tl when x = y && i <> j ->
385          x::multiple_arities tl
386      | _::tl -> multiple_arities tl in
387    multiple_arities heads_and_arities in
388
389   let showstoppers_eat = sort_uniq showstoppers_eat in
390   let showstoppers_eat = List.filter
391     (fun x -> not (List.mem x showstoppers_step))
392     showstoppers_eat in
393   List.iter (fun v -> prerr_endline ("DANGEROUS STEP: " ^ (string_of_var p.var_names) v)) showstoppers_step;
394   List.iter (fun v -> prerr_endline ("DANGEROUS EAT: " ^ (string_of_var p.var_names) v)) showstoppers_eat;
395   p, showstoppers_step, showstoppers_eat
396   ;;
397
398 let eat p =
399   let ({ps} as p), showstoppers_step, showstoppers_eat = critical_showstoppers p in
400   let showstoppers = showstoppers_step @ showstoppers_eat in
401   let heads = List.sort compare (filter_map hd_of ps) in
402   let arities = precompute_edible_data p (uniq heads) in
403   let showstoppers, showstoppers_conv =
404    edible p arities showstoppers in
405   let l = List.filter (fun (x,_,_) -> not (List.mem x showstoppers)) arities in
406   let p =
407   List.fold_left (fun p (x,pos,(xx : i_n_var)) -> if pos = -1 then p else
408    let n = match xx with `I(_,args) -> Listx.length args | _ -> 0 in
409    let v = `N(pos) in
410    let inst = make_lams v n in
411 prerr_endline ("# INST_IN_EAT: " ^ string_of_var p.var_names x ^ " := " ^ string_of_term p inst);
412    { p with sigma = p.sigma @ [x,inst] }
413    ) p l in
414   (* to avoid applied numbers in safe positions that
415      trigger assert failures subst_in_problem x inst p*)
416  let ps =
417   List.map (fun t ->
418    try
419     let _,j,_ = List.find (fun (h,_,_) -> hd_of t = Some h) l in
420     `N j
421    with Not_found -> t
422   ) ps in
423  let p = match p.div with
424   | None -> p
425   | Some div ->
426    if List.mem (hd_of_i_var div) showstoppers
427    then p
428    else
429     let n = match div with `I(_,args) -> Listx.length args | `Var _ -> 0 in
430     let p, bomb' = make_fresh_var p (-666) in
431     (if !bomb <> `Var (-1,-666) then
432      failwithProblem p
433       ("Bomb was duplicated! It was " ^ string_of_nf !bomb ^
434        ", tried to change it to " ^ string_of_nf bomb'));
435     bomb := bomb';
436     prerr_endline ("Just created bomb var: " ^ string_of_nf !bomb);
437     let x = hd_of_i_var div in
438     let inst = make_lams !bomb n in
439     let p = {p with div=None} in
440     (* subst_in_problem (hd_of_i_var div) inst p in *)
441      {p with sigma=p.sigma@[x,inst]} in
442      let dangerous_conv = showstoppers_conv in
443 let _ = prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
444 List.iter (fun l -> prerr_endline (String.concat " " (List.map (string_of_var p.var_names) l))) dangerous_conv; in
445  let conv =
446    List.map (function s,t ->
447     try
448      if s <> [] then t else (
449      (match t with | `Var _ -> raise Not_found | _ -> ());
450      let _ = List.find (fun h -> hd_of t = Some h) showstoppers in
451       t)
452     with Not_found -> match hd_of t with
453      | None -> assert (t = convergent_dummy); t
454      | Some h ->
455       prerr_endline ("FREEZING " ^ string_of_var p.var_names h);
456       convergent_dummy
457    ) (List.combine showstoppers_conv p.conv) in
458  List.iter
459   (fun bs ->
460     bs :=
461      List.map
462       (fun (n,t as res) ->
463         match List.nth ps n with
464            `N m -> m,t
465          | _ -> res
466       ) !bs
467   ) p.deltas ;
468  let old_conv = p.conv in
469  let p = { p with ps; conv } in
470  if l <> [] || old_conv <> conv
471   then prerr_endline (string_of_problem "eat" p);
472  if List.for_all (function `N _ -> true | _ -> false) ps && p.div = None then
473   `Finished p
474  else
475   `Continue p
476
477 let instantiate p x n =
478  (if hd_of_i_var (cast_to_i_var !bomb) = x
479    then failwithProblem p ("BOMB (" ^ string_of_nf !bomb ^ ") cannot be instantiated!"));
480  let arity_of_x = max_arity_tms x (all_terms p) in
481  (if arity_of_x = None then failwithProblem p "step on var non occurring in problem");
482  (if Util.option_get(arity_of_x) = min_int then failwithProblem p "step on fake variable");
483  (if Util.option_get(arity_of_x) <= 0 then failwithProblem p "step on var of non-positive arity");
484  let n = (prerr_endline "WARNING: using constant initialSpecialK"); p.initialSpecialK in
485  (* AC: Once upon a time, it was:
486     let arities = Num.compute_arities x (n+1) (all_terms p :> nf list) in *)
487  (* let arities = Array.to_list (Array.make (n+1) 0) in *)
488  let arities = Array.to_list (Array.make (n+1) min_int) in
489  let p,vars = make_fresh_vars p arities in
490  let args = Listx.from_list (vars :> nf list) in
491  let bs = ref [] in
492  (* 666, since it will be replaced anyway during subst: *)
493  let inst = `Lam(false,`Match(`I((0,min_int),Listx.map (lift 1) args),(x,-666),1,bs,[])) in
494  let p = {p with deltas=bs::p.deltas} in
495  subst_in_problem x inst p
496 ;;
497
498 let compute_special_k tms =
499  let rec aux k (t: nf) = Pervasives.max k (match t with
500  | `Lam(b,t) -> aux (k + if b then 1 else 0) t
501  | `I(n, tms) -> Listx.max (Listx.map (aux 0) tms)
502  | `Match(t, _, liftno, bs, args) ->
503      List.fold_left max 0 (List.map (aux 0) ((t :> nf)::args@List.map snd !bs))
504  | `N _
505  | `Var _ -> 0
506  ) in Listx.max (Listx.map (aux 0) tms)
507 ;;
508
509 let auto_instantiate (n,p) =
510  let p, showstoppers_step, showstoppers_eat = critical_showstoppers p in
511  let x =
512   match showstoppers_step, showstoppers_eat with
513   | [], y::_ ->
514      prerr_endline ("INSTANTIATING CRITICAL TO EAT " ^ string_of_var p.var_names y); y
515   | [], [] ->
516      let heads =
517       (* Choose only variables still alive (with arity > 0) *)
518       List.sort compare (filter_map (
519        fun t -> match t with `Var _ -> None | x -> if arity_of_hd x <= 0 then None else hd_of x
520       ) ((match p.div with Some t -> [(t :> i_n_var)] | _ -> []) @ p.ps)) in
521      (match heads with
522       | [] ->
523          (try
524            fst (List.find (((<) 0) ++ snd) (concat_map free_vars' (p.conv :> nf list)))
525           with
526            Not_found -> assert false)
527       | x::_ ->
528          prerr_endline ("INSTANTIATING TO EAT " ^ string_of_var p.var_names x);
529          x)
530   | x::_, _ ->
531       prerr_endline ("INSTANTIATING " ^ string_of_var p.var_names x);
532       x in
533 (* Strategy that  decreases the special_k to 0 first (round robin)
534 1:11m42 2:14m5 3:11m16s 4:14m46s 5:12m7s 6:6m31s *)
535  let x =
536   try
537    match
538     hd_of (List.find (fun t ->
539      compute_special_k (Listx.Nil (t :> nf)) > 0 && arity_of_hd t > 0
540      ) (all_terms p))
541    with
542     | None -> assert false
543     | Some x ->
544        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var p.var_names x);
545        x
546   with
547    Not_found ->
548     let arity_of_x = max_arity_tms x (all_terms p) in
549     assert (Util.option_get arity_of_x > 0);
550     x in
551 (* Instantiate in decreasing order of compute_special_k
552 1:15m14s 2:13m14s 3:4m55s 4:4m43s 5:4m34s 6:6m28s 7:3m31s
553 let x =
554  try
555   (match hd_of (snd (List.hd (List.sort (fun c1 c2 -> - compare (fst c1) (fst c2)) (filter_map (function `I _ as t -> Some (compute_special_k (Listx.Nil (t :> nf)),t) | _ -> None) (all_terms p))))) with
556       None -> assert false
557     | Some x ->
558        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var x);
559        x)
560  with
561   Not_found -> x
562 in*)
563  let special_k =
564      compute_special_k (Listx.from_list (all_terms p :> nf list) )in
565  if special_k < n then
566   prerr_endline ("@@@@ NEW INSTANTIATE PHASE (" ^ string_of_int special_k ^ ") @@@@");
567  let p = instantiate p x special_k in
568  special_k,p
569
570
571 let rec auto_eat (n,p) =
572  prerr_endline "{{{{{{{{ Computing measure before auto_instantiate }}}}}}";
573  let m = problem_measure p in
574  let (n,p') = auto_instantiate (n,p) in
575  match eat p' with
576  | `Finished p -> p
577  | `Continue p ->
578      prerr_endline "{{{{{{{{ Computing measure inafter auto_instantiate }}}}}}";
579      let delta = problem_measure p - m in
580      (* let delta = m - problem_measure p' in *)
581      if delta >= 0
582       then
583        (failwith
584        ("Measure did not decrease (+=" ^ string_of_int delta ^ ")"))
585       else prerr_endline ("$ Measure decreased of " ^ string_of_int delta);
586      auto_eat (n,p)
587 ;;
588
589 let auto p n =
590  prerr_endline ("@@@@ FIRST INSTANTIATE PHASE (" ^ string_of_int n ^ ") @@@@");
591  match eat p with
592  | `Finished p -> p
593  | `Continue p -> auto_eat (n,p)
594 ;;
595
596 (*
597 0 = snd
598
599       x y = y 0    a y = k  k z = z 0  c y = k   y u = u h1 h2 0          h2 a = h3
600 1 x a c    1 a 0 c  1 k c    1 c 0      1 k        1 k                     1 k
601 2 x a y    2 a 0 y  2 k y    2 y 0      2 y 0      2 h2 0                  2 h3
602 3 x b y    3 b 0 y  3 b 0 y  3 b 0 y    3 b 0 y    3 b 0 (\u. u h1 h2 0)   3 b 0 (\u. u h1 (\w.h3) 0)
603 4 x b c    4 b 0 c  4 b 0 c  4 b 0 c    4 b 0 c    4 b 0 c                 4 b 0 c
604 5 x (b e)  5 b e 0  5 b e 0  5 b e 0    5 b e 0    5 b e 0                 5 b e 0
605 6 y y      6 y y    6 y y    6 y y      6 y y      6 h1 h1 h2 0 h2 0       6 h1 h1 (\w. h3) 0 (\w. h3) 0
606
607                                 l2 _ = l3
608 b u = u l1 l2 0                 e _ _ _ _ = f                         l3 n = n j 0
609 1 k                             1 k                                  1 k
610 2 h3                            2 h3                                 2 h3
611 3 l2 0 (\u. u h1 (\w. h3) 0)    3 l3 (\u. u h1 (\w. h3) 0)           3 j h1 (\w. h3) 0 0
612 4 l2 0 c                        4 l3 c                               4 c j 0
613 5 e l1 l2 0 0                   5 f                                  5 f
614 6 h1 h1 (\w. h3) 0 (\w. h3) 0   6 h1 h1 (\w. h3) 0 (\w. h3) 0        6 h1 h1 (\w. h3) 0 (\w. h3) 0
615 *)
616
617 (*
618                 x n = n 0 ?
619 x a (b (a c))   a 0 = 1 ? (b (a c))   8
620 x a (b d')      a 0 = 1 ? (b d')      7
621 x b (a c)       b 0 = 1 ? (a c)       4
622 x b (a c')      b 0 = 1 ? (a c')      5
623
624 c = 2
625 c' = 3
626 a 2 = 4  (* a c *)
627 a 3 = 5  (* a c' *)
628 d' = 6
629 b 6 = 7  (* b d' *)
630 b 4 = 8  (* b (a c) *)
631 b 0 = 1
632 a 0 = 1
633 *)
634
635 (************** Tests ************************)
636
637 let optimize_numerals p =
638   let replace_in_sigma perm =
639     let rec aux = function
640     | `N n -> `N (List.nth perm n)
641     | `I _ -> assert false
642     | `Var _ as t -> t
643     | `Lam(v,t) -> `Lam(v, aux t)
644     | `Match(_,_,_,bs,_) as t -> (bs := List.map (fun (n,t) -> (List.nth perm n, t)) !bs); t
645     in List.map (fun (n,t) -> (n,aux t))
646   in
647   let deltas' = List.mapi (fun n d -> (n, List.map fst !d)) p.deltas in
648   let maxs = Array.to_list (Array.init (List.length deltas') (fun _ -> 0)) in
649   let max = List.fold_left max 0 (concat_map snd deltas') in
650   let perm,_ = List.fold_left (fun (perm, maxs) (curr_n:int) ->
651       let containing = filter_map (fun (i, bs) -> if List.mem curr_n bs then Some i else None) deltas' in
652       (* (prerr_endline (string_of_int curr_n ^ " occurs in: " ^ (String.concat " " (List.map string_of_int containing)))); *)
653       let neww = List.fold_left Pervasives.max 0 (List.mapi (fun n max -> if List.mem n containing then max else 0) maxs) in
654       let maxs = List.mapi (fun i m -> if List.mem i containing then neww+1 else m) maxs in
655       (neww::perm, maxs)
656     ) ([],maxs) (Array.to_list (Array.init (max+1) (fun x -> x))) in
657   replace_in_sigma (List.rev perm) p.sigma
658 ;;
659
660 let env_of_sigma freshno sigma should_explode =
661  let rec aux n =
662   if n > freshno then
663    []
664   else
665    let e = aux (n+1) in
666    (try
667     e,Pure.lift (-n-1) (snd (List.find (fun (i,_) -> i = n) sigma)),[]
668    with
669     Not_found ->
670      if should_explode && n = hd_of_i_var (cast_to_i_var !bomb)
671       then ([], (let f t = Pure.A(t,t) in f (Pure.L (f (Pure.V 0)))), [])
672       else ([],Pure.V n,[]))::e
673  in aux 0
674 ;;
675 (* ************************************************************************** *)
676
677 type result = [
678  | `Separable of (int * Num.nf) list
679  | `Unseparable of string
680 ]
681
682 let check p =
683  (* TODO check if there are duplicates in p.ps
684      before it was: ps = sort_uniq ~compare:eta_compare (ps :> nf list) *)
685  (* FIXME what about initial fragments? *)
686  if (let rec f = function
687      | [] -> false
688      | hd::tl -> List.exists (eta_eq hd) tl || f tl in
689    f p.ps)
690   then Some "ps contains duplicate entries"
691  (* check if div occurs somewhere in ps@conv *)
692  else match p.div with
693   | None -> None
694   | Some div ->
695      if (List.exists (eta_subterm div) (p.ps@p.conv))
696       then Some "div occurs as subterm in ps or conv"
697       else None
698 ;;
699
700 let solve p =
701  prerr_endline (string_of_problem "main" p);
702  match check p with
703  | Some s -> `Unseparable s
704  | None ->
705  bomb := `Var(-1,-666);
706  Console.print_hline();
707  let p_finale = auto p p.initialSpecialK in
708  let freshno,sigma = p_finale.freshno, p_finale.sigma in
709  prerr_endline ("------- <DONE> ------ measure=. \n ");
710  List.iter (fun (x,inst) -> prerr_endline
711  (string_of_var p_finale.var_names x ^ " := " ^ string_of_term p_finale inst)) sigma;
712
713  prerr_endline "---------<OPT>----------";
714  let sigma = optimize_numerals p_finale in (* optimize numerals *)
715  List.iter (fun (x,inst) -> prerr_endline
716   (string_of_var p_finale.var_names x ^ " := " ^ string_of_term p_finale inst)) sigma;
717
718  prerr_endline "---------<PURE>---------";
719  let scott_of_nf t = ToScott.t_of_nf (t :> nf) in
720  let div = option_map scott_of_nf p.div in
721  let conv = List.map scott_of_nf p.conv in
722  let ps = List.map scott_of_nf p.ps in
723
724  let sigma' = List.map (fun (x,inst) -> x, scott_of_nf inst) sigma in
725  let e' = env_of_sigma freshno sigma' false (* FIXME shoudl_explode *) in
726
727  prerr_endline "--------<REDUCE>---------";
728  let pure_bomb = ToScott.t_of_nf (!bomb) in (* Pure.B *)
729  (function
730    | Some div ->
731       print_endline (Pure.print div);
732       let t = Pure.mwhd (e',div,[]) in
733       prerr_endline ("*:: " ^ (Pure.print t));
734       assert (t = pure_bomb)
735    | None -> ()) div;
736  List.iter (fun n ->
737   verbose ("_::: " ^ (Pure.print n));
738   let t = Pure.mwhd (e',n,[]) in
739   verbose ("_:: " ^ (Pure.print t));
740   assert (t <> pure_bomb)
741  ) conv ;
742  List.iteri (fun i n ->
743   verbose ((string_of_int i) ^ "::: " ^ (Pure.print n));
744   let t = Pure.mwhd (e',n,[]) in
745   verbose ((string_of_int i) ^ ":: " ^ (Pure.print t));
746   assert (t = Scott.mk_n i)
747  ) ps ;
748  prerr_endline "-------- </DONE> --------";
749  `Separable p_finale.sigma
750 ;;
751
752 let problem_of (label, div, conv, ps, var_names) =
753  (* TODO: replace div with bottom in problem??? *)
754  let all_tms = (match div with None -> [] | Some div -> [(div :> i_n_var)]) @ ps @ conv in
755  if all_tms = [] then failwith "problem_of: empty problem";
756  let initialSpecialK = compute_special_k (Listx.from_list (all_tms :> nf list)) in
757  let freshno = List.length var_names in
758  let deltas =
759   let dummy = `Var (max_int / 2, -666) in
760    [ ref (Array.to_list (Array.init (List.length ps) (fun i -> i, dummy))) ] in
761  {freshno; div; conv; ps; sigma=[]; deltas; initialSpecialK; var_names; label}
762 ;;