|
1 | 1 | module PyGen |
2 | 2 |
|
3 | | -export @pygen |
4 | | -#= |
5 | | - @pygen is a macro that allows for python like generator functions. |
6 | | -The idea is that a function like this: |
7 | | -
|
8 | | -function f(args) |
9 | | - ... |
10 | | - yield x |
11 | | - ... |
12 | | - yield y |
13 | | - ... |
14 | | -end |
15 | | -
|
16 | | -should become.... |
17 | | -
|
18 | | -function f(args) |
19 | | - function γ(c::Channel) |
20 | | - ... |
21 | | - put!(c, x) |
22 | | - ... |
23 | | - put!(c, y) |
24 | | - ... |
25 | | - end |
26 | | - return Channel(γ) |
27 | | -end |
28 | | -=# |
29 | | - |
30 | | -const yregex = r"(yield .*)" |
31 | | - |
32 | | - |
33 | | -function asput(str) |
34 | | - # Convert "yield λ" to "put!(c, λ) |
35 | | - λ = replace(str, "yield ", "") |
36 | | - return "put!(c, $λ)" |
37 | | -end |
38 | | - |
| 3 | +using MacroTools |
39 | 4 |
|
| 5 | +export @pygen |
40 | 6 | """ |
41 | 7 | @pygen |
42 | 8 |
|
43 | 9 | Making julie walking a little *more* like python. Stick |
44 | 10 | the @pygen macro in front of a function declaration and |
45 | 11 | you can use `yield` statements to make a python style |
46 | | -generator! |
| 12 | +generator! |
| 13 | +
|
| 14 | +## Examples |
| 15 | +
|
| 16 | +```julia |
| 17 | +julia> @pygen function fibonacci() |
| 18 | + n, m = 0, 1 |
| 19 | + while true |
| 20 | + yield(m) |
| 21 | + n, m = m, n + m |
| 22 | + end |
| 23 | + end |
| 24 | +fibonacci (generic function with 1 method) |
| 25 | +
|
| 26 | +julia> for n in fibonacci() |
| 27 | + println(n) |
| 28 | + sleep(1) |
| 29 | + end |
| 30 | +1 |
| 31 | +1 |
| 32 | +2 |
| 33 | +3 |
| 34 | +5 |
| 35 | +8 |
| 36 | +13 |
| 37 | +. |
| 38 | +. |
| 39 | +. |
| 40 | +``` |
47 | 41 | """ |
48 | 42 | macro pygen(f) |
49 | | - f′ = replace(f, yregex, asput) |
50 | | - lines = f′ |> IOBuffer |> readlines |
51 | | - ind = findfirst(x -> contains(x, "function"), lines) |
52 | | - insert!(lines, ind + 1, "function γ(c::Channel)") |
53 | | - push!(lines, "return Channel(γ)\nend") |
54 | | - return join(lines, "\n") |> parse |> esc |
| 43 | + |
| 44 | + # generate a new symbol for the channel name and |
| 45 | + # wrapper function |
| 46 | + c = gensym() |
| 47 | + η = gensym() |
| 48 | + |
| 49 | + # yield(λ) → put!(c, λ) |
| 50 | + f′ = MacroTools.postwalk(f) do x |
| 51 | + @capture(x, yield(λ_)) || return x |
| 52 | + return :(put!($c, $λ)) |
| 53 | + end |
| 54 | + |
| 55 | + # Fetch the function name and args |
| 56 | + @capture(f′, function func_(args__) body_ end) |
| 57 | + |
| 58 | + # wrap up the η function |
| 59 | + final = quote |
| 60 | + function $func($(args...)) |
| 61 | + function $η($c) |
| 62 | + $body |
| 63 | + end |
| 64 | + return Channel(c -> $η(c)) |
| 65 | + end |
| 66 | + end |
| 67 | + |
| 68 | + return esc(final) |
55 | 69 | end |
56 | 70 |
|
57 | 71 | end |
0 commit comments