Skip to content

Commit

Permalink
Fix annotated join with non-concrete eltype iters
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 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.

Reported-by: kimikage <[email protected]>
  • Loading branch information
tecosaur committed Jul 4, 2024
1 parent 36a0da0 commit 6a1fec0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
12 changes: 8 additions & 4 deletions base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,16 @@ 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 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 @@ -101,6 +101,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 6a1fec0

Please sign in to comment.