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