1 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
2 use rustc::{declare_tool_lint, lint_array};
4 use syntax::tokenstream::{ThinTokenStream, TokenStream};
5 use syntax::parse::{token, parser};
7 use crate::utils::{span_lint, span_lint_and_sugg, snippet};
9 /// **What it does:** This lint warns when you use `println!("")` to
12 /// **Why is this bad?** You should use `println!()`, which is simpler.
14 /// **Known problems:** None.
20 declare_clippy_lint! {
21 pub PRINTLN_EMPTY_STRING,
23 "using `println!(\"\")` with an empty string"
26 /// **What it does:** This lint warns when you use `print!()` with a format
28 /// ends in a newline.
30 /// **Why is this bad?** You should use `println!()` instead, which appends the
33 /// **Known problems:** None.
37 /// print!("Hello {}!\n", name);
39 /// use println!() instead
41 /// println!("Hello {}!", name);
43 declare_clippy_lint! {
44 pub PRINT_WITH_NEWLINE,
46 "using `print!()` with a format string that ends in a single newline"
49 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
50 /// is to catch debugging remnants.
52 /// **Why is this bad?** People often print on *stdout* while debugging an
53 /// application and might forget to remove those prints afterward.
55 /// **Known problems:** Only catches `print!` and `println!` calls.
59 /// println!("Hello world!");
61 declare_clippy_lint! {
67 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
68 /// lint is to catch debugging remnants.
70 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
71 /// debugging Rust code. It should not be used in in user-facing output.
75 /// println!("{:?}", foo);
77 declare_clippy_lint! {
80 "use of `Debug`-based formatting"
83 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
85 /// **Why is this bad?** Using literals as `println!` args is inefficient
86 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
87 /// (i.e., just put the literal in the format string)
89 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
90 /// -- e.g., `println!("{}", env!("FOO"))`.
94 /// println!("{}", "foo");
96 /// use the literal without formatting:
100 declare_clippy_lint! {
103 "printing a literal with a format string"
106 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
109 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
111 /// **Known problems:** None.
117 declare_clippy_lint! {
118 pub WRITELN_EMPTY_STRING,
120 "using `writeln!(\"\")` with an empty string"
123 /// **What it does:** This lint warns when you use `write!()` with a format
125 /// ends in a newline.
127 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
130 /// **Known problems:** None.
134 /// write!(buf, "Hello {}!\n", name);
136 declare_clippy_lint! {
137 pub WRITE_WITH_NEWLINE,
139 "using `write!()` with a format string that ends in a single newline"
142 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
144 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
145 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
146 /// (i.e., just put the literal in the format string)
148 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
149 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
153 /// writeln!(buf, "{}", "foo");
155 declare_clippy_lint! {
158 "writing a literal with a format string"
161 #[derive(Copy, Clone, Debug)]
164 impl LintPass for Pass {
165 fn get_lints(&self) -> LintArray {
168 PRINTLN_EMPTY_STRING,
173 WRITELN_EMPTY_STRING,
179 impl EarlyLintPass for Pass {
180 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
181 if mac.node.path == "println" {
182 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
183 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
187 PRINTLN_EMPTY_STRING,
189 "using `println!(\"\")`",
191 "println!()".to_string(),
195 } else if mac.node.path == "print" {
196 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
197 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
198 if fmtstr.ends_with("\\n") && !fmtstr.ends_with("\\n\\n") {
199 span_lint(cx, PRINT_WITH_NEWLINE, mac.span,
200 "using `print!()` with a format string that ends in a \
201 single newline, consider using `println!()` instead");
204 } else if mac.node.path == "write" {
205 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true).0 {
206 if fmtstr.ends_with("\\n") && !fmtstr.ends_with("\\n\\n") {
207 span_lint(cx, WRITE_WITH_NEWLINE, mac.span,
208 "using `write!()` with a format string that ends in a \
209 single newline, consider using `writeln!()` instead");
212 } else if mac.node.path == "writeln" {
213 let check_tts = check_tts(cx, &mac.node.tts, true);
214 if let Some(fmtstr) = check_tts.0 {
216 let suggestion = check_tts.1.map_or(Cow::Borrowed("v"), |expr| snippet(cx, expr.span, "v"));
220 WRITELN_EMPTY_STRING,
222 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
224 format!("writeln!({})", suggestion),
232 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &ThinTokenStream, is_write: bool) -> (Option<String>, Option<Expr>) {
233 let tts = TokenStream::from(tts.clone());
234 let mut parser = parser::Parser::new(
241 let mut expr: Option<Expr> = None;
243 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
244 Ok(p) => Some(p.into_inner()),
245 Err(_) => return (None, None),
247 // might be `writeln!(foo)`
248 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
253 let fmtstr = match parser.parse_str().map_err(|mut err| err.cancel()) {
254 Ok(token) => token.0.to_string(),
255 Err(_) => return (None, expr),
258 let tmp = fmtstr.clone();
259 let mut args = vec![];
260 let mut fmt_parser = Parser::new(&tmp, None);
261 while let Some(piece) = fmt_parser.next() {
262 if !fmt_parser.errors.is_empty() {
265 if let Piece::NextArgument(arg) = piece {
266 if arg.format.ty == "?" {
267 // FIXME: modify rustc's fmt string parser to give us the current span
268 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
273 let lint = if is_write {
280 if !parser.eat(&token::Comma) {
281 assert!(parser.eat(&token::Eof));
282 return (Some(fmtstr), expr);
284 let token_expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
286 Err(_) => return (Some(fmtstr), None),
288 const SIMPLE: FormatSpec<'_> = FormatSpec {
292 precision: CountImplied,
296 match &token_expr.node {
297 ExprKind::Lit(_) => {
298 let mut all_simple = true;
299 let mut seen = false;
302 | ArgumentImplicitlyIs(n)
305 all_simple &= arg.format == SIMPLE;
308 ArgumentNamed(_) => {},
311 if all_simple && seen {
312 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
316 ExprKind::Assign(lhs, rhs) => {
317 if let ExprKind::Lit(_) = rhs.node {
318 if let ExprKind::Path(_, p) = &lhs.node {
319 let mut all_simple = true;
320 let mut seen = false;
323 | ArgumentImplicitlyIs(_)
326 ArgumentNamed(name) => if *p == name {
328 all_simple &= arg.format == SIMPLE;
332 if all_simple && seen {
333 span_lint(cx, lint, rhs.span, "literal with an empty format string");