Skip to content

Commit

Permalink
Implement eval-able AnnotatedString 2-arg show
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 29, 2024
1 parent 3265387 commit c96ea43
Show file tree
Hide file tree
Showing 2 changed files with 19 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
3 changes: 3 additions & 0 deletions test/strings/annotated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
(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), (6:11, :other=>0x02), (1:11, :all=>0x03)])"
@test sprint(show, str, MIME("text/plain")) == "\"some string\""
end

@testset "AnnotatedChar" begin
Expand Down

0 comments on commit c96ea43

Please sign in to comment.