Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
format embedded escaped characters (newlines, tabs etc) in
double-quited string literals
  • Loading branch information
prakashk committed Mar 2, 2013
1 parent 254899d commit 2ccdfc6
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
@@ -1 +1 @@
{"StatementsNode" : [{"StringLiteralNode" : "foo\\\"bar\\\""}]}
{"StatementsNode" : [{"StringLiteralNode" : "foo\"bar\""}]}
2 changes: 1 addition & 1 deletion src/main/scala/org/moe/parser/Literals.scala
Expand Up @@ -47,7 +47,7 @@ trait Literals extends Base {
// - SL

def doubleQuoteStringContents: Parser[StringLiteralNode] =
"""([^"\p{Cntrl}\\]|\\[\\'"bfnrt]|\\x\{[a-fA-F0-9]{4}\})*""".r ^^ StringLiteralNode
"""([^"\p{Cntrl}\\]|\\[\\'"bfnrt]|\\x\{[a-fA-F0-9]{4}\})*""".r ^^ { s => StringLiteralNode(formatStr(s)) }
def singleQuoteStringContents: Parser[StringLiteralNode] =
"""([^'\p{Cntrl}\\]|\\[\\'"bfnrt]|\\x\{[a-fA-F0-9]{4}\})*""".r ^^ StringLiteralNode

Expand Down
13 changes: 13 additions & 0 deletions src/main/scala/org/moe/parser/ParserUtils.scala
Expand Up @@ -9,4 +9,17 @@ object ParserUtils {
def formatHex (s: String): Int = Integer.parseInt( normPerlInt(s).substring(2).toUpperCase, 16 )
def formatBin (s: String): Int = Integer.parseInt( normPerlInt(s).substring(2).toUpperCase, 2 )

// handle escaped characters in double-quoted strings
def formatStr (s: String): String = {
val escaped = Map(
"\\b" -> "\b",
"\\f" -> "\f",
"\\n" -> "\n",
"\\r" -> "\r",
"\\t" -> "\t"
)
val escapes = """\\([bfnrt'"])""".r
escapes.replaceAllIn(s, m => escaped.getOrElse(m.group(0), m.group(0).tail))
}

}
4 changes: 2 additions & 2 deletions src/test/scala/org/moe/parser/StringLiteralTestSuite.scala
Expand Up @@ -19,12 +19,12 @@ class StringLiteralTestSuite extends FunSuite with BeforeAndAfter with ParserTes

test("... basic test with a double-quoted string with control characters") {
val result = interpretCode(""" "foo\tbar\n" """)
assert(result.unboxToString.get === "foo\\tbar\\n")
assert(result.unboxToString.get === "foo\tbar\n")
}

test("... basic test with a double-quoted string with escaped quotes") {
val result = interpretCode(""" "foo\"bar\"" """)
assert(result.unboxToString.get === "foo\\\"bar\\\"")
assert(result.unboxToString.get === "foo\"bar\"")
}

//
Expand Down

0 comments on commit 2ccdfc6

Please sign in to comment.