]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/simple.ml
079774e5ac67e5c53feaa53eca9e7e622dd77c76
[fireball-separation.git] / ocaml / simple.ml
1 let (++) f g x = f (g x);;\r
2 let id x = x;;\r
3 let rec fold_nat f x n = if n = 0 then x else f (fold_nat f x (n-1)) n ;;\r
4 \r
5 let print_hline = Console.print_hline;;\r
6 \r
7 open Pure\r
8 \r
9 type var = int;;\r
10 type t =\r
11  | V of var\r
12  | A of t * t\r
13  | L of (t * t list (*garbage*))\r
14  | C (* constant *)\r
15 ;;\r
16 \r
17 let delta = L(A(V 0, V 0),[]);;\r
18 \r
19 let rec is_stuck = function\r
20  | C -> true\r
21  | A(t,_) -> is_stuck t\r
22  | _ -> false\r
23 ;;\r
24 \r
25 let eta_eq' =\r
26  let rec aux l1 l2 t1 t2 = match t1, t2 with\r
27   | _, _ when is_stuck t1 || is_stuck t2 -> true\r
28   | L t1, L t2 -> aux l1 l2 (fst t1) (fst t2)\r
29   | L t1, t2 -> aux l1 (l2+1) (fst t1) t2\r
30   | t1, L t2 -> aux (l1+1) l2 t1 (fst t2)\r
31   | V a, V b -> a + l1 = b + l2\r
32   | A(t1,t2), A(u1,u2) -> aux l1 l2 t1 u1 && aux l1 l2 t2 u2\r
33   | _, _ -> false\r
34  in aux ;;\r
35 let eta_eq = eta_eq' 0 0;;\r
36 \r
37 (* is arg1 eta-subterm of arg2 ? *)\r
38 let eta_subterm u =\r
39  let rec aux lev t = if t = C then false else (eta_eq' lev 0 u t || match t with\r
40  | L(t,g) -> List.exists (aux (lev+1)) (t::g)\r
41  | A(t1, t2) -> aux lev t1 || aux lev t2\r
42  | _ -> false) in\r
43  aux 0\r
44 ;;\r
45 \r
46 (* does NOT lift the argument *)\r
47 let mk_lams = fold_nat (fun x _ -> L(x,[])) ;;\r
48 \r
49 let string_of_t =\r
50   let string_of_bvar =\r
51    let bound_vars = ["x"; "y"; "z"; "w"; "q"] in\r
52    let bvarsno = List.length bound_vars in\r
53    fun nn -> if nn < bvarsno then List.nth bound_vars nn else "x" ^ (string_of_int (nn - bvarsno + 1)) in\r
54   let rec string_of_term_w_pars level = function\r
55     | V v -> if v >= level then "`" ^ string_of_int (v-level) else\r
56        string_of_bvar (level - v-1)\r
57     | C -> "C"\r
58     | A _\r
59     | L _ as t -> "(" ^ string_of_term_no_pars level t ^ ")"\r
60   and string_of_term_no_pars_app level = function\r
61     | A(t1,t2) -> string_of_term_no_pars_app level t1 ^ " " ^ string_of_term_w_pars level t2\r
62     | _ as t -> string_of_term_w_pars level t\r
63   and string_of_term_no_pars level = function\r
64     | L(t,g) -> "λ" ^ string_of_bvar level ^ ". " ^ string_of_term_no_pars (level+1) t\r
65        ^ (if g = [] then "" else String.concat ", " ("" :: List.map (string_of_term_w_pars (level+1)) g))\r
66     | _ as t -> string_of_term_no_pars_app level t\r
67   in string_of_term_no_pars 0\r
68 ;;\r
69 \r
70 type problem = {\r
71    orig_freshno: int\r
72  ; freshno : int\r
73  ; label : string\r
74  ; div : t\r
75  ; conv : t\r
76  ; sigma : (var * t) list (* substitutions *)\r
77 }\r
78 \r
79 let string_of_problem p =\r
80  let lines = [\r
81   "[DV] " ^ string_of_t p.div;\r
82   "[CV] " ^ string_of_t p.conv;\r
83  ] in\r
84  String.concat "\n" lines\r
85 ;;\r
86 \r
87 exception B;;\r
88 exception Done of (var * t) list (* substitution *);;\r
89 exception Unseparable of string;;\r
90 exception Backtrack of string;;\r
91 \r
92 let rec try_all label f = function\r
93  | x::xs -> (try f x with Backtrack _ -> try_all label f xs)\r
94  | [] -> raise (Backtrack label)\r
95 ;;\r
96 \r
97 let problem_fail p reason =\r
98  print_endline "!!!!!!!!!!!!!!! FAIL !!!!!!!!!!!!!!!";\r
99  print_endline (string_of_problem p);\r
100  failwith reason\r
101 ;;\r
102 \r
103 let freshvar ({freshno} as p) =\r
104  {p with freshno=freshno+1}, freshno+1\r
105 ;;\r
106 \r
107 (* CSC: rename? is an applied C an inert?\r
108    is_inert and get_inert work inconsistently *)\r
109 let rec is_inert =\r
110  function\r
111  | A(t,_) -> is_inert t\r
112  | V _ -> true\r
113  | C\r
114  | L _ -> false\r
115 ;;\r
116 \r
117 let rec is_constant =\r
118  function\r
119     C -> true\r
120   | V _ -> false\r
121   | A(t,_)\r
122   | L(t,_) -> is_constant t\r
123 ;;\r
124 \r
125 let rec get_inert = function\r
126  | V _ | C as t -> (t,0)\r
127  | A(t, _) -> let hd,args = get_inert t in hd,args+1\r
128  | _ -> assert false\r
129 ;;\r
130 \r
131 let args_of_inert =\r
132  let rec aux acc =\r
133   function\r
134    | V _ | C -> acc\r
135    | A(t, a) -> aux (a::acc) t\r
136    | _ -> assert false\r
137  in\r
138   aux []\r
139 ;;\r
140 \r
141 (* precomputes the number of leading lambdas in a term,\r
142    after replacing _v_ w/ a term starting with n lambdas *)\r
143 let rec no_leading_lambdas v n = function\r
144  | L(t,_) -> 1 + no_leading_lambdas (v+1) n t\r
145  | A _ as t -> let v', m = get_inert t in if V v = v' then max 0 (n - m) else 0\r
146  | V v' -> if v = v' then n else 0\r
147  | C -> 0\r
148 ;;\r
149 \r
150 let rec subst level delift sub =\r
151  function\r
152  | V v -> (if v = level + fst sub then lift level (snd sub) else V (if delift && v > level then v-1 else v)), []\r
153  | L x -> let t, g = subst_in_lam (level+1) delift sub x in L(t, g), []\r
154  | A (t1,t2) ->\r
155   let t1, g1 = subst level delift sub t1 in\r
156   let t2, g2 = subst level delift sub t2 in\r
157   let t3, g3 = mk_app t1 t2 in\r
158   t3, g1 @ g2 @ g3\r
159  | C -> C, []\r
160 and subst_in_lam level delift sub (t, g) =\r
161   let t', g' = subst level delift sub t in\r
162   let g'' = List.fold_left\r
163    (fun xs t ->\r
164      let x,y = subst level delift sub t in\r
165      (x :: y @ xs)) g' g in t', g''\r
166 and mk_app t1 t2 = if t1 = delta && t2 = delta then raise B\r
167  else match t1 with\r
168  | L x -> subst_in_lam 0 true (0, t2) x\r
169  | _ -> A (t1, t2), []\r
170 and lift n =\r
171  let rec aux lev =\r
172   function\r
173   | V m -> V (if m >= lev then m + n else m)\r
174   | L(t,g) -> L (aux (lev+1) t, List.map (aux (lev+1)) g)\r
175   | A (t1, t2) -> A (aux lev t1, aux lev t2)\r
176   | C -> C\r
177  in aux 0\r
178 ;;\r
179 let subst = subst 0 false;;\r
180 \r
181 let subst_in_problem ((v, t) as sub) p =\r
182 print_endline ("-- SUBST " ^ string_of_t (V v) ^ " |-> " ^ string_of_t t);\r
183  let sigma = sub :: p.sigma in\r
184  let div, g = try subst sub p.div with B -> raise (Done sigma) in\r
185  assert (g = []);\r
186  let conv, f = try subst sub p.conv with B -> raise (Backtrack "p.conv diverged") in\r
187  assert (g = []);\r
188  {p with div; conv; sigma}\r
189 ;;\r
190 \r
191 let get_subterms_with_head hd_var =\r
192  let rec aux lev inert_done g = function\r
193  | L(t,g') -> List.fold_left (aux (lev+1) false) g (t::g')\r
194  | C | V _ -> g\r
195  | A(t1,t2) as t ->\r
196    let hd_var', n_args' = get_inert t1 in\r
197    if not inert_done && hd_var' = V (hd_var + lev)\r
198     then lift ~-lev t :: aux lev false (aux lev true g t1) t2\r
199     else                 aux lev false (aux lev true g t1) t2\r
200  in aux 0 false []\r
201 ;;\r
202 \r
203 let purify =\r
204  let rec aux = function\r
205  | L(t,g) ->\r
206     let t = aux (lift (List.length g) t) in\r
207     let t = List.fold_left (fun t g -> Pure.A(Pure.L t, aux g)) t g in\r
208     Pure.L t\r
209  | A (t1,t2) -> Pure.A (aux t1, aux t2)\r
210  | V n -> Pure.V (n)\r
211  | C -> Pure.V (min_int/2)\r
212  in aux\r
213 ;;\r
214 \r
215 let check p sigma =\r
216  print_endline "Checking...";\r
217  let div = purify p.div in\r
218  let conv = purify p.conv in\r
219  let sigma = List.map (fun (v,t) -> v, purify t) sigma in\r
220  let freshno = List.fold_right (max ++ fst) sigma 0 in\r
221  let env = Pure.env_of_sigma freshno sigma in\r
222  (if not (Pure.diverged (Pure.mwhd (env,div,[])))\r
223   then failwith "D converged in Pure");\r
224  print_endline "- D diverged.";\r
225  (if Pure.diverged (Pure.mwhd (env,conv,[]))\r
226   then failwith "C diverged in Pure");\r
227  print_endline "- C converged.";\r
228  ()\r
229 ;;\r
230 \r
231 let sanity p =\r
232  print_endline (string_of_problem p); (* non cancellare *)\r
233  if not (is_inert p.div) then raise (Backtrack "p.div converged");\r
234  (* Trailing constant args can be removed because do not contribute to eta-diff *)\r
235  let rec remove_trailing_constant_args = function\r
236  | A(t1, t2) when is_constant t2 -> remove_trailing_constant_args t1\r
237  | _ as t -> t in\r
238  let p = {p with div=remove_trailing_constant_args p.div} in\r
239  p\r
240 ;;\r
241 \r
242 (* drops the arguments of t after the n-th *)\r
243 let inert_cut_at n t =\r
244  let rec aux t =\r
245   match t with\r
246   | V _ as t -> 0, t\r
247   | A(t1,_) as t ->\r
248     let k', t' = aux t1 in\r
249      if k' = n then n, t'\r
250       else k'+1, t\r
251   | _ -> assert false\r
252  in snd (aux t)\r
253 ;;\r
254 \r
255 (* return the index of the first argument with a difference\r
256    (the first argument is 0) *)\r
257 let find_eta_difference p t =\r
258  let divargs = args_of_inert p.div in\r
259  let conargs = args_of_inert t in\r
260  let rec range i j =\r
261   if j = -1 then [] else i :: range (i+1) (j-1) in\r
262  let rec aux k divargs conargs =\r
263   match divargs,conargs with\r
264      [],conargs -> range k (List.length conargs)\r
265    | _::_,[] -> [k]\r
266    | t1::divargs,t2::conargs ->\r
267       (if not (eta_eq t1 t2) then [k] else []) @ aux (k+1) divargs conargs\r
268  in\r
269   aux 0 divargs conargs\r
270 ;;\r
271 \r
272 let compute_max_lambdas_at hd_var j =\r
273  let rec aux hd = function\r
274  | A(t1,t2) ->\r
275     (if get_inert t1 = (V hd, j)\r
276       then max ( (*FIXME*)\r
277        if is_inert t2 && let hd', j' = get_inert t2 in hd' = V hd\r
278         then let hd', j' = get_inert t2 in j - j'\r
279         else no_leading_lambdas hd_var j t2)\r
280       else id) (max (aux hd t1) (aux hd t2))\r
281  | L(t,_) -> aux (hd+1) t\r
282  | V _ | C -> 0\r
283  in aux hd_var\r
284 ;;\r
285 \r
286 let print_cmd s1 s2 = print_endline (">> " ^ s1 ^ " " ^ s2);;\r
287 \r
288 (* returns Some i if i is the smallest integer s.t. p holds for the i-th\r
289    element of the list in input *)\r
290 let smallest_such_that p =\r
291  let rec aux i =\r
292   function\r
293      [] -> None\r
294    | hd::_ when (print_endline (string_of_t hd) ; p hd) -> Some i\r
295    | _::tl -> aux (i+1) tl\r
296  in\r
297   aux 0\r
298 ;;\r
299 \r
300 (* step on the head of div, on the k-th argument, with n fresh vars *)\r
301 let step k n p =\r
302  let hd, _ = get_inert p.div in\r
303  match hd with\r
304  | C | L _ | A _  -> assert false\r
305  | V var ->\r
306 print_cmd "STEP" ("on " ^ string_of_t (V var) ^ " (on " ^ string_of_int (k+1) ^ "th)");\r
307  let p, t = (* apply fresh vars *)\r
308   fold_nat (fun (p, t) _ ->\r
309     let p, v = freshvar p in\r
310     p, A(t, V (v + k + 1))\r
311   ) (p, V 0) n in\r
312  let t = (* apply unused bound variables V_{k-1}..V_1 *)\r
313   fold_nat (fun t m -> A(t, V (k-m+1))) t k in\r
314  let t = mk_lams t (k+1) in (* make leading lambdas *)\r
315  let subst = var, t in\r
316  let p = subst_in_problem subst p in\r
317  sanity p\r
318 ;;\r
319 \r
320 let finish p =\r
321  (* one-step version of eat *)\r
322  let compute_max_arity =\r
323    let rec aux n = function\r
324    | A(t1,t2) -> max (aux (n+1) t1) (aux 0 t2)\r
325    | L(t,g) -> List.fold_right (max ++ (aux 0)) (t::g) 0\r
326    | _ -> n\r
327  in aux 0 in\r
328 print_cmd "FINISH" "";\r
329  (* First, a step on the last argument of the divergent.\r
330     Because of the sanity check, it will never be a constant term. *)\r
331  let div_hd, div_nargs = get_inert p.div in\r
332  let div_hd = match div_hd with V n -> n | _ -> assert false in\r
333  let j = div_nargs - 1 in\r
334  let arity = compute_max_arity p.conv in\r
335  let n = 1 + arity + max\r
336   (compute_max_lambdas_at div_hd j p.div)\r
337   (compute_max_lambdas_at div_hd j p.conv) in\r
338  let p = step j n p in\r
339  (* Now, find first argument of div that is a variable never applied anywhere.\r
340  It must exist because of some invariant, since we just did a step,\r
341  and because of the arity of the divergent *)\r
342  let div_hd, div_nargs = get_inert p.div in\r
343  let div_hd = match div_hd with V n -> n | _ -> assert false in\r
344  let rec aux m = function\r
345  | A(t, V delta_var) ->\r
346    if delta_var <> div_hd && get_subterms_with_head delta_var p.conv = []\r
347    then m, delta_var\r
348    else aux (m-1) t\r
349  | A(t,_) -> aux (m-1) t\r
350  | _ -> assert false in\r
351  let m, delta_var = aux div_nargs p.div in\r
352  let p = subst_in_problem (delta_var, delta) p in\r
353  let p = subst_in_problem (div_hd, mk_lams delta (m-1)) p in\r
354  sanity p\r
355 ;;\r
356 \r
357 let auto p =\r
358  let rec aux p =\r
359  let hd, n_args = get_inert p.div in\r
360  match hd with\r
361  | C | L _ | A _  -> assert false\r
362  | V hd_var ->\r
363  let tms = get_subterms_with_head hd_var p.conv in\r
364  if List.exists (fun t -> snd (get_inert t) >= n_args) tms\r
365   then (\r
366     (* let tms = List.sort (fun t1 t2 -> - compare (snd (get_inert t1)) (snd (get_inert t2))) tms in *)\r
367     try_all "no similar terms" (fun t ->\r
368       let js = find_eta_difference p t in\r
369       (* print_endline (String.concat ", " (List.map string_of_int js)); *)\r
370       let js = List.rev js in\r
371        try_all "no eta difference"\r
372         (fun j ->\r
373           let k = 1 + max\r
374            (compute_max_lambdas_at hd_var j p.div)\r
375             (compute_max_lambdas_at hd_var j p.conv) in\r
376           aux (step j k p)) js) tms\r
377    )\r
378   else\r
379     problem_fail (finish p) "Finish did not complete the problem"\r
380   in\r
381   try\r
382    aux p\r
383   with Done sigma -> sigma\r
384 ;;\r
385 \r
386 let problem_of (label, div, convs, ps, var_names) =\r
387  print_hline ();\r
388  let rec aux lev = function\r
389  | `Lam(_, t, g) -> L (aux (lev+1) t, List.map (aux (lev+1)) g)\r
390  | `I (v, args) -> Listx.fold_left (fun x y -> fst (mk_app x (aux lev y))) (aux lev (`Var v)) args\r
391  | `Var(v,_) -> if v >= lev && List.nth var_names (v-lev) = "C" then C else V v\r
392  | `N _ | `Match _ -> assert false in\r
393  assert (List.length ps = 0);\r
394  let convs = List.rev convs in\r
395  let conv = List.fold_left (fun x y -> fst (mk_app x (aux 0 (y :> Num.nf)))) (V (List.length var_names)) convs in\r
396  let var_names = "@" :: var_names in\r
397  let div = match div with\r
398  | Some div -> aux 0 (div :> Num.nf)\r
399  | None -> assert false in\r
400  let varno = List.length var_names in\r
401  {orig_freshno=varno; freshno=1+varno; div; conv; sigma=[]; label}\r
402 ;;\r
403 \r
404 let solve p =\r
405  let c = if String.length p.label > 0 then String.sub (p.label) 0 1 else "" in\r
406  let module M = struct exception Okay end in\r
407  try\r
408   if eta_subterm p.div p.conv\r
409   then raise (Unseparable "div is subterm of conv")\r
410   else\r
411    let p = sanity p (* initial sanity check *) in\r
412    check p (auto p);\r
413    raise M.Okay\r
414  with\r
415   | M.Okay -> if c = "?" then\r
416     failwith "The problem succeeded, but was supposed to be unseparable"\r
417   | e when c = "!" ->\r
418     failwith ("The problem was supposed to be separable, but: "^Printexc.to_string e)\r
419   | e ->\r
420     print_endline ("The problem failed, as expected ("^Printexc.to_string e^")")\r
421 ;;\r
422 \r
423 Problems.main (solve ++ problem_of);\r
424 \r
425 (* Example usage of interactive: *)\r
426 \r
427 (* let interactive div conv cmds =\r
428  let p = problem_of div conv in\r
429  try (\r
430  let p = List.fold_left (|>) p cmds in\r
431  let rec f p cmds =\r
432   let nth spl n = int_of_string (List.nth spl n) in\r
433   let read_cmd () =\r
434    let s = read_line () in\r
435    let spl = Str.split (Str.regexp " +") s in\r
436    s, let uno = List.hd spl in\r
437     try if uno = "eat" then eat\r
438     else if uno = "step" then step (nth spl 1) (nth spl 2)\r
439     else failwith "Wrong input."\r
440     with Failure s -> print_endline s; (fun x -> x) in\r
441   let str, cmd = read_cmd () in\r
442   let cmds = (" " ^ str ^ ";")::cmds in\r
443   try\r
444    let p = cmd p in f p cmds\r
445   with\r
446   | Done _ -> print_endline "Done! Commands history: "; List.iter print_endline (List.rev cmds)\r
447  in f p []\r
448  ) with Done _ -> ()\r
449 ;; *)\r
450 \r
451 (* interactive "x y"\r
452  "@ (x x) (y x) (y z)" [step 0 1; step 0 2; eat]\r
453 ;; *)\r