Skip to content

Commit 8b562af

Browse files
committed
helpful error upon misuse of macro
1 parent af83ae7 commit 8b562af

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

base/runtime_internals.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,8 @@ false
173173
"""
174174
ispublic(m::Module, s::Symbol) = ccall(:jl_module_public_p, Cint, (Any, Any), m, s) != 0
175175

176+
_function_macro_error() = (@noinline; error("@__FUNCTION__ can only be used within a function"))
177+
176178
"""
177179
@__FUNCTION__ -> Function
178180
@@ -217,7 +219,10 @@ julia> factorial(5)
217219
```
218220
"""
219221
macro __FUNCTION__()
220-
return esc(:(var"#self#"))
222+
quote
223+
$(esc(Expr(:isdefined, :var"#self#"))) || $(esc(_function_macro_error))()
224+
$(esc(:var"#self#"))
225+
end
221226
end
222227

223228
# TODO: this is vaguely broken because it only works for explicit calls to

test/loading.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ end
141141
c = CallableStruct(5)
142142
@test_throws UndefVarError c()
143143
end
144+
145+
@testset "Error upon misuse" begin
146+
@gensym A
147+
@test_throws(
148+
"@__FUNCTION__ can only be used within a function",
149+
@eval(module $A; @__FUNCTION__; end)
150+
)
151+
end
144152
end
145153
end
146154

0 commit comments

Comments
 (0)