Skip to content

Commit 198f49a

Browse files
committed
@rand: allow references to objects outside of rand calls
E.g. in `@rand rand(d::Die) = d.n`, `d.n` in not within a `rand` call, and must be transformed into `d[].n` in the "samplerized" version (where `d isa SamplerTrivial{Die}`).
1 parent b5f09a6 commit 198f49a

2 files changed

Lines changed: 13 additions & 6 deletions

File tree

src/macros.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ function as_sampler(ex, istrivial)
6363
end
6464

6565
function samplerize!(sps, ex, name)
66+
if ex == name
67+
# not within a rand() call
68+
return Expr(:ref, name) # name -> name[]
69+
end
6670
ex isa Expr || return ex
6771
if ex.head == :call && ex.args[1] == :rand
6872
# TODO: handle Repetition == Val(Inf) for arrays

test/runtests.jl

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -573,14 +573,13 @@ end
573573

574574
Base.eltype(::Type{Die}) = Int
575575

576-
@rand function rand(d::Die)
577-
7
578-
end
579-
580576
@testset "@rand" begin
581577
d = Die(6)
582578
rng = MersenneTwister()
583579

580+
@rand function rand(d::Die)
581+
7
582+
end
584583
@test rand(d) == 7
585584

586585
# redefinition
@@ -595,7 +594,11 @@ end
595594
@test rand(d) 11:16
596595
@test all((11:16), rand(d, 10))
597596

597+
# redefinition access to argument not within rand call
598+
@rand rand(d::Die) = rand(1:1) + d.n
599+
@test all(==(7), rand(d, 10))
600+
598601
# redefinition back to SamplerTrivial
599-
@rand rand(d::Die) = 0
600-
@test all(==(0), rand(d, 100))
602+
@rand rand(d::Die) = d.n
603+
@test all(==(6), rand(d, 100))
601604
end

0 commit comments

Comments
 (0)