-
Notifications
You must be signed in to change notification settings - Fork 14
/
Chain.jl
343 lines (279 loc) · 9.34 KB
/
Chain.jl
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
module Chain
export @chain
is_aside(x) = false
is_aside(x::Expr) = x.head == :macrocall && x.args[1] == Symbol("@aside")
insert_first_arg(symbol::Symbol, firstarg; assignment = false) = Expr(:call, symbol, firstarg)
insert_first_arg(any, firstarg; assignment = false) = insertionerror(any)
function insertionerror(expr)
error(
"""Can't insert a first argument into:
$expr.
First argument insertion works with expressions like these, where [Module.SubModule.] is optional:
[Module.SubModule.]func
[Module.SubModule.]func(args...)
[Module.SubModule.]func(args...; kwargs...)
[Module.SubModule.]@macro
[Module.SubModule.]@macro(args...)
@. [Module.SubModule.]func
"""
)
end
is_moduled_symbol(x) = false
function is_moduled_symbol(e::Expr)
e.head == :. &&
length(e.args) == 2 &&
(e.args[1] isa Symbol || is_moduled_symbol(e.args[1])) &&
e.args[2] isa QuoteNode &&
e.args[2].value isa Symbol
end
function insert_first_arg(e::Expr, firstarg; assignment = false)
head = e.head
args = e.args
# variable = ...
# set assignment = true and rerun with right hand side
if !assignment && head == :(=) && length(args) == 2
if !(args[1] isa Symbol)
error("You can only use assignment syntax with a Symbol as a variable name, not $(args[1]).")
end
variable = args[1]
righthandside = insert_first_arg(args[2], firstarg; assignment = true)
:($variable = $righthandside)
# Module.SubModule.symbol
elseif is_moduled_symbol(e)
Expr(:call, e, firstarg)
# f(args...) --> f(firstarg, args...)
elseif head == :call && length(args) > 0
if length(args) ≥ 2 && Meta.isexpr(args[2], :parameters)
Expr(head, args[1:2]..., firstarg, args[3:end]...)
else
Expr(head, args[1], firstarg, args[2:end]...)
end
# f.(args...) --> f.(firstarg, args...)
elseif head == :. &&
length(args) > 1 &&
args[1] isa Symbol &&
args[2] isa Expr &&
args[2].head == :tuple
Expr(head, args[1], Expr(args[2].head, firstarg, args[2].args...))
# @. [Module.SubModule.]somesymbol --> somesymbol.(firstarg)
elseif head == :macrocall &&
length(args) == 3 &&
args[1] == Symbol("@__dot__") &&
args[2] isa LineNumberNode &&
(is_moduled_symbol(args[3]) || args[3] isa Symbol)
Expr(:., args[3], Expr(:tuple, firstarg))
# @macro(args...) --> @macro(firstarg, args...)
elseif head == :macrocall &&
(is_moduled_symbol(args[1]) || args[1] isa Symbol) &&
args[2] isa LineNumberNode
if args[1] == Symbol("@__dot__")
error("You can only use the @. macro and automatic first argument insertion if what follows is of the form `[Module.SubModule.]func`")
end
if length(args) >= 3 && args[3] isa Expr && args[3].head == :parameters
# macros can have keyword arguments after ; as well
Expr(head, args[1], args[2], args[3], firstarg, args[4:end]...)
else
Expr(head, args[1], args[2], firstarg, args[3:end]...)
end
else
insertionerror(e)
end
end
function rewrite(expr, replacement)
aside = is_aside(expr)
if aside
length(expr.args) != 3 && error("Malformed @aside macro")
expr = expr.args[3] # 1 is macro symbol, 2 is LineNumberNode
end
had_underscore, new_expr = replace_underscores(expr, replacement)
if !aside
if !had_underscore
new_expr = insert_first_arg(new_expr, replacement)
end
replacement = gensym()
new_expr = :(local $replacement = $new_expr)
end
(new_expr, replacement)
end
rewrite(l::LineNumberNode, replacement) = (l, replacement)
function rewrite_chain_block(firstpart, block)
pushfirst!(block.args, firstpart)
rewrite_chain_block(block)
end
"""
@chain(expr, exprs...)
Rewrites a series of expressions into a chain, where the result of one expression
is inserted into the next expression following certain rules.
**Rule 1**
Any `expr` that is a `begin ... end` block is flattened.
For example, these two pseudocodes are equivalent:
```julia
@chain a b c d e f
@chain a begin
b
c
d
end e f
```
**Rule 2**
Any expression but the first (in the flattened representation) will have the preceding result
inserted as its first argument, unless at least one underscore `_` is present.
In that case, all underscores will be replaced with the preceding result.
If the expression is a symbol, the symbol is treated equivalently to a function call.
For example, the following code block
```julia
@chain begin
x
f()
@g()
h
@i
j(123, _)
k(_, 123, _)
end
```
is equivalent to
```julia
begin
local temp1 = f(x)
local temp2 = @g(temp1)
local temp3 = h(temp2)
local temp4 = @i(temp3)
local temp5 = j(123, temp4)
local temp6 = k(temp5, 123, temp5)
end
```
**Rule 3**
An expression that begins with `@aside` does not pass its result on to the following expression.
Instead, the result of the previous expression will be passed on.
This is meant for inspecting the state of the chain.
The expression within `@aside` will not get the previous result auto-inserted, you can use
underscores to reference it.
```julia
@chain begin
[1, 2, 3]
filter(isodd, _)
@aside @info "There are \$(length(_)) elements after filtering"
sum
end
```
**Rule 4**
It is allowed to start an expression with a variable assignment.
In this case, the usual insertion rules apply to the right-hand side of that assignment.
This can be used to store intermediate results.
```julia
@chain begin
[1, 2, 3]
filtered = filter(isodd, _)
sum
end
filtered == [1, 3]
```
**Rule 5**
The `@.` macro may be used with a symbol to broadcast that function over the preceding result.
```julia
@chain begin
[1, 2, 3]
@. sqrt
end
```
is equivalent to
```julia
@chain begin
[1, 2, 3]
sqrt.(_)
end
```
"""
macro chain(initial_value, args...)
block = flatten_to_single_block(initial_value, args...)
rewrite_chain_block(block)
end
function flatten_to_single_block(args...)
blockargs = []
for arg in args
if arg isa Expr && arg.head === :block
append!(blockargs, arg.args)
else
push!(blockargs, arg)
end
end
Expr(:block, blockargs...)
end
function rewrite_chain_block(block)
block_expressions = block.args
isempty(block_expressions) ||
(length(block_expressions) == 1 && block_expressions[] isa LineNumberNode) &&
error("No expressions found in chain block.")
reconvert_docstrings!(block_expressions)
# assign first line to first gensym variable
firstvar = gensym()
rewritten_exprs = []
replacement = firstvar
did_first = false
for expr in block_expressions
# could be an expression first or a LineNumberNode, so a bit convoluted
# we just do the firstvar transformation for the first non LineNumberNode
# we encounter
if !(did_first || expr isa LineNumberNode)
expr = :(local $firstvar = $expr)
did_first = true
push!(rewritten_exprs, expr)
continue
end
rewritten, replacement = rewrite(expr, replacement)
push!(rewritten_exprs, rewritten)
end
result = Expr(:block, rewritten_exprs..., replacement)
:($(esc(result)))
end
# if a line in a chain is a string, it can be parsed as a docstring
# for whatever is on the following line. because this is unexpected behavior
# for most users, we convert all docstrings back to separate lines.
function reconvert_docstrings!(args::Vector)
docstring_indices = findall(args) do arg
(arg isa Expr
&& arg.head == :macrocall
&& length(arg.args) == 4
&& arg.args[1] == GlobalRef(Core, Symbol("@doc")))
end
# replace docstrings from back to front because this leaves the earlier indices intact
for i in reverse(docstring_indices)
e = args[i]
str = e.args[3]
nextline = e.args[4]
splice!(args, i:i, [str, nextline])
end
args
end
function replace_underscores(expr::Expr, replacement)
found_underscore = false
# if a @chain macrocall is found, only its first arg can be replaced if it's an
# underscore, otherwise the macro insides are left untouched
if expr.head == :macrocall && expr.args[1] == Symbol("@chain")
length(expr.args) < 3 && error("Malformed nested @chain macro")
expr.args[2] isa LineNumberNode || error("Malformed nested @chain macro")
arg3 = if expr.args[3] == Symbol("_")
found_underscore = true
replacement
else
expr.args[3]
end
newexpr = Expr(:macrocall, Symbol("@chain"), expr.args[2], arg3, expr.args[4:end]...)
# for all other expressions, their arguments are checked for underscores recursively
# and replaced if any are found
else
newargs = map(x -> replace_underscores(x, replacement), expr.args)
found_underscore = any(first.(newargs))
newexpr = Expr(expr.head, last.(newargs)...)
end
return found_underscore, newexpr
end
function replace_underscores(x, replacement)
if x == Symbol("_")
true, replacement
else
false, x
end
end
end