Skip to content

Commit

Permalink
fix for #511
Browse files Browse the repository at this point in the history
  • Loading branch information
torfjelde committed Aug 4, 2023
1 parent 5dd7c53 commit 92c2835
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/compiler.jl
Original file line number Diff line number Diff line change
Expand Up @@ -541,9 +541,7 @@ definitions. This is checked using [`isfuncdef`](@ref).
"""
replace_returns(e) = e
function replace_returns(e::Expr)
if isfuncdef(e)
return e
end
isfuncdef(e) && return e

if Meta.isexpr(e, :return)
# We capture the original return-value in `retval` and return
Expand All @@ -562,13 +560,12 @@ function replace_returns(e::Expr)
return Expr(e.head, map(replace_returns, e.args)...)
end

# If it's just a symbol, e.g. `f(x) = 1`, then we make it `f(x) = return 1`.
make_returns_explicit!(body) = Expr(:return, body)
function make_returns_explicit!(body::Expr)
add_return_to_last_statment!(body) = Expr(:return, body)

Check warning on line 563 in src/compiler.jl

View check run for this annotation

Codecov / codecov/patch

src/compiler.jl#L563

Added line #L563 was not covered by tests
function add_return_to_last_statment!(body::Expr)
# If the last statement is a return-statement, we don't do anything.
# Otherwise we replace the last statement with a `return` statement.
# Otherwise we replace the last statement with an altered `return`.
if !Meta.isexpr(body.args[end], :return)
body.args[end] = Expr(:return, body.args[end])
body.args[end] = replace_returns(Expr(:return, body.args[end]))
end
return body
end
Expand Down Expand Up @@ -626,7 +623,7 @@ function build_output(modeldef, linenumbernode)
# See the docstrings of `replace_returns` for more info.
evaluatordef[:body] = MacroTools.@q begin
$(linenumbernode)
$(replace_returns(make_returns_explicit!(modeldef[:body])))
$(add_return_to_last_statment!(replace_returns(modeldef[:body])))
end

## Build the model function.
Expand Down
18 changes: 18 additions & 0 deletions test/compiler.jl
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,24 @@ end
# With assignment.
@model outer() = @submodel x = inner()
@test outer()() isa Real

# Edge-cases.
# `return` in the last statement.
# Ref: issue #511.
@model function demo_ret_in_last_stmt(x::Bool)
# Two different values not supporting `iterate`.
if x
return nothing
else
return missing
end
end

model_true = demo_ret_in_last_stmt(true)
@test model_true() === nothing

model_false = demo_ret_in_last_stmt(false)
@test model_false() === missing
end

@testset "issue #368: hasmissing dispatch" begin
Expand Down

0 comments on commit 92c2835

Please sign in to comment.