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