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