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