Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix modifying user-expressions in macros #3639

Merged
merged 1 commit into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ A helper function so that we can change how we rewrite expressions in a single
place and have it cascade to all locations in the JuMP macros that rewrite
expressions.
"""
function _rewrite_expression(expr)
function _rewrite_expression(expr::Expr)
new_expr = MacroTools.postwalk(_rewrite_to_jump_logic, expr)
new_aff, parse_aff = _MA.rewrite(new_expr; move_factors_into_sums = false)
ret = gensym()
Expand All @@ -242,6 +242,17 @@ function _rewrite_expression(expr)
return ret, code
end

"""
_rewrite_expression(expr)

If `expr` is not an `Expr`, then rewriting it won't do anything. We just need to
copy if it is mutable so that future operations do not modify the user's data.
"""
function _rewrite_expression(expr)
ret = gensym()
return ret, :($ret = $_MA.copy_if_mutable($(esc(expr))))
end

"""
model_convert(
model::AbstractModel,
Expand Down
11 changes: 11 additions & 0 deletions test/test_macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2223,4 +2223,15 @@ function test_constraint_broadcast_in_set()
return
end

function test_macro_modify_user_data()
model = Model()
@variable(model, x)
@expression(model, e, x + 5)
@constraint(model, -10 <= e <= 10)
@test isequal_canonical(e, x + 5)
@constraint(model, e in MOI.LessThan(1.0))
@test isequal_canonical(e, x + 5)
return
end

end # module
Loading