From abb58dcef1b4758f4e3af26c030e1f0630b8d145 Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Sun, 27 Apr 2014 00:08:54 -0700 Subject: SI-6476 Improve error on escapement Behavior of escape processing under string interpolation can be confusing. This commit improves the exception message so you know at least what sort of escapes are handled. This came up on SO in the form `s"\d".r`, where it may not be obvious what is throwing and how to work around it. ``` scala> s"\d".r scala.StringContext$InvalidEscapeException: invalid escape '\d' not one of [\b, \t, \n, \f, \r, \\, \", \'] at index 0 in "\d". Use \\ for literal \. scala> s"a\" scala.StringContext$InvalidEscapeException: invalid escape at terminal index 1 in "a\". Use \\ for literal \. ``` Referencing SI-6476 because that has become the magnet ticket for "escape processing under string interpolation, huh?" This doesn't address `$"` and doesn't handle the more interesting parse error `s"a\"b"`. --- src/library/scala/StringContext.scala | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/library') diff --git a/src/library/scala/StringContext.scala b/src/library/scala/StringContext.scala index c0468e8b02..0b08182102 100644 --- a/src/library/scala/StringContext.scala +++ b/src/library/scala/StringContext.scala @@ -175,8 +175,13 @@ object StringContext { * @param str The offending string * @param idx The index of the offending backslash character in `str`. */ - class InvalidEscapeException(str: String, @deprecatedName('idx) val index: Int) - extends IllegalArgumentException("invalid escape character at index "+index+" in \""+str+"\"") + class InvalidEscapeException(str: String, @deprecatedName('idx) val index: Int) extends IllegalArgumentException( + s"""invalid escape ${ + require(index >= 0 && index < str.length) + val ok = """[\b, \t, \n, \f, \r, \\, \", \']""" + if (index == str.length - 1) "at terminal" else s"'\\${str(index + 1)}' not one of $ok at" + } index $index in "$str". Use \\\\ for literal \\.""" + ) /** Expands standard Scala escape sequences in a string. * Escape sequences are: -- cgit v1.2.3