This repository was archived by the owner on Dec 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpysimpl.ml
More file actions
82 lines (73 loc) · 2.12 KB
/
pysimpl.ml
File metadata and controls
82 lines (73 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
open Pythonlib.Simpl
open Pythonlib.Ast
let tmp_prefix = "__"
let is_tmpid =
let len = String.length tmp_prefix in
fun x ->
let l = String.length x in
let rec d i =
if i>=l then true
else
if i>=len then
(match x.[i] with
| '0'..'9' -> d (i+1)
| _ -> false)
else
(x.[i] = tmp_prefix.[i]) && d (i+1) in
d 0
let list_count f =
let rec c n = function
| [] -> n
| hd :: tl -> c (if f hd then n+1 else n) tl
in
c 0
let preferred a b =
let f x =
match x with
| Name(x, Param, _) -> is_tmpid x
| _ -> assert false in
let fst (x, _, _, _) = x in
let score_a = list_count f (fst a) in
let score_b = list_count f (fst b) in
if score_a > score_b then b else a
let same_args formal effective kw star kwargs =
kw=[]
&& star=None
&& kwargs=None
&& match formal with
| (formal, None, None, []) ->
let is_in n =
let rec loop l =
match l with
| [] -> false
| Name(m, _, _) :: tl -> n=m || loop tl
| _ :: tl -> loop tl in
loop in
let rec s f e =
match f with
| [] -> e=[]
| Name(n, Param, _) :: tlf when not(is_in n tlf) ->
(match e with
| Name(n', Load, _) :: tle when n=n' -> s tlf tle
| _ -> false)
| _ -> false in
s formal effective
| _ -> false
let se = function
| Lambda(args,
Call(Lambda(args', body', al'), eargs, kw, star, kwargs, ac), al)
when same_args args eargs kw star kwargs
-> Some (Lambda(preferred args args', body', al'))
| _ -> None
let ss = function
| FunctionDef(id, args,
[Return(Some(Call(Lambda(args', body', al), eargs, kw, star, kwargs, ac)), ar)], deco, af)
when same_args args eargs kw star kwargs
-> Some (FunctionDef(id, preferred args args',
[Return(Some(body'), ar)], deco, af))
| _ -> None
let s = {
simpl_expr = Some se;
simpl_stmt = Some ss }
let () =
Pythonlib.Pretty.print_mod (simpl s (Pythonlib.Parser2.parse_from_channel stdin))