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

Record where thunks actually created #58

Merged
merged 2 commits into from
Oct 23, 2019
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
11 changes: 10 additions & 1 deletion src/differentials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,17 @@ struct Thunk{F} <: AbstractThunk
f::F
end


"""
@thunk expr

Define a [`Thunk`](@ref) wrapping the `expr`, to lazily defer its evaluation.
"""
macro thunk(body)
return :(Thunk(() -> $(esc(body))))
# Basically `:(Thunk(() -> $(esc(body))))` but use the location where it is defined.
# so we get useful stack traces if it errors.
func = Expr(:->, Expr(:tuple), Expr(:block, __source__, body))
return :(Thunk($(esc(func))))
end

# have to define this here after `@thunk` and `Thunk` is defined
Expand Down
15 changes: 15 additions & 0 deletions test/differentials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,21 @@
@test (@thunk(3))() == 3
@test (@thunk(@thunk(3)))() isa Thunk
end

@testset "erroring thunks should include the source in the backtrack" begin
expected_line = (@__LINE__) + 2 # for testing it is at right palce
try
x = @thunk(error())
extern(x)
catch err
err isa ErrorException || rethrow()
st = stacktrace(catch_backtrace())
# Should be 2nd last line, as last line will be the `error` function
stackframe = st[2]
@test stackframe.line == expected_line
@test stackframe.file == Symbol(@__FILE__)
end
end
end

@testset "No ambiguities in $f" for f in (+, *)
Expand Down