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 22, 2024
1 parent 36a0da0 commit ab26f4f
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 @@ -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 ab26f4f

Please sign in to comment.