Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can Variables Start With # In Julia Macro Name Mangling?

Tags:

julia

I'm just learning macros and I'm confused about how it's possible for a variable name to start with a #, but that is exactly what a macro seems to successfully do. For example, if I want to set a variable to equal 4:

macro testMacro(sym)
  esym = esc(sym)
  quote
    temp = 4
    $esym = temp
    return
  end
end

Then

julia> macroexpand(:(@testMacro α))
quote  # none, line 4:
    #132#temp = 4 # line 5:
    α = #132#temp # line 6:
    return
end

julia> @testMacro α

julia> α
4

Notice the temp variable is named #132#temp and it's my understanding that it will be evaluated in the REPL just like that. However, that seems impossible since that whole line should now technically be a comment.

If I look at the first expression within the macro, I get something that I cannot reproduce.

julia> macroexpand(:(@testMacro α)).args[2]
:(#132#temp = 4)

julia> ex = :(#132#temp = 4)


ERROR: syntax: incomplete: premature end of input

What's going on here? I suppose I fundamentally have two questions. 1.) If it's possible, how can I define a variable (even within an expression) that starts with a #? 2.) Assuming the existence of such a variable, how does julia manage to not treat it as a comment?

like image 841
physicsd00d Avatar asked Dec 19 '22 05:12

physicsd00d


1 Answers

What's going on here?

The name-mangling here is to preserve macro hygiene so that names defined within a macro don't conflict with other names in the environment. (it is possible to override this using esc)

1.) If it's possible, how can I define a variable (even within an expression) that starts with a #?

I'm not sure why you would want to do this because accessing the variable will be cumbersome. But it is possible:

julia> eval(Expr(:(=), symbol("#s"), 1))
1

julia> whos()
#s                            Int64
Base                          Module
Core                          Module
LastMain                      Module
Main                          Module
ans                           Int64

julia> eval(symbol("#s"))
1

2.) Assuming the existence of such a variable, how does julia manage to not treat it as a comment?

Comments are dropped at the parser level, so the rest of the system never actually sees them. As shown above, a Symbol can be created from an arbitrary string containing a #, which is what the macro code does internally.

like image 148
Isaiah Norton Avatar answered Mar 04 '23 15:03

Isaiah Norton