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