Skip to content

Commit

Permalink
Fix modifying user-expressions in macros (#3639)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Dec 20, 2023
1 parent f5f07b5 commit 868b3d5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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

0 comments on commit 868b3d5

Please sign in to comment.