Fix string literal and backslashes.
diff --git a/src/main/java/com/squareup/javapoet/Util.java b/src/main/java/com/squareup/javapoet/Util.java
index 5b9f557..8c3e1bf 100644
--- a/src/main/java/com/squareup/javapoet/Util.java
+++ b/src/main/java/com/squareup/javapoet/Util.java
@@ -122,7 +122,7 @@
case '\r': return "\\r"; /* \u000d: carriage return (CR) */
case '\"': return "\""; /* \u0022: double quote (") */
case '\'': return "\\'"; /* \u0027: single quote (') */
- case '\\': return "\\"; /* \u005c: backslash (\) */
+ case '\\': return "\\\\"; /* \u005c: backslash (\) */
default:
return isISOControl(c) ? String.format("\\u%04x", (int) c) : Character.toString(c);
}
@@ -139,6 +139,11 @@
result.append("'");
continue;
}
+ // trivial case: double quotes must be escaped
+ if (c == '\"') {
+ result.append("\\\"");
+ continue;
+ }
// default case: just let character literal do its work
result.append(characterLiteralWithoutSingleQuotes(c));
// need to append indent after linefeed?
diff --git a/src/test/java/com/squareup/javapoet/UtilTest.java b/src/test/java/com/squareup/javapoet/UtilTest.java
index c80a45b..d4b9c52 100644
--- a/src/test/java/com/squareup/javapoet/UtilTest.java
+++ b/src/test/java/com/squareup/javapoet/UtilTest.java
@@ -33,7 +33,7 @@
assertEquals("\\r", Util.characterLiteralWithoutSingleQuotes('\r'));
assertEquals("\"", Util.characterLiteralWithoutSingleQuotes('"'));
assertEquals("\\'", Util.characterLiteralWithoutSingleQuotes('\''));
- assertEquals("\\", Util.characterLiteralWithoutSingleQuotes('\\'));
+ assertEquals("\\\\", Util.characterLiteralWithoutSingleQuotes('\\'));
// octal escapes
assertEquals("\\u0000", Util.characterLiteralWithoutSingleQuotes('\0'));
assertEquals("\\u0007", Util.characterLiteralWithoutSingleQuotes('\7'));
@@ -61,6 +61,8 @@
stringLiteral("♦♥♠♣");
stringLiteral("€\\t@\\t$", "€\t@\t$", " ");
stringLiteral("abc();\\n\"\n + \"def();", "abc();\ndef();", " ");
+ stringLiteral("This is \\\"quoted\\\"!", "This is \"quoted\"!", " ");
+ stringLiteral("e^{i\\\\pi}+1=0", "e^{i\\pi}+1=0", " ");
}
void stringLiteral(String string) {