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