From 9ab125e8793e105b4594ba1b2fb2342b7c1275ec Mon Sep 17 00:00:00 2001 From: odow Date: Fri, 3 May 2024 08:56:18 +1200 Subject: [PATCH] Update --- docs/src/manual/nonlinear.md | 2 +- src/macros/@force_nonlinear.jl | 17 ++++++++++------- test/test_macros.jl | 2 +- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/src/manual/nonlinear.md b/docs/src/manual/nonlinear.md index dcba37b45d5..afd11e58876 100644 --- a/docs/src/manual/nonlinear.md +++ b/docs/src/manual/nonlinear.md @@ -370,7 +370,7 @@ x² - 0.2 x + 0.010000000000000002 julia> typeof(f) QuadExpr (alias for GenericQuadExpr{Float64, GenericVariableRef{Float64}}) ``` -To over-ride this behavior, use the [`@force_nonlinear`](@ref) macro: +To override this behavior, use the [`@force_nonlinear`](@ref) macro: ```jldoctest force_nonlinear julia> g = @force_nonlinear((x - 0.1)^2) (x - 0.1) ^ 2 diff --git a/src/macros/@force_nonlinear.jl b/src/macros/@force_nonlinear.jl index 530bccf7e80..5ea1dfde2a7 100644 --- a/src/macros/@force_nonlinear.jl +++ b/src/macros/@force_nonlinear.jl @@ -108,11 +108,14 @@ macro force_nonlinear(expr) end return x end - return quote - r = $(esc(ret)) - if !(r isa $GenericNonlinearExpr) - $error_fn("expression did not produce a GenericNonlinearExpr") - end - r - end + return Expr(:call, _force_nonlinear, error_fn, esc(ret)) +end + +_force_nonlinear(::F, ret::GenericNonlinearExpr) where {F} = ret + +function _force_nonlinear(error_fn::F, ret::Any) where {F} + return error_fn( + "expression did not produce a `GenericNonlinearExpr`. Got a " * + "`$(typeof(ret))`: $(ret)", + ) end diff --git a/test/test_macros.jl b/test/test_macros.jl index 0ea3fb23efc..9a144f7126d 100644 --- a/test/test_macros.jl +++ b/test/test_macros.jl @@ -2373,7 +2373,7 @@ function test_force_nonlinear() @test @force_nonlinear(x^2) isa GenericNonlinearExpr @test_throws_runtime( ErrorException( - "In `@force_nonlinear(x)`: expression did not produce a GenericNonlinearExpr", + "In `@force_nonlinear(x)`: expression did not produce a `GenericNonlinearExpr`. Got a `$(typeof(x))`: $x", ), @force_nonlinear(x), )