forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
macros_vs_inlining
38 lines (28 loc) · 1.96 KB
/
macros_vs_inlining
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Macros are totally different from inlining. Macros are a hook into the compiler that lets you examine and rewrite the syntax of a piece of the program. You can use them to implement entirely new syntactic constructs like spawn, parfor, pattern matching, stefan's command syntax, etc.
Macros also run at an earlier binding time than functions and so have different semantics. Inlining moves code around in a way that keeps the same function call semantics, i.e. you can't "tell" that it happened. Macros are just the opposite.
For example, say I have a function that contains an inner function:
function foo()
bar(x) = XXX
...
bar(...)
end
Now I want to abstract away the definition of bar. Maybe I want to use it in multiple functions and I don't want to copy and paste it. With macros I can do this:
macro definestuff(name)
quote
($name)(x) = XXX
end
end
function foo()
@definestuff bar
...
end
This is not possible without macros. If you passed :bar to a function, that function has no way to define a local bar inside foo. If it used eval, it would define a top-level function called bar. Since the macro runs so much earlier, it can change the code of foo itself, so it can easily modify local variables.
And this example hardly shows the full power, since the argument to the macro is only a symbol. This is just to show the semantic differences.
Another example is spawn:
macro spawn(expr)
quote
spawn(()->($expr))
end
end
Now you can write "@spawn a+b" and it will call a function spawn() on "a+b" wrapped in a thunk. It should be clear that this syntax improvement requires macros. The function call f(a+b) couldn't work since a+b will be fully evaluated before f is called. f(:(a+b)) is ugly, and also wouldn't work since f cannot use :(a+b) to access the values of local variables a and b.
People often compare macros to inlining (for example, the designer(s) of C++), but this is a pun. There is only a superficial similarity of inserting code into other code.