-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathrule.jl
484 lines (378 loc) · 14 KB
/
rule.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
@inline alwaystrue(x) = true
# Matcher patterns with Slot and Segment
# matches one term
# syntax: ~x
struct Slot{P}
name::Symbol
predicate::P
end
Slot(s) = Slot(s, alwaystrue)
Base.isequal(s1::Slot, s2::Slot) = s1.name == s2.name
Base.show(io::IO, s::Slot) = (print(io, "~"); print(io, s.name))
# matches zero or more terms
# syntax: ~~x
struct Segment{F}
name::Symbol
predicate::F
end
ismatch(s::Segment, t) = s.predicate(t)
Segment(s) = Segment(s, alwaystrue)
Base.show(io::IO, s::Segment) = (print(io, "~~"); print(io, s.name))
makesegment(s::Symbol, keys) = (push!(keys, s); Segment(s))
function makesegment(s::Expr, keys)
if !(s.head == :(::))
error("Syntax for specifying a segment is ~~x::\$predicate, where predicate is a boolean function")
end
name = s.args[1]
push!(keys, name)
:(Segment($(QuoteNode(name)), $(esc(s.args[2]))))
end
makeslot(s::Symbol, keys) = (push!(keys, s); Slot(s))
function makeslot(s::Expr, keys)
if !(s.head == :(::))
error("Syntax for specifying a slot is ~x::\$predicate, where predicate is a boolean function")
end
name = s.args[1]
push!(keys, name)
:(Slot($(QuoteNode(name)), $(esc(s.args[2]))))
end
function makepattern(expr, keys)
if expr isa Expr
if expr.head === :call
if expr.args[1] === :(~)
if expr.args[2] isa Expr && expr.args[2].args[1] == :(~)
# matches ~~x::predicate
makesegment(expr.args[2].args[2], keys)
else
# matches ~x::predicate
makeslot(expr.args[2], keys)
end
else
:(term($(map(x->makepattern(x, keys), expr.args)...); type=Any))
end
elseif expr.head === :ref
:(term(getindex, $(map(x->makepattern(x, keys), expr.args)...); type=Any))
elseif expr.head === :$
return esc(expr.args[1])
else
Expr(expr.head, makepattern.(expr.args, (keys,))...)
end
else
# treat as a literal
return esc(expr)
end
end
function makeconsequent(expr)
if expr isa Expr
if expr.head === :call
if expr.args[1] === :(~)
if expr.args[2] isa Symbol
return :(getindex(__MATCHES__, $(QuoteNode(expr.args[2]))))
elseif expr.args[2] isa Expr && expr.args[2].args[1] == :(~)
@assert expr.args[2].args[2] isa Symbol
return :(getindex(__MATCHES__, $(QuoteNode(expr.args[2].args[2]))))
end
else
return Expr(:call, map(makeconsequent, expr.args)...)
end
else
return Expr(expr.head, map(makeconsequent, expr.args)...)
end
else
# treat as a literal
return esc(expr)
end
end
abstract type AbstractRule end # Currently doesn't really do anything. Can be removed.
#-----------------------------
#### Regular Rewriting Rules
struct Rule{L, M, R} <: AbstractRule
expr::Expr # rule pattern stored for pretty printing
lhs::L # the pattern
matcher::M # matcher(lhs)
rhs::R # consequent
depth::Int # number of levels of expr this rule touches
end
getdepth(r::Rule) = r.depth
function rule_depth(rule, d=0, maxdepth=0)
if iscall(rule)
maxdepth = reduce(max, (rule_depth(r, d+1, maxdepth) for r in arguments(rule)), init=1)
elseif rule isa Slot || rule isa Segment
maxdepth = max(d, maxdepth)
end
return maxdepth
end
function Base.show(io::IO, r::Rule)
Base.print(io, r.expr)
end
const EMPTY_IMMUTABLE_DICT = ImmutableDict{Symbol, Any}(:____, nothing)
function (r::Rule)(term)
rhs = r.rhs
try
# n == 1 means that exactly one term of the input (term,) was matched
success(bindings, n) = n == 1 ? (@timer "RHS" rhs(assoc(bindings, :MATCH, term))) : nothing
return r.matcher(success, (term,), EMPTY_IMMUTABLE_DICT)
catch err
throw(RuleRewriteError(r, term))
end
end
"""
rewrite_rhs(expr::Expr)
Rewrite the `expr` by dealing with `:where` if necessary.
The `:where` is rewritten from, for example, `~x where f(~x)` to `f(~x) ? ~x : nothing`.
"""
function rewrite_rhs(expr::Expr)
if expr.head == :where
rhs = expr.args[1]
predicate = expr.args[2]
expr = :($predicate ? $rhs : nothing)
end
return expr
end
rewrite_rhs(expr) = expr
"""
@rule LHS => RHS
Creates a `Rule` object. A rule object is callable, and takes an expression and rewrites
it if it matches the LHS pattern to the RHS pattern, returns `nothing` otherwise.
The rule language is described below.
LHS can be any possibly nested function call expression where any of the arguments can
optionally be a Slot (`~x`) or a Segment (`~~x`) (described below).
If an expression matches LHS entirely, then it is rewritten to the pattern in the RHS
Segment (`~x`) and slot variables (`~~x`) on the RHS will substitute the result of the
matches found for these variables in the LHS.
**Slot**:
A Slot variable is written as `~x` and matches a single expression. `x` is the name of the variable. If a slot appears more than once in an LHS expression then expression matched at every such location must be equal (as shown by `isequal`).
_Example:_
Simple rule to turn any `sin` into `cos`:
```julia
julia> @syms a b c
(a, b, c)
julia> r = @rule sin(~x) => cos(~x)
sin(~x) => cos(~x)
julia> r(sin(1+a))
cos((1 + a))
```
A rule with 2 segment variables
```julia
julia> r = @rule sin(~x + ~y) => sin(~x)*cos(~y) + cos(~x)*sin(~y)
sin(~x + ~y) => sin(~x) * cos(~y) + cos(~x) * sin(~y)
julia> r(sin(a + b))
cos(a)*sin(b) + sin(a)*cos(b)
```
A rule that matches two of the same expressions:
```julia
julia> r = @rule sin(~x)^2 + cos(~x)^2 => 1
sin(~x) ^ 2 + cos(~x) ^ 2 => 1
julia> r(sin(2a)^2 + cos(2a)^2)
1
julia> r(sin(2a)^2 + cos(a)^2)
# nothing
```
**Segment**:
A Segment variable is written as `~~x` and matches zero or more expressions in the
function call.
_Example:_
This implements the distributive property of multiplication: `+(~~ys)` matches expressions
like `a + b`, `a+b+c` and so on. On the RHS `~~ys` presents as any old julia array.
```julia
julia> r = @rule ~x * +((~~ys)) => sum(map(y-> ~x * y, ~~ys));
julia> r(2 * (a+b+c))
((2 * a) + (2 * b) + (2 * c))
```
**Predicates**:
There are two kinds of predicates, namely over slot variables and over the whole rule.
For the former, predicates can be used on both `~x` and `~~x` by using the `~x::f` or `~~x::f`.
Here `f` can be any julia function. In the case of a slot the function gets a single
matched subexpression, in the case of segment, it gets an array of matched expressions.
The predicate should return `true` if the current match is acceptable, and `false`
otherwise.
```julia
julia> two_πs(x::Number) = abs(round(x/(2π)) - x/(2π)) < 10^-9
two_πs (generic function with 1 method)
julia> two_πs(x) = false
two_πs (generic function with 2 methods)
julia> r = @rule sin(~~x + ~y::two_πs + ~~z) => sin(+(~~x..., ~~z...))
sin(~(~x) + ~(y::two_πs) + ~(~z)) => sin(+(~(~x)..., ~(~z)...))
julia> r(sin(a+3π))
julia> r(sin(a+6π))
sin(a)
julia> r(sin(a+6π+c))
sin((a + c))
```
Predicate function gets an array of values if attached to a segment variable (`~~x`).
For the predicate over the whole rule, use `@rule <LHS> => <RHS> where <predicate>`:
```
julia> @syms a b;
julia> predicate(x) = x === a;
julia> r = @rule ~x => ~x where predicate(~x);
julia> r(a)
a
julia> r(b) === nothing
true
```
Note that this is syntactic sugar and that it is the same as something like
`@rule ~x => f(~x) ? ~x : nothing`.
**Context**:
_In predicates_: Contextual predicates are functions wrapped in the `Contextual` type.
The function is called with 2 arguments: the expression and a context object
passed during a call to the Rule object (maybe done by passing a context to `simplify` or
a `RuleSet` object).
The function can use the inputs however it wants, and must return a boolean indicating
whether the predicate holds or not.
_In the consequent pattern_: Use `(@ctx)` to access the context object on the right hand side
of an expression.
"""
macro rule(expr)
@assert expr.head == :call && expr.args[1] == :(=>)
lhs = expr.args[2]
rhs = rewrite_rhs(expr.args[3])
keys = Symbol[]
lhs_term = makepattern(lhs, keys)
unique!(keys)
quote
$(__source__)
lhs_pattern = $(lhs_term)
Rule($(QuoteNode(expr)),
lhs_pattern,
matcher(lhs_pattern),
__MATCHES__ -> $(makeconsequent(rhs)),
rule_depth($lhs_term))
end
end
"""
@capture ex pattern
Uses a `Rule` object to capture an expression if it matches the `pattern`. Returns `true` and injects
slot variable match results into the calling scope when the `pattern` matches, otherwise returns false. The
rule language for specifying the `pattern` is the same in @capture as it is in `@rule`. Contextual matching
is not yet supported
```julia
julia> @syms a; ex = a^a;
julia> if @capture ex (~x)^(~x)
@show x
elseif @capture ex 2(~y)
@show y
end;
x = a
```
See also: [`@rule`](@ref)
"""
macro capture(ex, lhs)
keys = Symbol[]
lhs_term = makepattern(lhs, keys)
unique!(keys)
bind = Expr(:block, map(key-> :($(esc(key)) = getindex(__MATCHES__, $(QuoteNode(key)))), keys)...)
quote
$(__source__)
lhs_pattern = $(lhs_term)
__MATCHES__ = Rule($(QuoteNode(lhs)),
lhs_pattern,
matcher(lhs_pattern),
identity,
rule_depth($lhs_term))($(esc(ex)))
if __MATCHES__ !== nothing
$bind
true
else
false
end
end
end
#-----------------------------
#### Associative Commutative Rules
struct ACRule{F,R} <: AbstractRule
sets::F
rule::R
arity::Int
end
Rule(acr::ACRule) = acr.rule
getdepth(r::ACRule) = getdepth(r.rule)
macro acrule(expr)
arity = length(expr.args[2].args[2:end])
quote
ACRule(permutations, $(esc(:(@rule($(expr))))), $arity)
end
end
macro ordered_acrule(expr)
arity = length(expr.args[2].args[2:end])
quote
ACRule(combinations, $(esc(:(@rule($(expr))))), $arity)
end
end
Base.show(io::IO, acr::ACRule) = print(io, "ACRule(", acr.rule, ")")
function (acr::ACRule)(term)
r = Rule(acr)
if !iscall(term)
r(term)
else
f = operation(term)
# Assume that the matcher was formed by closing over a term
if f != operation(r.lhs) # Maybe offer a fallback if m.term errors.
return nothing
end
T = symtype(term)
args = arguments(term)
itr = acr.sets(eachindex(args), acr.arity)
for inds in itr
result = r(Term{T}(f, @views args[inds]))
if result !== nothing
# Assumption: inds are unique
length(args) == length(inds) && return result
return maketerm(typeof(term), f, [result, (args[i] for i in eachindex(args) if i ∉ inds)...], metadata(term))
end
end
end
end
struct RuleRewriteError
rule
expr
end
getdepth(::Any) = typemax(Int)
@noinline function Base.showerror(io::IO, err::RuleRewriteError)
msg = "Failed to apply rule $(err.rule) on expression "
msg *= sprint(io->showraw(io, err.expr))
print(io, msg)
end
function timerewrite(f)
if !TIMER_OUTPUTS
error("timerewrite must be called after enabling " *
"TIMER_OUTPUTS in the main file of this package")
end
reset_timer!()
being_timed[] = true
x = f()
being_timed[] = false
print_timer()
println()
x
end
"""
@timerewrite expr
If `expr` calls `simplify` or a `RuleSet` object, track the amount of time
it spent on applying each rule and pretty print the timing.
This uses [TimerOutputs.jl](https://github.com/KristofferC/TimerOutputs.jl).
## Example:
```julia
julia> expr = foldr(*, rand([a,b,c,d], 100))
(a ^ 26) * (b ^ 30) * (c ^ 16) * (d ^ 28)
julia> @timerewrite simplify(expr)
────────────────────────────────────────────────────────────────────────────────────────────────
Time Allocations
────────────────────── ───────────────────────
Tot / % measured: 340ms / 15.3% 92.2MiB / 10.8%
Section ncalls time %tot avg alloc %tot avg
────────────────────────────────────────────────────────────────────────────────────────────────
ACRule((~y) ^ ~n * ~y => (~y) ^ (~n ... 667 11.1ms 21.3% 16.7μs 2.66MiB 26.8% 4.08KiB
RHS 92 277μs 0.53% 3.01μs 14.4KiB 0.14% 160B
ACRule((~x) ^ ~n * (~x) ^ ~m => (~x)... 575 7.63ms 14.6% 13.3μs 1.83MiB 18.4% 3.26KiB
(*)(~(~(x::!issortedₑ))) => sort_arg... 831 6.31ms 12.1% 7.59μs 738KiB 7.26% 910B
RHS 164 3.03ms 5.81% 18.5μs 250KiB 2.46% 1.52KiB
...
...
────────────────────────────────────────────────────────────────────────────────────────────────
(a ^ 26) * (b ^ 30) * (c ^ 16) * (d ^ 28)
```
"""
macro timerewrite(expr)
:(timerewrite(()->$(esc(expr))))
end
Base.@deprecate RuleSet(x) Postwalk(Chain(x))