diff --git a/src/macros.jl b/src/macros.jl index 7660ab6576d..19bb34e427a 100644 --- a/src/macros.jl +++ b/src/macros.jl @@ -3016,7 +3016,13 @@ macro variable(args...) requested_container, ) end - + # Wrap the entire code block in a let statement to make the model act as + # a type stable local variable. + creation_code = quote + let $model = $model + $creation_code + end + end if anonvar # Anonymous variable, no need to register it in the model-level # dictionary nor to assign it to a variable in the user scope. diff --git a/test/test_hygiene.jl b/test/test_hygiene.jl index a7bc87a8ed5..09b82cb11ff 100644 --- a/test/test_hygiene.jl +++ b/test/test_hygiene.jl @@ -57,4 +57,10 @@ Test.@test ex[3] == 6 Test.@test i == 10 Test.@test j == 10 +# Test that `model` is inferred correctly inside macros, despite being a +# non-const global. +model = JuMP.Model() +JuMP.@variable(model, x[1:0]) +Test.@test x == JuMP.VariableRef[] + end