Skip to content

Commit 2130ed8

Browse files
authored
Merge pull request #58 from JuliaDiff/ox/thunkwhere
Record where thunks actually created
2 parents d829da4 + 4e361cb commit 2130ed8

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/differentials.jl

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,17 @@ struct Thunk{F} <: AbstractThunk
212212
f::F
213213
end
214214

215+
216+
"""
217+
@thunk expr
218+
219+
Define a [`Thunk`](@ref) wrapping the `expr`, to lazily defer its evaluation.
220+
"""
215221
macro thunk(body)
216-
return :(Thunk(() -> $(esc(body))))
222+
# Basically `:(Thunk(() -> $(esc(body))))` but use the location where it is defined.
223+
# so we get useful stack traces if it errors.
224+
func = Expr(:->, Expr(:tuple), Expr(:block, __source__, body))
225+
return :(Thunk($(esc(func))))
217226
end
218227

219228
# have to define this here after `@thunk` and `Thunk` is defined

test/differentials.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,21 @@
6666
@test (@thunk(3))() == 3
6767
@test (@thunk(@thunk(3)))() isa Thunk
6868
end
69+
70+
@testset "erroring thunks should include the source in the backtrack" begin
71+
expected_line = (@__LINE__) + 2 # for testing it is at right palce
72+
try
73+
x = @thunk(error())
74+
extern(x)
75+
catch err
76+
err isa ErrorException || rethrow()
77+
st = stacktrace(catch_backtrace())
78+
# Should be 2nd last line, as last line will be the `error` function
79+
stackframe = st[2]
80+
@test stackframe.line == expected_line
81+
@test stackframe.file == Symbol(@__FILE__)
82+
end
83+
end
6984
end
7085

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

0 commit comments

Comments
 (0)