Skip to content

Commit a984dc5

Browse files
committed
Conversion of VarName to/from string
1 parent 9156b3c commit a984dc5

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

src/AbstractPPL.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export VarName,
88
subsumes,
99
subsumedby,
1010
varname,
11+
varname_from_str,
1112
vsym,
1213
@varname,
1314
@vsym

src/varname.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,8 @@ function drop_escape(expr::Expr)
663663
return Expr(expr.head, map(x -> drop_escape(x), expr.args)...)
664664
end
665665

666+
varname_from_str(str::AbstractString) = eval(drop_escape(varname(Meta.parse(str))))
667+
666668
function _parse_obj_optic(ex)
667669
obj, optics = _parse_obj_optics(ex)
668670
optic = Expr(:call, Accessors.opticcompose, optics...)

test/varname.jl

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,34 @@ end
137137
@inferred get(c, @varname(b.a[1]))
138138
@inferred Accessors.set(c, @varname(b.a[1]), 10)
139139
end
140+
141+
@testset "roundtrip conversion to/from string" begin
142+
# Static optics
143+
vns = [
144+
@varname(x),
145+
@varname(x.a),
146+
@varname(x[1]),
147+
@varname(x[1:10]),
148+
@varname(x[1, 2]),
149+
@varname(x[1, 2:5]),
150+
@varname(x[:]),
151+
@varname(x.a[1]),
152+
@varname(x.a[1:10]),
153+
@varname(x[1].a),
154+
]
155+
for vn in vns
156+
@test varname_from_str(repr(vn)) == vn
157+
end
158+
159+
# Post-concretisation
160+
x = ones(10)
161+
vn = @varname(x[begin:end])
162+
@test varname_from_str(repr(vn)) == vn
163+
164+
# When forcing concretisation
165+
vn = @varname(x[:], true)
166+
@test_broken varname_from_str(repr(vn)) == vn
167+
dump(varname_from_str(repr(vn)))
168+
dump(vn)
169+
end
140170
end

0 commit comments

Comments
 (0)