Skip to content

Commit

Permalink
Conversion of VarName to/from string
Browse files Browse the repository at this point in the history
  • Loading branch information
penelopeysm committed Sep 12, 2024
1 parent 9156b3c commit a984dc5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/AbstractPPL.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export VarName,
subsumes,
subsumedby,
varname,
varname_from_str,
vsym,
@varname,
@vsym
Expand Down
2 changes: 2 additions & 0 deletions src/varname.jl
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,8 @@ function drop_escape(expr::Expr)
return Expr(expr.head, map(x -> drop_escape(x), expr.args)...)
end

varname_from_str(str::AbstractString) = eval(drop_escape(varname(Meta.parse(str))))

function _parse_obj_optic(ex)
obj, optics = _parse_obj_optics(ex)
optic = Expr(:call, Accessors.opticcompose, optics...)
Expand Down
30 changes: 30 additions & 0 deletions test/varname.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,34 @@ end
@inferred get(c, @varname(b.a[1]))
@inferred Accessors.set(c, @varname(b.a[1]), 10)
end

@testset "roundtrip conversion to/from string" begin
# Static optics
vns = [
@varname(x),
@varname(x.a),
@varname(x[1]),
@varname(x[1:10]),
@varname(x[1, 2]),
@varname(x[1, 2:5]),
@varname(x[:]),
@varname(x.a[1]),
@varname(x.a[1:10]),
@varname(x[1].a),
]
for vn in vns
@test varname_from_str(repr(vn)) == vn
end

# Post-concretisation
x = ones(10)
vn = @varname(x[begin:end])
@test varname_from_str(repr(vn)) == vn

# When forcing concretisation
vn = @varname(x[:], true)
@test_broken varname_from_str(repr(vn)) == vn
dump(varname_from_str(repr(vn)))
dump(vn)
end
end

0 comments on commit a984dc5

Please sign in to comment.