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