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