Skip to content

write_with_newline now handles \r\n #4547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions clippy_lints/src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ impl EarlyLintPass for Write {
} else if mac.path == sym!(print) {
span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, false) {
if check_newlines(&fmt_str) {
if terminating_newline(&fmt_str) {
span_lint_and_then(
cx,
PRINT_WITH_NEWLINE,
Expand All @@ -222,7 +222,7 @@ impl EarlyLintPass for Write {
}
} else if mac.path == sym!(write) {
if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, true) {
if check_newlines(&fmt_str) {
if terminating_newline(&fmt_str) {
span_lint_and_then(
cx,
WRITE_WITH_NEWLINE,
Expand Down Expand Up @@ -440,12 +440,14 @@ fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (O
}
}

/// Checks if the format string constains a single newline that terminates it.
/// Checks if the format string contains a single newline or \r\n that terminates it.
///
/// Literal and escaped newlines are both checked (only literal for raw strings).
fn check_newlines(fmt_str: &FmtStr) -> bool {
fn terminating_newline(fmt_str: &FmtStr) -> bool {
let s = &fmt_str.contents;

if s.ends_with("\\r\\n") {
return false;
}
if s.ends_with('\n') {
return true;
} else if let StrStyle::Raw(_) = fmt_str.style {
Expand Down
4 changes: 4 additions & 0 deletions tests/ui/write_with_newline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,8 @@ fn main() {
r"
"
);

// strings ending with \r\n
write!(&mut v, "\r\n"); // 4208
write!(&mut v, "foobar123\r\n"); // 4208
}