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