]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/write.rs
Fix lint registration
[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, DiagnosticBuilder};
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, InnerSpan, 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                     let suggestion = if let Some(e) = expr {
346                         snippet_with_applicability(cx, e.span, "v", &mut applicability)
347                     } else {
348                         applicability = Applicability::HasPlaceholders;
349                         Cow::Borrowed("v")
350                     };
351
352                     span_lint_and_sugg(
353                         cx,
354                         WRITELN_EMPTY_STRING,
355                         mac.span(),
356                         format!("using `writeln!({}, \"\")`", suggestion).as_str(),
357                         "replace it with",
358                         format!("writeln!({})", suggestion),
359                         applicability,
360                     );
361                 }
362             }
363         }
364     }
365 }
366
367 /// Given a format string that ends in a newline and its span, calculates the span of the
368 /// newline, or the format string itself if the format string consists solely of a newline.
369 /// Return this and a boolean indicating whether it only consisted of a newline.
370 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
371     let sp = fmtstr.span;
372     let contents = fmtstr.symbol.as_str();
373
374     if contents == r"\n" {
375         return (sp, true);
376     }
377
378     let newline_sp_hi = sp.hi()
379         - match fmtstr.style {
380             StrStyle::Cooked => BytePos(1),
381             StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
382         };
383
384     let newline_sp_len = if contents.ends_with('\n') {
385         BytePos(1)
386     } else if contents.ends_with(r"\n") {
387         BytePos(2)
388     } else {
389         panic!("expected format string to contain a newline");
390     };
391
392     (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
393 }
394
395 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
396 /// empty format string.
397 #[derive(Default)]
398 struct SimpleFormatArgs {
399     unnamed: Vec<Vec<Span>>,
400     named: Vec<(Symbol, Vec<Span>)>,
401 }
402 impl SimpleFormatArgs {
403     fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
404         self.unnamed.iter().map(|x| match x.as_slice() {
405             // Ignore the dummy span added from out of order format arguments.
406             [DUMMY_SP] => &[],
407             x => x,
408         })
409     }
410
411     fn get_named(&self, n: &Path) -> &[Span] {
412         self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
413     }
414
415     fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
416         use rustc_parse_format::{
417             AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
418         };
419
420         const SIMPLE: FormatSpec<'_> = FormatSpec {
421             fill: None,
422             align: AlignUnknown,
423             flags: 0,
424             precision: CountImplied,
425             precision_span: None,
426             width: CountImplied,
427             width_span: None,
428             ty: "",
429             ty_span: None,
430         };
431
432         match arg.position {
433             ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
434                 if self.unnamed.len() <= n {
435                     // Use a dummy span to mark all unseen arguments.
436                     self.unnamed.resize_with(n, || vec![DUMMY_SP]);
437                     if arg.format == SIMPLE {
438                         self.unnamed.push(vec![span]);
439                     } else {
440                         self.unnamed.push(Vec::new());
441                     }
442                 } else {
443                     let args = &mut self.unnamed[n];
444                     match (args.as_mut_slice(), arg.format == SIMPLE) {
445                         // A non-empty format string has been seen already.
446                         ([], _) => (),
447                         // Replace the dummy span, if it exists.
448                         ([dummy @ DUMMY_SP], true) => *dummy = span,
449                         ([_, ..], true) => args.push(span),
450                         ([_, ..], false) => *args = Vec::new(),
451                     }
452                 }
453             },
454             ArgumentNamed(n, _) => {
455                 let n = Symbol::intern(n);
456                 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
457                     match x.1.as_slice() {
458                         // A non-empty format string has been seen already.
459                         [] => (),
460                         [_, ..] if arg.format == SIMPLE => x.1.push(span),
461                         [_, ..] => x.1 = Vec::new(),
462                     }
463                 } else if arg.format == SIMPLE {
464                     self.named.push((n, vec![span]));
465                 } else {
466                     self.named.push((n, Vec::new()));
467                 }
468             },
469         };
470     }
471 }
472
473 impl Write {
474     /// Parses a format string into a collection of spans for each argument. This only keeps track
475     /// of empty format arguments. Will also lint usages of debug format strings outside of debug
476     /// impls.
477     fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
478         use rustc_parse_format::{ParseMode, Parser, Piece};
479
480         let str_sym = str_lit.symbol_unescaped.as_str();
481         let style = match str_lit.style {
482             StrStyle::Cooked => None,
483             StrStyle::Raw(n) => Some(n as usize),
484         };
485
486         let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
487         let mut args = SimpleFormatArgs::default();
488
489         while let Some(arg) = parser.next() {
490             let arg = match arg {
491                 Piece::String(_) => continue,
492                 Piece::NextArgument(arg) => arg,
493             };
494             let span = parser
495                 .arg_places
496                 .last()
497                 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(InnerSpan::new(x.start, x.end)));
498
499             if !self.in_debug_impl && arg.format.ty == "?" {
500                 // FIXME: modify rustc's fmt string parser to give us the current span
501                 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
502             }
503
504             args.push(arg, span);
505         }
506
507         parser.errors.is_empty().then(move || args)
508     }
509
510     /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
511     /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
512     /// the contents of the string, whether it's a raw string, and the span of the literal in the
513     /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
514     /// `format_str` should be written to.
515     ///
516     /// Example:
517     ///
518     /// Calling this function on
519     /// ```rust
520     /// # use std::fmt::Write;
521     /// # let mut buf = String::new();
522     /// # let something = "something";
523     /// writeln!(buf, "string to write: {}", something);
524     /// ```
525     /// will return
526     /// ```rust,ignore
527     /// (Some("string to write: {}"), Some(buf))
528     /// ```
529     fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
530         let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None);
531         let expr = if is_write {
532             match parser
533                 .parse_expr()
534                 .map(rustc_ast::ptr::P::into_inner)
535                 .map_err(DiagnosticBuilder::cancel)
536             {
537                 // write!(e, ...)
538                 Ok(p) if parser.eat(&token::Comma) => Some(p),
539                 // write!(e) or error
540                 e => return (None, e.ok()),
541             }
542         } else {
543             None
544         };
545
546         let fmtstr = match parser.parse_str_lit() {
547             Ok(fmtstr) => fmtstr,
548             Err(_) => return (None, expr),
549         };
550
551         let args = match self.parse_fmt_string(cx, &fmtstr) {
552             Some(args) => args,
553             None => return (Some(fmtstr), expr),
554         };
555
556         let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
557         let mut unnamed_args = args.get_unnamed();
558         loop {
559             if !parser.eat(&token::Comma) {
560                 return (Some(fmtstr), expr);
561             }
562
563             let comma_span = parser.prev_token.span;
564             let token_expr = if let Ok(expr) = parser.parse_expr().map_err(DiagnosticBuilder::cancel) {
565                 expr
566             } else {
567                 return (Some(fmtstr), None);
568             };
569             let (fmt_spans, lit) = match &token_expr.kind {
570                 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
571                 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
572                     (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
573                     _ => continue,
574                 },
575                 _ => {
576                     unnamed_args.next();
577                     continue;
578                 },
579             };
580
581             let replacement: String = match lit.token.kind {
582                 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
583                     lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
584                 },
585                 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
586                     lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
587                 },
588                 LitKind::StrRaw(_)
589                 | LitKind::Str
590                 | LitKind::ByteStrRaw(_)
591                 | LitKind::ByteStr
592                 | LitKind::Integer
593                 | LitKind::Float
594                 | LitKind::Err => continue,
595                 LitKind::Byte | LitKind::Char => match lit.token.symbol.as_str() {
596                     "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
597                     "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
598                     "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
599                     "\\'" => "'",
600                     "{" => "{{",
601                     "}" => "}}",
602                     x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
603                     x => x,
604                 }
605                 .into(),
606                 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
607             };
608
609             if !fmt_spans.is_empty() {
610                 span_lint_and_then(
611                     cx,
612                     lint,
613                     token_expr.span,
614                     "literal with an empty format string",
615                     |diag| {
616                         diag.multipart_suggestion(
617                             "try this",
618                             iter::once((comma_span.to(token_expr.span), String::new()))
619                                 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
620                                 .collect(),
621                             Applicability::MachineApplicable,
622                         );
623                     },
624                 );
625             }
626         }
627     }
628
629     fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
630         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
631             if fmt_str.symbol == kw::Empty {
632                 let name = mac.path.segments[0].ident.name;
633                 span_lint_and_sugg(
634                     cx,
635                     PRINTLN_EMPTY_STRING,
636                     mac.span(),
637                     &format!("using `{}!(\"\")`", name),
638                     "replace it with",
639                     format!("{}!()", name),
640                     Applicability::MachineApplicable,
641                 );
642             }
643         }
644     }
645
646     fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
647         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
648             if check_newlines(&fmt_str) {
649                 let name = mac.path.segments[0].ident.name;
650                 let suggested = format!("{}ln", name);
651                 span_lint_and_then(
652                     cx,
653                     PRINT_WITH_NEWLINE,
654                     mac.span(),
655                     &format!("using `{}!()` with a format string that ends in a single newline", name),
656                     |err| {
657                         err.multipart_suggestion(
658                             &format!("use `{}!` instead", suggested),
659                             vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
660                             Applicability::MachineApplicable,
661                         );
662                     },
663                 );
664             }
665         }
666     }
667 }
668
669 /// Checks if the format string contains a single newline that terminates it.
670 ///
671 /// Literal and escaped newlines are both checked (only literal for raw strings).
672 fn check_newlines(fmtstr: &StrLit) -> bool {
673     let mut has_internal_newline = false;
674     let mut last_was_cr = false;
675     let mut should_lint = false;
676
677     let contents = fmtstr.symbol.as_str();
678
679     let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
680         let c = c.unwrap();
681
682         if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
683             should_lint = true;
684         } else {
685             last_was_cr = c == '\r';
686             if c == '\n' {
687                 has_internal_newline = true;
688             }
689         }
690     };
691
692     match fmtstr.style {
693         StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
694         StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),
695     }
696
697     should_lint
698 }