Skip to content

Commit

Permalink
document macro dispatch (#24457) (#24462)
Browse files Browse the repository at this point in the history
  • Loading branch information
jw3126 authored and StefanKarpinski committed Nov 20, 2017
1 parent 183b24b commit 4f5e374
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions doc/src/manual/metaprogramming.md
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,47 @@ However, we don't do this for a good reason: wrapping the `expr` in a new scope
also slightly changes the meaning of the expression (the scope of any variables in it),
while we want `@time` to be usable with minimum impact on the wrapped code.

### Macros and dispatch

Macros, just like Julia functions, are generic. This means they can also have multiple method definitions, thanks to multiple dispatch:
```jldoctest macromethods
julia> macro m end
@m (macro with 0 methods)
julia> macro m(args...)
println("$(length(args)) arguments")
end
@m (macro with 1 method)
julia> macro m(x,y)
println("Two arguments")
end
@m (macro with 2 methods)
julia> @m "asd"
1 arguments
julia> @m 1 2
Two arguments
```
However one should keep in mind, that macro dispatch is based on the types of AST
that are handed to the macro, not the types that the AST evaluates to at runtime:
```jldoctest macromethods
julia> macro m(::Int)
println("An Integer")
end
@m (macro with 3 methods)
julia> @m 2
An Integer
julia> x = 2
2
julia> @m x
1 arguments
```

## Code Generation

When a significant amount of repetitive boilerplate code is required, it is common to generate
Expand Down

0 comments on commit 4f5e374

Please sign in to comment.