Skip to content

Instantly share code, notes, and snippets.

@FPGro
Created April 22, 2021 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FPGro/7cd5cd0e724ff135de66e5fc1027c129 to your computer and use it in GitHub Desktop.
Save FPGro/7cd5cd0e724ff135de66e5fc1027c129 to your computer and use it in GitHub Desktop.
Catch the monkey
"""
A more convenient syntax for try/catch clauses.
You know that you want it!
Instead of the boring old:
```julia
try
foo()
catch e
bar(e)
finally
baz()
end
```
you can now write the far more legible:
```julia
πŸ’£ = foo
πŸ˜₯ = bar
🍌 = baz
@πŸ’ begin
πŸ™ˆ
πŸ’£()
πŸ™Š(πŸ’₯)
πŸ˜₯(πŸ’₯)
πŸ™‰
🍌()
end
```
"""
macro πŸ’(monkeyexpression::Expr)
monkeyexpression.head == :block || error("You have to wrap this in a begin...end block, sorry!")
newexpr = Expr(:block)
tryblock = Expr(:block)
catchme = false
catchblock = false
finallyblock = nothing
state = :start # where are we in the expression
for sub in monkeyexpression.args
if state == :start
if sub isa Symbol && sub == :πŸ™ˆ
state = :try
elseif sub isa LineNumberNode
push!(newexpr.args, sub)
else
error("Missing πŸ™ˆ")
end
elseif state == :try
if sub isa Symbol && sub == :πŸ™Š
state = :catch
catchblock = Expr(:block)
elseif sub isa Expr && sub.args[1] == :πŸ™Š
state = :catch
catchblock = Expr(:block)
if length(sub.args) == 2
catchme = sub.args[2]
else
error("Can only catch a single error at once, duh!")
end
elseif sub isa Symbol && sub == :πŸ™‰
state = :finally
finallyblock = Expr(:block)
else
push!(tryblock.args, sub)
end
elseif state == :catch
if sub isa Symbol && sub == :πŸ™‰
state = :finally
finallyblock = Expr(:block)
else
push!(catchblock.args, sub)
end
elseif state == :finally
push!(finallyblock.args, sub)
end
end
tryexpr = Expr(:try, tryblock, catchme, catchblock)
if !isnothing(finallyblock)
push!(tryexpr.args, finallyblock)
end
push!(newexpr.args, tryexpr)
return newexpr
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment