Please see this section of the manual
http://julia.readthedocs.org/en/latest/manual/metaprogramming/?highlight=quotenode#hygiene

The following is not the best way to solve this problem (you probably
don't want to escape everything) but it's a simple enough way to get
this particular case working

```julia
using Base.Test
import Base.hash

function auto_hash(typ::Expr)
    @assert typ.head == :type
    quote
        function hash(a::$(typ.args[2]))
            1
        end
    end
end

macro auto(typ)
    @assert typ.head == :type
    hash = auto_hash(typ)
    r = quote
        $typ
        $hash
    end
    esc(r)
end

println(macroexpand(:(@auto type A end)))
@auto type A end
@test typeof(A()) == A
@test hash(A()) == 1

println("ok")
```

On Fri, Jun 5, 2015 at 7:42 PM, andrew cooke <[email protected]> wrote:
> i'm trying to write a macro that will define == and hash() for a composite
> type.
>
> my initial effort is just to define a hash of 1
>
> using Base.Test
> import Base.hash
>
> function auto_hash(typ::Expr)
>     @assert typ.head == :type
>     quote
>         function hash(a::$(typ.args[2]))
>             1
>         end
>     end
> end
>
> macro auto(typ)
>     @assert typ.head == :type
>     hash = auto_hash(typ)
>     r = quote
>         $typ
>         $hash
>     end
>     show(r)
>     r
> end
>
> @auto type A end
> @test typeof(A()) == A
> @test hash(A()) == 1
>
> println("ok")
>
> unfortunately this fails - the hash value is some "random" value.
>
> yet the generated code, displayed by show, works when i cut + paste it into
> julia.  here's the result of running the program:
>
> andrew@laptop:~/project/ParserCombinator-0.4> julia-trunk test/auto.jl
> quote  # /home/andrew/.julia/v0.4/ParserCombinator/test/auto.jl, line 18:
>     type A
>     end # line 19:
>     begin  # /home/andrew/.julia/v0.4/ParserCombinator/test/auto.jl, line 8:
>         function hash(a::A) #
> /home/andrew/.julia/v0.4/ParserCombinator/test/auto.jl, line 9:
>             1
>         end
>     end
> end
> ERROR: LoadError: test failed: 0x0d6a95a0cf175e49 == 1
>
> here's some cut + pasting:
>
> julia> import Base.hash
>
> julia> type A    end # line 19:
>
> julia> begin  # /home/andrew/.julia/v0.4/ParserCombinator/test/auto.jl, line
> 8:
>            function hash(a::A) #
> /home/andrew/.julia/v0.4/ParserCombinator/test/auto.jl, line 9:
>                1
>            end
>        end
> hash (generic function with 36 methods)
>
> julia> hash(A())
> 1
>
> so why, oh why, doesn't my macro work?
>
> *something* is being evaluated ok because the type A is being created.
>
> thanks,
> andrew
>
>
>

Reply via email to