Looks like I was accidentally on 0.4, and hygiene rules changed in 0.5.
This works:
using MacroTools
macro withself(fdef)
@assert @capture(fdef, fname_() = expr_)
esc(:(@generated function $(fname)(self)
expr = $(Expr(:quote, expr))
# Replace this with recursive
>
> This only works if A and type_fields are defined in the same module
> though. Although to be honest it surprised me a bit that it works at all, I
> guess the type definitions are evaluated prior to macro expansions?
>
Good point.
You can use a generated function then:
using MacroTools
> Would eval'ing the type inside the macro work? This shows [:x, :y]
>
>
This only works if A and type_fields are defined in the same module though.
Although to be honest it surprised me a bit that it works at all, I guess
the type definitions are evaluated prior to macro expansions?
A
On Fri, 2016-09-30 at 00:53, Marius Millea wrote:
> I think there's at least once scenario where eval-in-a-macro is not a
> mistake, mainly when you want to generate some code that depends on 1) some
> passed in expression and 2) something which can only be known at
You could do it like so:
A macro which defines a type-specific version @self_MyType of your @self
macro at the definition of the type:
@with_self type MyType
x
end
Then use that generated macro when defining the function:
@self_MyType function inc()
x += 1
end
This avoids any at little
Would eval'ing the type inside the macro work? This shows [:x, :y]
macro type_fields(typ)
fields = fieldnames(eval(typ))
@show fields
end
type A
x
y
end
@type_fields A
You can use that to generate the right expansion for that type.
On Thursday, September 29, 2016 at 6:53:01 PM
I think there's at least once scenario where eval-in-a-macro is not a
mistake, mainly when you want to generate some code that depends on 1) some
passed in expression and 2) something which can only be known at runtime.
Here's my example:
The macro (@self) which I'm writing takes a type name
On Tuesday, September 27, 2016 at 10:27:59 AM UTC-4, Stefan Karpinski wrote:
>
> But note that if you want some piece of f to be "pasted" from the user and
> have access to certain parts of the local state of f, it's probably a much
> better design to let the user pass in a function which f
If you need to generate code where the outer function has access to some
part of a local scope, you can generate the entire function and then call
it:
julia> ex = :(x + 1)
:(x + 1)
julia> @eval function f(x)
y = $ex
return y^2
end
f (generic function with 1 method)
On Tue, Sep 27, 2016 at 7:47 AM, Marius Millea wrote:
>> Macros are functions evaluated at parse-time. The runtime scope doesn't
>> even exist when the macro is called.
>
>
> That's right, the answer may well have nothing to do with marcos (maybe I
> obscured the question
10 matches
Mail list logo