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