How to tell if code is being run in global scope?

How do you tell if code is being evaluated at top-level, or directly into the REPL?

I have a macro that defines some variables in the current scope. For example:

macro defs(n)
	assignments = [:($(esc(Symbol("x$i"))) = $i) for i in 1:n]
	quote $(assignments...) end
end

@defs 3
# expands to:
quote
    x1 = 1
    x2 = 2
    x3 = 3
end

If this is entered into the REPL, I want to show an informative message like

julia> @defs 3
[ Info: Defined global variables: x1, x2, x3

but I don’t want this message to be shown when used in a local scope, e.g., in a function definition:

julia> function foo()
           x = 42
           @defs 5
           x + x5
       end
foo (generic function with 1 method)
# no info message

Is this possible to do with Julia macros?

Edit: this might be an XY problem, so I’m open to workarounds — I just want to inform the user when something “permanent” happens, like defining variables in global scope.

See https://discourse.julialang.org/t/is-there-a-way-to-determine-whether-code-is-toplevel and https://discourse.julialang.org/t/should-macros-get-an-istoplevel-or-scope-argument

1 Like