Skip to content

Commit 9f1edaa

Browse files
committed
Escape chars when printing strings in decompiler
1 parent 6ac7520 commit 9f1edaa

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

library/src/scala/tasty/util/ShowSourceCode.scala

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package scala.tasty
22
package util
33

4+
import scala.annotation.switch
5+
46
class ShowSourceCode[T <: Tasty with Singleton](tasty0: T) extends Show[T](tasty0) {
57
import tasty._
68

@@ -591,8 +593,8 @@ class ShowSourceCode[T <: Tasty with Singleton](tasty0: T) extends Show[T](tasty
591593
case Constant.Long(v) => this += v += "L"
592594
case Constant.Float(v) => this += v
593595
case Constant.Double(v) => this += v
594-
case Constant.Char(v) => this += '\'' += v.toString += '\'' // TODO escape char
595-
case Constant.String(v) => this += '"' += v.toString += '"' // TODO escape string
596+
case Constant.Char(v) => this += '\'' += escapedChar(v) += '\''
597+
case Constant.String(v) => this += '"' += escapedString(v) += '"'
596598
}
597599

598600
def printTypeOrBoundsTree(tpt: TypeOrBoundsTree): Buffer = tpt match {
@@ -770,6 +772,19 @@ class ShowSourceCode[T <: Tasty with Singleton](tasty0: T) extends Show[T](tasty
770772
def +=(x: Char): this.type = { sb.append(x); this }
771773
def +=(x: String): this.type = { sb.append(x); this }
772774

775+
@switch private def escapedChar(ch: Char): String = ch match {
776+
case '\b' => "\\b"
777+
case '\t' => "\\t"
778+
case '\n' => "\\n"
779+
case '\f' => "\\f"
780+
case '\r' => "\\r"
781+
case '"' => "\\\""
782+
case '\'' => "\\\'"
783+
case '\\' => "\\\\"
784+
case _ => if (ch.isControl) "\\0" + Integer.toOctalString(ch) else String.valueOf(ch)
785+
}
786+
787+
private def escapedString(str: String): String = str flatMap escapedChar
773788
}
774789

775790

0 commit comments

Comments
 (0)