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