From 1715110da6a9f7a1f1774281e5bbb8d953c3ba60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=90=86=E5=BF=B5=E5=9C=88?= <73381027+Rratic@users.noreply.github.com> Date: Tue, 30 Aug 2022 21:29:03 +0800 Subject: [PATCH] Enhance `StringIndexError` display (correct escaping) (#46039) --- base/strings/string.jl | 6 ++++-- test/strings/basic.jl | 5 +++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/base/strings/string.jl b/base/strings/string.jl index e44746f9834d9..3d8db74d7b795 100644 --- a/base/strings/string.jl +++ b/base/strings/string.jl @@ -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 diff --git a/test/strings/basic.jl b/test/strings/basic.jl index c1f1473daa236..c9b6e425f6a9c 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -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"