From a984dc501804613e2c5f726c6daaaf4cf040c1ec Mon Sep 17 00:00:00 2001 From: Penelope Yong Date: Thu, 12 Sep 2024 17:56:41 +0100 Subject: [PATCH] Conversion of VarName to/from string --- src/AbstractPPL.jl | 1 + src/varname.jl | 2 ++ test/varname.jl | 30 ++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/src/AbstractPPL.jl b/src/AbstractPPL.jl index 775576a..012364f 100644 --- a/src/AbstractPPL.jl +++ b/src/AbstractPPL.jl @@ -8,6 +8,7 @@ export VarName, subsumes, subsumedby, varname, + varname_from_str, vsym, @varname, @vsym diff --git a/src/varname.jl b/src/varname.jl index b4960ef..dc12c76 100644 --- a/src/varname.jl +++ b/src/varname.jl @@ -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...) diff --git a/test/varname.jl b/test/varname.jl index d0e3de7..4ca7912 100644 --- a/test/varname.jl +++ b/test/varname.jl @@ -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