Skip to content

Instantly share code, notes, and snippets.

@aviatesk
Last active September 24, 2021 06:27
Show Gist options
  • Save aviatesk/5d3de0434fcbeefd4f99b88fcc08e4c6 to your computer and use it in GitHub Desktop.
Save aviatesk/5d3de0434fcbeefd4f99b88fcc08e4c6 to your computer and use it in GitHub Desktop.
# write the macro
macro return_const_case(x, d)
@assert isa(d, Symbol)
repr = string(d)
return quote
if $(esc(x)) == $(esc(d))
return $repr
end
end
end
const ELFDATAONE = 1
const ELFDATATWO = 2
const ELFDATATHREE = 3
@macroexpand let
d = 0x01
@return_const_case d ELFDATAONE
@return_const_case d ELFDATATWO
@return_const_case d ELFDATATHREE
end
# might want to handle them all at once ?
target = :(if x == c1
return "c1"
elseif x == c2
return "c2"
elseif x == c3
return "c3"
end)
# inspect the data structure
target.head
target.args[3].head
target.args[3].args[3].head
macro return_const_case(x, consts...)
_return_const_case(x, consts...)
end
function _return_const_case(x, consts...)
next = ret = Expr(:if, false, nothing)
for c in consts
@assert isa(c, Symbol)
repr = string(c)
cond = :($(esc(x)) == $(esc(c)))
body = :(return $repr)
blk = Expr(:elseif, cond, body)
push!(next.args, blk)
next = blk
end
return ret
end
@macroexpand let
d = 0x01
@return_const_case d ELFDATAONE ELFDATATWO ELFDATATHREE
end
# fun fact:
# macro def is a syntax sugar that lowers to a function def
# @-prefixed function is called at lowering time, taking two implicit arguments
function var"@somemacro"(source, mod, x)
@show source mod
return esc(x)
end
let
a = "hello macro"
@somemacro a
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment