Skip to content

Commit

Permalink
Fix annotated join with non-concrete eltype iters (#54919)
Browse files Browse the repository at this point in the history
As raised in
<JuliaLang/StyledStrings.jl#57 (comment)>,
when the eltype of an iterator is non-concrete, `_isannotated` will
return false. To properly check such cases, we need to see if any of the
elements of the iterator are annotated.

This is a bit of an interesting case, since:
- Most of the time it shouldn't be hit, we can reasonably expect most
iterables to infer as producing concrete types
- The eltype of the iterator is (generally) known at compile-time, and
so in any case other than the ambiguous non-concrete one, this check
remains able to be done at compile-time.

With this change, join always preserves annotations. The compromise made
is that iterators with non-concrete eltypes can result in join inferring
a union return type (i.e. type instability with non-concrete iterators),
but that doesn't seem too bad to me (I don't see how we could be
completely type stable without concrete types here).

(cherry picked from commit 462d7f4)
  • Loading branch information
tecosaur authored and KristofferC committed Aug 2, 2024
1 parent 50e5fe0 commit 29f6950
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
16 changes: 12 additions & 4 deletions base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,20 @@ function join(io::IO, iterator, delim="")
end

function _join_preserve_annotations(iterator, args...)
if _isannotated(eltype(iterator)) || any(_isannotated, args)
if isconcretetype(eltype(iterator)) && !_isannotated(eltype(iterator)) && !any(_isannotated, args)
sprint(join, iterator, args...)
else
io = AnnotatedIOBuffer()
join(io, iterator, args...)
read(seekstart(io), AnnotatedString{String})
else
sprint(join, iterator, args...)
# If we know (from compile time information, or dynamically in the case
# of iterators with a non-concrete eltype), that the result is annotated
# in nature, we extract an `AnnotatedString`, otherwise we just extract
# a plain `String` from `io`.
if isconcretetype(eltype(iterator)) || !isempty(io.annotations)
read(seekstart(io), AnnotatedString{String})
else
String(take!(io.io))
end
end
end

Expand Down
2 changes: 2 additions & 0 deletions test/strings/annotated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ end
[(1:4, :label => 5),
(5:5, :label => 2),
(6:9, :label => 5)])
@test join((String(str1), str1), ' ') ==
Base.AnnotatedString("test test", [(6:9, :label => 5)])
@test repeat(str1, 2) == Base.AnnotatedString("testtest", [(1:8, :label => 5)])
@test repeat(str2, 2) == Base.AnnotatedString("casecase", [(2:3, :label => "oomph"),
(6:7, :label => "oomph")])
Expand Down

0 comments on commit 29f6950

Please sign in to comment.