Skip to content

Commit 38e42d9

Browse files
tecosaurKristofferC
authored andcommitted
Implement eval-able AnnotatedString 2-arg show (#54308)
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. (cherry picked from commit cc26f4a)
1 parent 6fc6eb0 commit 38e42d9

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

base/strings/annotated.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,22 @@ function getindex(s::AnnotatedString, i::Integer)
159159
end
160160
end
161161

162+
# To make `AnnotatedString`s repr-evaluable, we need to override
163+
# the generic `AbstractString` 2-arg show method.
164+
165+
function show(io::IO, s::A) where {A <: AnnotatedString}
166+
show(io, A)
167+
print(io, '(')
168+
show(io, s.string)
169+
print(io, ", ")
170+
show(IOContext(io, :typeinfo => typeof(annotations(s))), annotations(s))
171+
print(io, ')')
172+
end
173+
174+
# But still use the generic `AbstractString` fallback for the 3-arg show.
175+
show(io::IO, ::MIME"text/plain", s::AnnotatedString) =
176+
invoke(show, Tuple{IO, AbstractString}, io, s)
177+
162178
## AbstractChar interface ##
163179

164180
ncodeunits(c::AnnotatedChar) = ncodeunits(c.char)

test/strings/annotated.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@
5858
(3:3, :val => 2)])),
5959
Base.AnnotatedString("abc", [(1:2, :val => 1),
6060
(2:3, :val => 2)]))
61+
@test chopprefix(sprint(show, str), "Base.") ==
62+
"AnnotatedString{String}(\"some string\", [(1:4, :thing => 0x01), (1:11, :all => 0x03), (6:11, :other => 0x02)])"
63+
@test eval(Meta.parse(repr(str))) == str
64+
@test sprint(show, MIME("text/plain"), str) == "\"some string\""
6165
end
6266

6367
@testset "AnnotatedChar" begin

0 commit comments

Comments
 (0)