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