Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance StringIndexError display (correct escaping) #46039

Merged
merged 2 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions base/strings/string.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ function Base.showerror(io::IO, exc::StringIndexError)
if firstindex(s) <= exc.index <= ncodeunits(s)
iprev = thisind(s, exc.index)
inext = nextind(s, iprev)
escprev = escape_string(s[iprev:iprev])
if inext <= ncodeunits(s)
print(io, ", valid nearby indices [$iprev]=>'$(s[iprev])', [$inext]=>'$(s[inext])'")
escnext = escape_string(s[inext:inext])
print(io, ", valid nearby indices [$iprev]=>'$escprev', [$inext]=>'$escnext'")
else
print(io, ", valid nearby index [$iprev]=>'$(s[iprev])'")
print(io, ", valid nearby index [$iprev]=>'$escprev'")
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,11 @@ end
@test_throws ArgumentError "abc"[BitArray([true, false, true])]
end

@testset "issue #46039 enhance StringIndexError display" begin
@test sprint(showerror, StringIndexError("αn", 2)) == "StringIndexError: invalid index [2], valid nearby indices [1]=>'α', [3]=>'n'"
@test sprint(showerror, StringIndexError("α\n", 2)) == "StringIndexError: invalid index [2], valid nearby indices [1]=>'α', [3]=>'\\n'"
end

@testset "concatenation" begin
@test "ab" * "cd" == "abcd"
@test 'a' * "bc" == "abc"
Expand Down