]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/write.rs
Auto merge of #8354 - dswij:8345, r=giraffate
[rust.git] / clippy_lints / src / write.rs
1 use std::borrow::Cow;
2 use std::iter;
3 use std::ops::{Deref, Range};
4
5 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
6 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
7 use rustc_ast::ast::{Expr, ExprKind, Impl, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
8 use rustc_ast::token::{self, LitKind};
9 use rustc_ast::tokenstream::TokenStream;
10 use rustc_errors::Applicability;
11 use rustc_lexer::unescape::{self, EscapeError};
12 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
13 use rustc_parse::parser;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::symbol::{kw, Symbol};
16 use rustc_span::{sym, BytePos, Span, DUMMY_SP};
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// This lint warns when you use `println!("")` to
21     /// print a newline.
22     ///
23     /// ### Why is this bad?
24     /// You should use `println!()`, which is simpler.
25     ///
26     /// ### Example
27     /// ```rust
28     /// // Bad
29     /// println!("");
30     ///
31     /// // Good
32     /// println!();
33     /// ```
34     #[clippy::version = "pre 1.29.0"]
35     pub PRINTLN_EMPTY_STRING,
36     style,
37     "using `println!(\"\")` with an empty string"
38 }
39
40 declare_clippy_lint! {
41     /// ### What it does
42     /// This lint warns when you use `print!()` with a format
43     /// string that ends in a newline.
44     ///
45     /// ### Why is this bad?
46     /// You should use `println!()` instead, which appends the
47     /// newline.
48     ///
49     /// ### Example
50     /// ```rust
51     /// # let name = "World";
52     /// print!("Hello {}!\n", name);
53     /// ```
54     /// use println!() instead
55     /// ```rust
56     /// # let name = "World";
57     /// println!("Hello {}!", name);
58     /// ```
59     #[clippy::version = "pre 1.29.0"]
60     pub PRINT_WITH_NEWLINE,
61     style,
62     "using `print!()` with a format string that ends in a single newline"
63 }
64
65 declare_clippy_lint! {
66     /// ### What it does
67     /// Checks for printing on *stdout*. The purpose of this lint
68     /// is to catch debugging remnants.
69     ///
70     /// ### Why is this bad?
71     /// People often print on *stdout* while debugging an
72     /// application and might forget to remove those prints afterward.
73     ///
74     /// ### Known problems
75     /// * Only catches `print!` and `println!` calls.
76     /// * The lint level is unaffected by crate attributes. The level can still
77     ///   be set for functions, modules and other items. To change the level for
78     ///   the entire crate, please use command line flags. More information and a
79     ///   configuration example can be found in [clippy#6610].
80     ///
81     /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
82     ///
83     /// ### Example
84     /// ```rust
85     /// println!("Hello world!");
86     /// ```
87     #[clippy::version = "pre 1.29.0"]
88     pub PRINT_STDOUT,
89     restriction,
90     "printing on stdout"
91 }
92
93 declare_clippy_lint! {
94     /// ### What it does
95     /// Checks for printing on *stderr*. The purpose of this lint
96     /// is to catch debugging remnants.
97     ///
98     /// ### Why is this bad?
99     /// People often print on *stderr* while debugging an
100     /// application and might forget to remove those prints afterward.
101     ///
102     /// ### Known problems
103     /// * Only catches `eprint!` and `eprintln!` calls.
104     /// * The lint level is unaffected by crate attributes. The level can still
105     ///   be set for functions, modules and other items. To change the level for
106     ///   the entire crate, please use command line flags. More information and a
107     ///   configuration example can be found in [clippy#6610].
108     ///
109     /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
110     ///
111     /// ### Example
112     /// ```rust
113     /// eprintln!("Hello world!");
114     /// ```
115     #[clippy::version = "1.50.0"]
116     pub PRINT_STDERR,
117     restriction,
118     "printing on stderr"
119 }
120
121 declare_clippy_lint! {
122     /// ### What it does
123     /// Checks for use of `Debug` formatting. The purpose of this
124     /// lint is to catch debugging remnants.
125     ///
126     /// ### Why is this bad?
127     /// The purpose of the `Debug` trait is to facilitate
128     /// debugging Rust code. It should not be used in user-facing output.
129     ///
130     /// ### Example
131     /// ```rust
132     /// # let foo = "bar";
133     /// println!("{:?}", foo);
134     /// ```
135     #[clippy::version = "pre 1.29.0"]
136     pub USE_DEBUG,
137     restriction,
138     "use of `Debug`-based formatting"
139 }
140
141 declare_clippy_lint! {
142     /// ### What it does
143     /// This lint warns about the use of literals as `print!`/`println!` args.
144     ///
145     /// ### Why is this bad?
146     /// Using literals as `println!` args is inefficient
147     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
148     /// (i.e., just put the literal in the format string)
149     ///
150     /// ### Known problems
151     /// Will also warn with macro calls as arguments that expand to literals
152     /// -- e.g., `println!("{}", env!("FOO"))`.
153     ///
154     /// ### Example
155     /// ```rust
156     /// println!("{}", "foo");
157     /// ```
158     /// use the literal without formatting:
159     /// ```rust
160     /// println!("foo");
161     /// ```
162     #[clippy::version = "pre 1.29.0"]
163     pub PRINT_LITERAL,
164     style,
165     "printing a literal with a format string"
166 }
167
168 declare_clippy_lint! {
169     /// ### What it does
170     /// This lint warns when you use `writeln!(buf, "")` to
171     /// print a newline.
172     ///
173     /// ### Why is this bad?
174     /// You should use `writeln!(buf)`, which is simpler.
175     ///
176     /// ### Example
177     /// ```rust
178     /// # use std::fmt::Write;
179     /// # let mut buf = String::new();
180     /// // Bad
181     /// writeln!(buf, "");
182     ///
183     /// // Good
184     /// writeln!(buf);
185     /// ```
186     #[clippy::version = "pre 1.29.0"]
187     pub WRITELN_EMPTY_STRING,
188     style,
189     "using `writeln!(buf, \"\")` with an empty string"
190 }
191
192 declare_clippy_lint! {
193     /// ### What it does
194     /// This lint warns when you use `write!()` with a format
195     /// string that
196     /// ends in a newline.
197     ///
198     /// ### Why is this bad?
199     /// You should use `writeln!()` instead, which appends the
200     /// newline.
201     ///
202     /// ### Example
203     /// ```rust
204     /// # use std::fmt::Write;
205     /// # let mut buf = String::new();
206     /// # let name = "World";
207     /// // Bad
208     /// write!(buf, "Hello {}!\n", name);
209     ///
210     /// // Good
211     /// writeln!(buf, "Hello {}!", name);
212     /// ```
213     #[clippy::version = "pre 1.29.0"]
214     pub WRITE_WITH_NEWLINE,
215     style,
216     "using `write!()` with a format string that ends in a single newline"
217 }
218
219 declare_clippy_lint! {
220     /// ### What it does
221     /// This lint warns about the use of literals as `write!`/`writeln!` args.
222     ///
223     /// ### Why is this bad?
224     /// Using literals as `writeln!` args is inefficient
225     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
226     /// (i.e., just put the literal in the format string)
227     ///
228     /// ### Known problems
229     /// Will also warn with macro calls as arguments that expand to literals
230     /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
231     ///
232     /// ### Example
233     /// ```rust
234     /// # use std::fmt::Write;
235     /// # let mut buf = String::new();
236     /// // Bad
237     /// writeln!(buf, "{}", "foo");
238     ///
239     /// // Good
240     /// writeln!(buf, "foo");
241     /// ```
242     #[clippy::version = "pre 1.29.0"]
243     pub WRITE_LITERAL,
244     style,
245     "writing a literal with a format string"
246 }
247
248 #[derive(Default)]
249 pub struct Write {
250     in_debug_impl: bool,
251 }
252
253 impl_lint_pass!(Write => [
254     PRINT_WITH_NEWLINE,
255     PRINTLN_EMPTY_STRING,
256     PRINT_STDOUT,
257     PRINT_STDERR,
258     USE_DEBUG,
259     PRINT_LITERAL,
260     WRITE_WITH_NEWLINE,
261     WRITELN_EMPTY_STRING,
262     WRITE_LITERAL
263 ]);
264
265 impl EarlyLintPass for Write {
266     fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
267         if let ItemKind::Impl(box Impl {
268             of_trait: Some(trait_ref),
269             ..
270         }) = &item.kind
271         {
272             let trait_name = trait_ref
273                 .path
274                 .segments
275                 .iter()
276                 .last()
277                 .expect("path has at least one segment")
278                 .ident
279                 .name;
280             if trait_name == sym::Debug {
281                 self.in_debug_impl = true;
282             }
283         }
284     }
285
286     fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
287         self.in_debug_impl = false;
288     }
289
290     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
291         fn is_build_script(cx: &EarlyContext<'_>) -> bool {
292             // Cargo sets the crate name for build scripts to `build_script_build`
293             cx.sess()
294                 .opts
295                 .crate_name
296                 .as_ref()
297                 .map_or(false, |crate_name| crate_name == "build_script_build")
298         }
299
300         if mac.path == sym!(print) {
301             if !is_build_script(cx) {
302                 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
303             }
304             self.lint_print_with_newline(cx, mac);
305         } else if mac.path == sym!(println) {
306             if !is_build_script(cx) {
307                 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
308             }
309             self.lint_println_empty_string(cx, mac);
310         } else if mac.path == sym!(eprint) {
311             span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
312             self.lint_print_with_newline(cx, mac);
313         } else if mac.path == sym!(eprintln) {
314             span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
315             self.lint_println_empty_string(cx, mac);
316         } else if mac.path == sym!(write) {
317             if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
318                 if check_newlines(&fmt_str) {
319                     let (nl_span, only_nl) = newline_span(&fmt_str);
320                     let nl_span = match (dest, only_nl) {
321                         // Special case of `write!(buf, "\n")`: Mark everything from the end of
322                         // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
323                         (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
324                         _ => nl_span,
325                     };
326                     span_lint_and_then(
327                         cx,
328                         WRITE_WITH_NEWLINE,
329                         mac.span(),
330                         "using `write!()` with a format string that ends in a single newline",
331                         |err| {
332                             err.multipart_suggestion(
333                                 "use `writeln!()` instead",
334                                 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
335                                 Applicability::MachineApplicable,
336                             );
337                         },
338                     );
339                 }
340             }
341         } else if mac.path == sym!(writeln) {
342             if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
343                 if fmt_str.symbol == kw::Empty {
344                     let mut applicability = Applicability::MachineApplicable;
345                     // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
346                     #[allow(clippy::option_if_let_else)]
347                     let suggestion = if let Some(e) = expr {
348                         snippet_with_applicability(cx, e.span, "v", &mut applicability)
349                     } else {
350                         applicability = Applicability::HasPlaceholders;
351                         Cow::Borrowed("v")
352                     };
353
354                     span_lint_and_sugg(
355                         cx,
356                         WRITELN_EMPTY_STRING,
357                         mac.span(),
358                         format!("using `writeln!({}, \"\")`", suggestion).as_str(),
359                         "replace it with",
360                         format!("writeln!({})", suggestion),
361                         applicability,
362                     );
363                 }
364             }
365         }
366     }
367 }
368
369 /// Given a format string that ends in a newline and its span, calculates the span of the
370 /// newline, or the format string itself if the format string consists solely of a newline.
371 /// Return this and a boolean indicating whether it only consisted of a newline.
372 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
373     let sp = fmtstr.span;
374     let contents = fmtstr.symbol.as_str();
375
376     if contents == r"\n" {
377         return (sp, true);
378     }
379
380     let newline_sp_hi = sp.hi()
381         - match fmtstr.style {
382             StrStyle::Cooked => BytePos(1),
383             StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
384         };
385
386     let newline_sp_len = if contents.ends_with('\n') {
387         BytePos(1)
388     } else if contents.ends_with(r"\n") {
389         BytePos(2)
390     } else {
391         panic!("expected format string to contain a newline");
392     };
393
394     (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
395 }
396
397 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
398 /// empty format string.
399 #[derive(Default)]
400 struct SimpleFormatArgs {
401     unnamed: Vec<Vec<Span>>,
402     named: Vec<(Symbol, Vec<Span>)>,
403 }
404 impl SimpleFormatArgs {
405     fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
406         self.unnamed.iter().map(|x| match x.as_slice() {
407             // Ignore the dummy span added from out of order format arguments.
408             [DUMMY_SP] => &[],
409             x => x,
410         })
411     }
412
413     fn get_named(&self, n: &Path) -> &[Span] {
414         self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
415     }
416
417     fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
418         use rustc_parse_format::{
419             AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
420         };
421
422         const SIMPLE: FormatSpec<'_> = FormatSpec {
423             fill: None,
424             align: AlignUnknown,
425             flags: 0,
426             precision: CountImplied,
427             precision_span: None,
428             width: CountImplied,
429             width_span: None,
430             ty: "",
431             ty_span: None,
432         };
433
434         match arg.position {
435             ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
436                 if self.unnamed.len() <= n {
437                     // Use a dummy span to mark all unseen arguments.
438                     self.unnamed.resize_with(n, || vec![DUMMY_SP]);
439                     if arg.format == SIMPLE {
440                         self.unnamed.push(vec![span]);
441                     } else {
442                         self.unnamed.push(Vec::new());
443                     }
444                 } else {
445                     let args = &mut self.unnamed[n];
446                     match (args.as_mut_slice(), arg.format == SIMPLE) {
447                         // A non-empty format string has been seen already.
448                         ([], _) => (),
449                         // Replace the dummy span, if it exists.
450                         ([dummy @ DUMMY_SP], true) => *dummy = span,
451                         ([_, ..], true) => args.push(span),
452                         ([_, ..], false) => *args = Vec::new(),
453                     }
454                 }
455             },
456             ArgumentNamed(n) => {
457                 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
458                     match x.1.as_slice() {
459                         // A non-empty format string has been seen already.
460                         [] => (),
461                         [_, ..] if arg.format == SIMPLE => x.1.push(span),
462                         [_, ..] => x.1 = Vec::new(),
463                     }
464                 } else if arg.format == SIMPLE {
465                     self.named.push((n, vec![span]));
466                 } else {
467                     self.named.push((n, Vec::new()));
468                 }
469             },
470         };
471     }
472 }
473
474 impl Write {
475     /// Parses a format string into a collection of spans for each argument. This only keeps track
476     /// of empty format arguments. Will also lint usages of debug format strings outside of debug
477     /// impls.
478     fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
479         use rustc_parse_format::{ParseMode, Parser, Piece};
480
481         let str_sym = str_lit.symbol_unescaped.as_str();
482         let style = match str_lit.style {
483             StrStyle::Cooked => None,
484             StrStyle::Raw(n) => Some(n as usize),
485         };
486
487         let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
488         let mut args = SimpleFormatArgs::default();
489
490         while let Some(arg) = parser.next() {
491             let arg = match arg {
492                 Piece::String(_) => continue,
493                 Piece::NextArgument(arg) => arg,
494             };
495             let span = parser
496                 .arg_places
497                 .last()
498                 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
499
500             if !self.in_debug_impl && arg.format.ty == "?" {
501                 // FIXME: modify rustc's fmt string parser to give us the current span
502                 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
503             }
504
505             args.push(arg, span);
506         }
507
508         parser.errors.is_empty().then(move || args)
509     }
510
511     /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
512     /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
513     /// the contents of the string, whether it's a raw string, and the span of the literal in the
514     /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
515     /// `format_str` should be written to.
516     ///
517     /// Example:
518     ///
519     /// Calling this function on
520     /// ```rust
521     /// # use std::fmt::Write;
522     /// # let mut buf = String::new();
523     /// # let something = "something";
524     /// writeln!(buf, "string to write: {}", something);
525     /// ```
526     /// will return
527     /// ```rust,ignore
528     /// (Some("string to write: {}"), Some(buf))
529     /// ```
530     #[allow(clippy::too_many_lines)]
531     fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
532         let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None);
533         let expr = if is_write {
534             match parser
535                 .parse_expr()
536                 .map(rustc_ast::ptr::P::into_inner)
537                 .map_err(|mut e| e.cancel())
538             {
539                 // write!(e, ...)
540                 Ok(p) if parser.eat(&token::Comma) => Some(p),
541                 // write!(e) or error
542                 e => return (None, e.ok()),
543             }
544         } else {
545             None
546         };
547
548         let fmtstr = match parser.parse_str_lit() {
549             Ok(fmtstr) => fmtstr,
550             Err(_) => return (None, expr),
551         };
552
553         let args = match self.parse_fmt_string(cx, &fmtstr) {
554             Some(args) => args,
555             None => return (Some(fmtstr), expr),
556         };
557
558         let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
559         let mut unnamed_args = args.get_unnamed();
560         loop {
561             if !parser.eat(&token::Comma) {
562                 return (Some(fmtstr), expr);
563             }
564
565             let comma_span = parser.prev_token.span;
566             let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
567                 expr
568             } else {
569                 return (Some(fmtstr), None);
570             };
571             let (fmt_spans, lit) = match &token_expr.kind {
572                 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
573                 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
574                     (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
575                     _ => continue,
576                 },
577                 _ => {
578                     unnamed_args.next();
579                     continue;
580                 },
581             };
582
583             let replacement: String = match lit.token.kind {
584                 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
585                 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
586                     lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
587                 },
588                 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
589                     lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
590                 },
591                 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
592                 LitKind::Byte | LitKind::Char => match lit.token.symbol.as_str() {
593                     "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
594                     "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
595                     "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
596                     "\\'" => "'",
597                     "{" => "{{",
598                     "}" => "}}",
599                     x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
600                     x => x,
601                 }
602                 .into(),
603                 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
604             };
605
606             if !fmt_spans.is_empty() {
607                 span_lint_and_then(
608                     cx,
609                     lint,
610                     token_expr.span,
611                     "literal with an empty format string",
612                     |diag| {
613                         diag.multipart_suggestion(
614                             "try this",
615                             iter::once((comma_span.to(token_expr.span), String::new()))
616                                 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
617                                 .collect(),
618                             Applicability::MachineApplicable,
619                         );
620                     },
621                 );
622             }
623         }
624     }
625
626     fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
627         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
628             if fmt_str.symbol == kw::Empty {
629                 let name = mac.path.segments[0].ident.name;
630                 span_lint_and_sugg(
631                     cx,
632                     PRINTLN_EMPTY_STRING,
633                     mac.span(),
634                     &format!("using `{}!(\"\")`", name),
635                     "replace it with",
636                     format!("{}!()", name),
637                     Applicability::MachineApplicable,
638                 );
639             }
640         }
641     }
642
643     fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
644         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
645             if check_newlines(&fmt_str) {
646                 let name = mac.path.segments[0].ident.name;
647                 let suggested = format!("{}ln", name);
648                 span_lint_and_then(
649                     cx,
650                     PRINT_WITH_NEWLINE,
651                     mac.span(),
652                     &format!("using `{}!()` with a format string that ends in a single newline", name),
653                     |err| {
654                         err.multipart_suggestion(
655                             &format!("use `{}!` instead", suggested),
656                             vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
657                             Applicability::MachineApplicable,
658                         );
659                     },
660                 );
661             }
662         }
663     }
664 }
665
666 /// Checks if the format string contains a single newline that terminates it.
667 ///
668 /// Literal and escaped newlines are both checked (only literal for raw strings).
669 fn check_newlines(fmtstr: &StrLit) -> bool {
670     let mut has_internal_newline = false;
671     let mut last_was_cr = false;
672     let mut should_lint = false;
673
674     let contents = fmtstr.symbol.as_str();
675
676     let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
677         let c = c.unwrap();
678
679         if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
680             should_lint = true;
681         } else {
682             last_was_cr = c == '\r';
683             if c == '\n' {
684                 has_internal_newline = true;
685             }
686         }
687     };
688
689     match fmtstr.style {
690         StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
691         StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),
692     }
693
694     should_lint
695 }