Skip to content

Commit

Permalink
SONARJAVA-5098 FP in S3457 when using strings involving \\n
Browse files Browse the repository at this point in the history
Co-authored-by: leonardo-pilastri-sonarsource <[email protected]>
  • Loading branch information
kaufco and leonardo-pilastri-sonarsource authored Sep 12, 2024
1 parent 26ab5be commit 3acc73e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -454,3 +454,13 @@ void foo(org.slf4j.Logger log, org.slf4j.Marker marker) {
log.debug("message");
}
}

class SonarJava5098 {
void foo() {
String.format("\\newpage %n"); // Compliant
String.format("\\\newpage %n"); // Noncompliant {{%n should be used in place of \n to produce the platform-specific line separator.}}
String.format("\newpage %n"); // Noncompliant
String.format("aaa\\naaa\\\\naaa\\\\\na%naaa\\\\\\n"); // Noncompliant
String.format("aaa\\naaa\\\\naaa\\\\na%naaa\\\\\\n"); // Compliant
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,22 @@ private void checkBoolean(MethodInvocationTree mit, String param, Type argType)
}

private void checkLineFeed(String formatString, MethodInvocationTree mit) {
if (formatString.contains("\\n")) {
reportIssue(mit, "%n should be used in place of \\n to produce the platform-specific line separator.");
var index = formatString.indexOf("\\n");
while (index != -1) {
if (isOddNumberOfEscapeChars(formatString, index)) {
reportIssue(mit, "%n should be used in place of \\n to produce the platform-specific line separator.");
return;
}
index = formatString.indexOf("\\n", index+2);
}
}

private static boolean isOddNumberOfEscapeChars(String formatString, int lastIndex) {
var index = lastIndex-1;
while (index >= 0 && formatString.charAt(index) == '\\') {
index--;
}
return (lastIndex - index) % 2 != 0;
}

private static boolean usesMessageFormat(String formatString, List<String> params) {
Expand Down

0 comments on commit 3acc73e

Please sign in to comment.