diff --git a/src/nlp_expr.jl b/src/nlp_expr.jl index b76cbcd706b..b87db787108 100644 --- a/src/nlp_expr.jl +++ b/src/nlp_expr.jl @@ -1144,3 +1144,12 @@ end function LinearAlgebra.qr(::AbstractMatrix{<:AbstractJuMPScalar}) return throw(MOI.UnsupportedNonlinearOperator(:qr)) end + +function add_to_expression!(f::GenericNonlinearExpr, args...) + return error( + "`add_to_expression!` is not supported for expressions of type " * + "`$(typeof(f))` because they cannot be modified in-place. " * + "Instead of `add_to_expression!(expr, args..)`, use " * + "`expr += *(args...)`.", + ) +end diff --git a/test/test_nlp_expr.jl b/test/test_nlp_expr.jl index bd309f4c1d8..c74487bf719 100644 --- a/test/test_nlp_expr.jl +++ b/test/test_nlp_expr.jl @@ -926,4 +926,20 @@ function test_generic_nonlinear_expr_infer_variable_type() return end +function test_add_to_expression!() + model = Model() + @variable(model, x) + y = zero(NonlinearExpr) + @test_throws( + ErrorException( + "`add_to_expression!` is not supported for expressions of type " * + "`$(typeof(y))` because they cannot be modified in-place. " * + "Instead of `add_to_expression!(expr, args..)`, use " * + "`expr += *(args...)`.", + ), + test_add_to_expression!(y, 2.0, sin(x)), + ) + return +end + end # module