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