Skip to content

Commit

Permalink
Implement eval-able AnnotatedString 2-arg show (#54308)
Browse files Browse the repository at this point in the history
The generic/fallback AbstractString 2-arg show omits the annotations,
meaning that eval(Meta.parse(repr(::AnnotatedString))) doesn't
round-trip.

The resolution to this is fairly simple, we just need to implement a
specialised show method. The implementation is fairly obvious, we're
just also able to get away with hiding the vector type annotation since
the constructor is fine without it.
  • Loading branch information
tecosaur committed Apr 30, 2024
1 parent 69036e1 commit cc26f4a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
16 changes: 16 additions & 0 deletions base/strings/annotated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,22 @@ function getindex(s::AnnotatedString, i::Integer)
end
end

# To make `AnnotatedString`s repr-evaluable, we need to override
# the generic `AbstractString` 2-arg show method.

function show(io::IO, s::A) where {A <: AnnotatedString}
show(io, A)
print(io, '(')
show(io, s.string)
print(io, ", ")
show(IOContext(io, :typeinfo => typeof(annotations(s))), annotations(s))
print(io, ')')
end

# But still use the generic `AbstractString` fallback for the 3-arg show.
show(io::IO, ::MIME"text/plain", s::AnnotatedString) =
invoke(show, Tuple{IO, AbstractString}, io, s)

## AbstractChar interface ##

ncodeunits(c::AnnotatedChar) = ncodeunits(c.char)
Expand Down
4 changes: 4 additions & 0 deletions test/strings/annotated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
(3:3, :val => 2)])),
Base.AnnotatedString("abc", [(1:2, :val => 1),
(2:3, :val => 2)]))
@test chopprefix(sprint(show, str), "Base.") ==
"AnnotatedString{String}(\"some string\", [(1:4, :thing => 0x01), (1:11, :all => 0x03), (6:11, :other => 0x02)])"
@test eval(Meta.parse(repr(str))) == str
@test sprint(show, MIME("text/plain"), str) == "\"some string\""
end

@testset "AnnotatedChar" begin
Expand Down

0 comments on commit cc26f4a

Please sign in to comment.