|
| 1 | +using MacroTools |
| 2 | +using IRTools |
| 3 | + |
| 4 | +using IRTools: branches, block, empty!, evalir, func, branch!, block, IR, @dynamo, xcall |
| 5 | + |
| 6 | +function _mark(label, ex) |
| 7 | + label isa Symbol || error("label has to be a Symbol") |
| 8 | + return Expr( |
| 9 | + :block, |
| 10 | + Expr(:meta, :begin_optional, label), |
| 11 | + esc(ex), |
| 12 | + Expr(:meta, :end_optional, label), |
| 13 | + ) |
| 14 | +end |
| 15 | + |
| 16 | +macro mark(label, ex) |
| 17 | + _mark(label, ex) |
| 18 | +end |
| 19 | + |
| 20 | + |
| 21 | +foo(x) = bar(baz(x)) |
| 22 | + |
| 23 | +function bar(x) |
| 24 | + @mark print iseven(x) && println("The input is even.") |
| 25 | + x |
| 26 | +end |
| 27 | + |
| 28 | +function baz(x) |
| 29 | + @mark print x<0 && println("The input is negative.") |
| 30 | + x |
| 31 | +end |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +isbegin(e::Expr) = Meta.isexpr(e,:meta) && e.args[1]===:begin_optional |
| 36 | +isend(e::Expr) = Meta.isexpr(e,:meta) && e.args[1]===:end_optional |
| 37 | + |
| 38 | + |
| 39 | +skip(f::Core.IntrinsicFunction, args...) = f(args...) |
| 40 | +skip(f::Core.Builtin, args...) = f(args...) |
| 41 | + |
| 42 | +@dynamo function skip(args...) |
| 43 | + ir = IR(args...) |
| 44 | + delete_line = false |
| 45 | + local orig |
| 46 | + |
| 47 | + for (x,st) in ir |
| 48 | + is_begin = isbegin(st.expr) |
| 49 | + is_end = isend(st.expr) |
| 50 | + |
| 51 | + if is_begin |
| 52 | + delete_line = true |
| 53 | + end |
| 54 | + |
| 55 | + if is_begin |
| 56 | + orig = block(ir,x) |
| 57 | + elseif is_end |
| 58 | + dest = block(ir,x) |
| 59 | + if orig != dest |
| 60 | + empty!(branches(orig)) |
| 61 | + branch!(orig,dest) |
| 62 | + end |
| 63 | + end |
| 64 | + |
| 65 | + if delete_line |
| 66 | + delete!(ir,x) |
| 67 | + end |
| 68 | + |
| 69 | + if is_end |
| 70 | + delete_line = false |
| 71 | + end |
| 72 | + |
| 73 | + if haskey(ir,x) && Meta.isexpr(st.expr,:call) |
| 74 | + ir[x] = IRTools.xcall(skip, st.expr.args...) |
| 75 | + end |
| 76 | + end |
| 77 | + return ir |
| 78 | +end |
| 79 | + |
| 80 | +function skip(ex::Expr) |
| 81 | +end |
| 82 | + |
| 83 | +macro skip(ex) |
| 84 | + ex.head == :call || error("Input expression has to be a `:call`.") |
| 85 | + return xcall(skip, ex.args...) |
| 86 | +end |
| 87 | + |
| 88 | +display(@code_ir foo(-2)) |
| 89 | +display(@code_ir skip(foo,-2)) |
| 90 | +display(foo(-2)) |
| 91 | +@skip foo(-2) |
0 commit comments