2019-11-02 23:41:22 -05:00
|
|
|
use std::borrow::Cow;
|
2021-03-25 13:29:11 -05:00
|
|
|
use std::iter;
|
|
|
|
use std::ops::{Deref, Range};
|
|
|
|
|
|
|
|
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
|
|
|
|
use clippy_utils::source::{snippet_opt, snippet_with_applicability};
|
2021-11-07 02:43:49 -06:00
|
|
|
use rustc_ast::ast::{Expr, ExprKind, Impl, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
|
2021-03-25 13:29:11 -05:00
|
|
|
use rustc_ast::token::{self, LitKind};
|
2020-02-29 21:23:33 -06:00
|
|
|
use rustc_ast::tokenstream::TokenStream;
|
2022-03-14 06:02:53 -05:00
|
|
|
use rustc_errors::{Applicability, DiagnosticBuilder};
|
2019-11-02 23:41:22 -05:00
|
|
|
use rustc_lexer::unescape::{self, EscapeError};
|
2021-12-04 09:09:15 -06:00
|
|
|
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
|
2019-11-10 22:22:50 -06:00
|
|
|
use rustc_parse::parser;
|
2020-01-14 09:28:08 -06:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2021-03-25 13:29:11 -05:00
|
|
|
use rustc_span::symbol::{kw, Symbol};
|
2022-04-29 11:48:58 -05:00
|
|
|
use rustc_span::{sym, BytePos, InnerSpan, Span, DUMMY_SP};
|
2018-04-04 22:46:39 -05:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns when you use `println!("")` to
|
2019-03-05 10:50:33 -06:00
|
|
|
/// print a newline.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// You should use `println!()`, which is simpler.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```rust
|
|
|
|
/// println!("");
|
2022-06-16 10:39:06 -05:00
|
|
|
/// ```
|
2020-07-14 07:59:59 -05:00
|
|
|
///
|
2022-06-16 10:39:06 -05:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
2020-07-14 07:59:59 -05:00
|
|
|
/// println!();
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub PRINTLN_EMPTY_STRING,
|
|
|
|
style,
|
|
|
|
"using `println!(\"\")` with an empty string"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns when you use `print!()` with a format
|
2020-07-14 07:59:59 -05:00
|
|
|
/// string that ends in a newline.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// You should use `println!()` instead, which appends the
|
2019-03-05 10:50:33 -06:00
|
|
|
/// newline.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-09 01:51:23 -06:00
|
|
|
/// ```rust
|
|
|
|
/// # let name = "World";
|
2019-03-05 10:50:33 -06:00
|
|
|
/// print!("Hello {}!\n", name);
|
|
|
|
/// ```
|
|
|
|
/// use println!() instead
|
2019-03-09 01:51:23 -06:00
|
|
|
/// ```rust
|
|
|
|
/// # let name = "World";
|
2019-03-05 10:50:33 -06:00
|
|
|
/// println!("Hello {}!", name);
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub PRINT_WITH_NEWLINE,
|
|
|
|
style,
|
2018-08-07 15:01:10 -05:00
|
|
|
"using `print!()` with a format string that ends in a single newline"
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for printing on *stdout*. The purpose of this lint
|
2019-03-05 10:50:33 -06:00
|
|
|
/// is to catch debugging remnants.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// People often print on *stdout* while debugging an
|
2019-03-05 10:50:33 -06:00
|
|
|
/// application and might forget to remove those prints afterward.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
2021-12-06 05:33:31 -06:00
|
|
|
/// * Only catches `print!` and `println!` calls.
|
|
|
|
/// * The lint level is unaffected by crate attributes. The level can still
|
|
|
|
/// be set for functions, modules and other items. To change the level for
|
|
|
|
/// the entire crate, please use command line flags. More information and a
|
|
|
|
/// configuration example can be found in [clippy#6610].
|
|
|
|
///
|
|
|
|
/// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```rust
|
|
|
|
/// println!("Hello world!");
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub PRINT_STDOUT,
|
|
|
|
restriction,
|
|
|
|
"printing on stdout"
|
|
|
|
}
|
|
|
|
|
2020-12-20 10:19:49 -06:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for printing on *stderr*. The purpose of this lint
|
2020-12-20 10:19:49 -06:00
|
|
|
/// is to catch debugging remnants.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// People often print on *stderr* while debugging an
|
2020-12-20 10:19:49 -06:00
|
|
|
/// application and might forget to remove those prints afterward.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
2021-12-06 05:33:31 -06:00
|
|
|
/// * Only catches `eprint!` and `eprintln!` calls.
|
|
|
|
/// * The lint level is unaffected by crate attributes. The level can still
|
|
|
|
/// be set for functions, modules and other items. To change the level for
|
|
|
|
/// the entire crate, please use command line flags. More information and a
|
|
|
|
/// configuration example can be found in [clippy#6610].
|
|
|
|
///
|
|
|
|
/// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
|
2020-12-20 10:19:49 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2020-12-20 10:19:49 -06:00
|
|
|
/// ```rust
|
|
|
|
/// eprintln!("Hello world!");
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "1.50.0"]
|
2020-12-20 10:19:49 -06:00
|
|
|
pub PRINT_STDERR,
|
|
|
|
restriction,
|
|
|
|
"printing on stderr"
|
|
|
|
}
|
|
|
|
|
2018-04-04 22:46:39 -05:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for use of `Debug` formatting. The purpose of this
|
2019-03-05 10:50:33 -06:00
|
|
|
/// lint is to catch debugging remnants.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// The purpose of the `Debug` trait is to facilitate
|
2019-08-11 05:56:30 -05:00
|
|
|
/// debugging Rust code. It should not be used in user-facing output.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```rust
|
2019-08-03 14:24:50 -05:00
|
|
|
/// # let foo = "bar";
|
2019-03-05 10:50:33 -06:00
|
|
|
/// println!("{:?}", foo);
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub USE_DEBUG,
|
|
|
|
restriction,
|
|
|
|
"use of `Debug`-based formatting"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns about the use of literals as `print!`/`println!` args.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Using literals as `println!` args is inefficient
|
2019-03-05 10:50:33 -06:00
|
|
|
/// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
|
|
|
|
/// (i.e., just put the literal in the format string)
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
|
|
|
/// Will also warn with macro calls as arguments that expand to literals
|
2019-03-05 10:50:33 -06:00
|
|
|
/// -- e.g., `println!("{}", env!("FOO"))`.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```rust
|
|
|
|
/// println!("{}", "foo");
|
|
|
|
/// ```
|
|
|
|
/// use the literal without formatting:
|
|
|
|
/// ```rust
|
|
|
|
/// println!("foo");
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub PRINT_LITERAL,
|
|
|
|
style,
|
|
|
|
"printing a literal with a format string"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns when you use `writeln!(buf, "")` to
|
2019-03-05 10:50:33 -06:00
|
|
|
/// print a newline.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// You should use `writeln!(buf)`, which is simpler.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-09 01:51:23 -06:00
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
2019-03-05 16:23:50 -06:00
|
|
|
/// writeln!(buf, "");
|
2022-06-16 10:39:06 -05:00
|
|
|
/// ```
|
2020-07-14 07:59:59 -05:00
|
|
|
///
|
2022-06-16 10:39:06 -05:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
2020-07-14 07:59:59 -05:00
|
|
|
/// writeln!(buf);
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub WRITELN_EMPTY_STRING,
|
|
|
|
style,
|
2019-03-05 16:23:50 -06:00
|
|
|
"using `writeln!(buf, \"\")` with an empty string"
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns when you use `write!()` with a format
|
2019-03-05 10:50:33 -06:00
|
|
|
/// string that
|
|
|
|
/// ends in a newline.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// You should use `writeln!()` instead, which appends the
|
2019-03-05 10:50:33 -06:00
|
|
|
/// newline.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-09 01:51:23 -06:00
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
|
|
|
/// # let name = "World";
|
2019-03-05 10:50:33 -06:00
|
|
|
/// write!(buf, "Hello {}!\n", name);
|
2022-06-16 10:39:06 -05:00
|
|
|
/// ```
|
2020-07-14 07:59:59 -05:00
|
|
|
///
|
2022-06-16 10:39:06 -05:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
|
|
|
/// # let name = "World";
|
2020-07-14 07:59:59 -05:00
|
|
|
/// writeln!(buf, "Hello {}!", name);
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub WRITE_WITH_NEWLINE,
|
|
|
|
style,
|
2018-08-07 15:01:10 -05:00
|
|
|
"using `write!()` with a format string that ends in a single newline"
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// This lint warns about the use of literals as `write!`/`writeln!` args.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Using literals as `writeln!` args is inefficient
|
2019-03-05 10:50:33 -06:00
|
|
|
/// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
|
|
|
|
/// (i.e., just put the literal in the format string)
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
|
|
|
/// Will also warn with macro calls as arguments that expand to literals
|
2019-03-05 10:50:33 -06:00
|
|
|
/// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-03-09 01:51:23 -06:00
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
2019-03-05 10:50:33 -06:00
|
|
|
/// writeln!(buf, "{}", "foo");
|
2022-06-16 10:39:06 -05:00
|
|
|
/// ```
|
2020-07-14 07:59:59 -05:00
|
|
|
///
|
2022-06-16 10:39:06 -05:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
2020-07-14 07:59:59 -05:00
|
|
|
/// writeln!(buf, "foo");
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-04-04 22:46:39 -05:00
|
|
|
pub WRITE_LITERAL,
|
|
|
|
style,
|
|
|
|
"writing a literal with a format string"
|
|
|
|
}
|
|
|
|
|
2020-01-14 09:28:08 -06:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct Write {
|
|
|
|
in_debug_impl: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(Write => [
|
2019-04-08 15:43:55 -05:00
|
|
|
PRINT_WITH_NEWLINE,
|
|
|
|
PRINTLN_EMPTY_STRING,
|
|
|
|
PRINT_STDOUT,
|
2020-12-20 10:19:49 -06:00
|
|
|
PRINT_STDERR,
|
2019-04-08 15:43:55 -05:00
|
|
|
USE_DEBUG,
|
|
|
|
PRINT_LITERAL,
|
|
|
|
WRITE_WITH_NEWLINE,
|
|
|
|
WRITELN_EMPTY_STRING,
|
|
|
|
WRITE_LITERAL
|
|
|
|
]);
|
2018-04-04 22:46:39 -05:00
|
|
|
|
2019-04-08 15:43:55 -05:00
|
|
|
impl EarlyLintPass for Write {
|
2020-01-14 09:28:08 -06:00
|
|
|
fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
|
2021-11-07 02:43:49 -06:00
|
|
|
if let ItemKind::Impl(box Impl {
|
2021-02-02 22:43:30 -06:00
|
|
|
of_trait: Some(trait_ref),
|
|
|
|
..
|
|
|
|
}) = &item.kind
|
|
|
|
{
|
2020-01-14 09:28:08 -06:00
|
|
|
let trait_name = trait_ref
|
|
|
|
.path
|
|
|
|
.segments
|
|
|
|
.iter()
|
|
|
|
.last()
|
|
|
|
.expect("path has at least one segment")
|
|
|
|
.ident
|
|
|
|
.name;
|
2020-11-05 07:29:48 -06:00
|
|
|
if trait_name == sym::Debug {
|
2020-01-14 09:28:08 -06:00
|
|
|
self.in_debug_impl = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
|
|
|
|
self.in_debug_impl = false;
|
|
|
|
}
|
|
|
|
|
2020-03-15 12:23:43 -05:00
|
|
|
fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
|
2020-10-09 05:45:29 -05:00
|
|
|
fn is_build_script(cx: &EarlyContext<'_>) -> bool {
|
|
|
|
// Cargo sets the crate name for build scripts to `build_script_build`
|
2021-12-04 09:09:15 -06:00
|
|
|
cx.sess()
|
2020-10-09 05:45:29 -05:00
|
|
|
.opts
|
|
|
|
.crate_name
|
|
|
|
.as_ref()
|
|
|
|
.map_or(false, |crate_name| crate_name == "build_script_build")
|
|
|
|
}
|
|
|
|
|
2020-12-20 10:19:49 -06:00
|
|
|
if mac.path == sym!(print) {
|
2020-10-09 05:45:29 -05:00
|
|
|
if !is_build_script(cx) {
|
|
|
|
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
|
|
|
|
}
|
2020-12-20 10:19:49 -06:00
|
|
|
self.lint_print_with_newline(cx, mac);
|
|
|
|
} else if mac.path == sym!(println) {
|
|
|
|
if !is_build_script(cx) {
|
|
|
|
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
2020-12-20 10:19:49 -06:00
|
|
|
self.lint_println_empty_string(cx, mac);
|
|
|
|
} else if mac.path == sym!(eprint) {
|
|
|
|
span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
|
|
|
|
self.lint_print_with_newline(cx, mac);
|
|
|
|
} else if mac.path == sym!(eprintln) {
|
|
|
|
span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
|
|
|
|
self.lint_println_empty_string(cx, mac);
|
2019-08-15 21:30:38 -05:00
|
|
|
} else if mac.path == sym!(write) {
|
2021-05-20 05:30:31 -05:00
|
|
|
if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
|
2019-11-18 09:38:36 -06:00
|
|
|
if check_newlines(&fmt_str) {
|
2021-05-20 05:30:31 -05:00
|
|
|
let (nl_span, only_nl) = newline_span(&fmt_str);
|
|
|
|
let nl_span = match (dest, only_nl) {
|
|
|
|
// Special case of `write!(buf, "\n")`: Mark everything from the end of
|
|
|
|
// `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
|
2021-08-21 10:07:21 -05:00
|
|
|
(Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
|
2021-05-20 05:30:31 -05:00
|
|
|
_ => nl_span,
|
|
|
|
};
|
2019-05-23 13:11:38 -05:00
|
|
|
span_lint_and_then(
|
2018-09-06 05:33:00 -05:00
|
|
|
cx,
|
|
|
|
WRITE_WITH_NEWLINE,
|
2019-12-03 10:54:32 -06:00
|
|
|
mac.span(),
|
2019-05-23 13:11:38 -05:00
|
|
|
"using `write!()` with a format string that ends in a single newline",
|
|
|
|
|err| {
|
|
|
|
err.multipart_suggestion(
|
|
|
|
"use `writeln!()` instead",
|
2021-05-20 05:30:31 -05:00
|
|
|
vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
|
2019-05-23 13:11:38 -05:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
},
|
2021-06-03 01:41:37 -05:00
|
|
|
);
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
|
|
|
}
|
2019-08-15 21:30:38 -05:00
|
|
|
} else if mac.path == sym!(writeln) {
|
2020-08-28 09:10:16 -05:00
|
|
|
if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
|
2021-01-15 03:56:44 -06:00
|
|
|
if fmt_str.symbol == kw::Empty {
|
2018-11-27 08:13:57 -06:00
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
2020-08-28 09:10:16 -05:00
|
|
|
let suggestion = if let Some(e) = expr {
|
|
|
|
snippet_with_applicability(cx, e.span, "v", &mut applicability)
|
|
|
|
} else {
|
|
|
|
applicability = Applicability::HasPlaceholders;
|
|
|
|
Cow::Borrowed("v")
|
|
|
|
};
|
2018-08-20 07:03:13 -05:00
|
|
|
|
2018-07-22 17:19:07 -05:00
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
WRITELN_EMPTY_STRING,
|
2019-12-03 10:54:32 -06:00
|
|
|
mac.span(),
|
2018-08-20 08:50:15 -05:00
|
|
|
format!("using `writeln!({}, \"\")`", suggestion).as_str(),
|
2018-07-22 17:19:07 -05:00
|
|
|
"replace it with",
|
2018-08-20 08:33:43 -05:00
|
|
|
format!("writeln!({})", suggestion),
|
2018-11-27 08:13:57 -06:00
|
|
|
applicability,
|
2018-07-22 17:19:07 -05:00
|
|
|
);
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-18 09:38:36 -06:00
|
|
|
/// Given a format string that ends in a newline and its span, calculates the span of the
|
2020-09-24 07:49:22 -05:00
|
|
|
/// newline, or the format string itself if the format string consists solely of a newline.
|
2021-05-20 05:30:31 -05:00
|
|
|
/// Return this and a boolean indicating whether it only consisted of a newline.
|
|
|
|
fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
|
2019-11-18 09:38:36 -06:00
|
|
|
let sp = fmtstr.span;
|
2021-12-14 21:39:23 -06:00
|
|
|
let contents = fmtstr.symbol.as_str();
|
2019-05-23 13:11:38 -05:00
|
|
|
|
2021-12-14 21:39:23 -06:00
|
|
|
if contents == r"\n" {
|
2021-05-20 05:30:31 -05:00
|
|
|
return (sp, true);
|
2020-09-24 07:49:22 -05:00
|
|
|
}
|
|
|
|
|
2019-11-18 09:38:36 -06:00
|
|
|
let newline_sp_hi = sp.hi()
|
|
|
|
- match fmtstr.style {
|
|
|
|
StrStyle::Cooked => BytePos(1),
|
|
|
|
StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
|
2019-05-23 13:11:38 -05:00
|
|
|
};
|
|
|
|
|
2019-11-18 09:38:36 -06:00
|
|
|
let newline_sp_len = if contents.ends_with('\n') {
|
|
|
|
BytePos(1)
|
|
|
|
} else if contents.ends_with(r"\n") {
|
|
|
|
BytePos(2)
|
|
|
|
} else {
|
|
|
|
panic!("expected format string to contain a newline");
|
|
|
|
};
|
|
|
|
|
2021-05-20 05:30:31 -05:00
|
|
|
(sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
|
2019-05-23 13:11:38 -05:00
|
|
|
}
|
|
|
|
|
2021-03-25 13:29:11 -05:00
|
|
|
/// Stores a list of replacement spans for each argument, but only if all the replacements used an
|
|
|
|
/// empty format string.
|
|
|
|
#[derive(Default)]
|
|
|
|
struct SimpleFormatArgs {
|
|
|
|
unnamed: Vec<Vec<Span>>,
|
|
|
|
named: Vec<(Symbol, Vec<Span>)>,
|
|
|
|
}
|
|
|
|
impl SimpleFormatArgs {
|
|
|
|
fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
|
|
|
|
self.unnamed.iter().map(|x| match x.as_slice() {
|
|
|
|
// Ignore the dummy span added from out of order format arguments.
|
|
|
|
[DUMMY_SP] => &[],
|
|
|
|
x => x,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_named(&self, n: &Path) -> &[Span] {
|
|
|
|
self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
|
|
|
|
use rustc_parse_format::{
|
|
|
|
AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
|
|
|
|
};
|
|
|
|
|
|
|
|
const SIMPLE: FormatSpec<'_> = FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
precision_span: None,
|
|
|
|
width: CountImplied,
|
|
|
|
width_span: None,
|
|
|
|
ty: "",
|
|
|
|
ty_span: None,
|
|
|
|
};
|
|
|
|
|
|
|
|
match arg.position {
|
2022-07-31 10:11:00 -05:00
|
|
|
ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
|
2021-03-25 13:29:11 -05:00
|
|
|
if self.unnamed.len() <= n {
|
|
|
|
// Use a dummy span to mark all unseen arguments.
|
|
|
|
self.unnamed.resize_with(n, || vec![DUMMY_SP]);
|
|
|
|
if arg.format == SIMPLE {
|
|
|
|
self.unnamed.push(vec![span]);
|
|
|
|
} else {
|
|
|
|
self.unnamed.push(Vec::new());
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let args = &mut self.unnamed[n];
|
|
|
|
match (args.as_mut_slice(), arg.format == SIMPLE) {
|
|
|
|
// A non-empty format string has been seen already.
|
|
|
|
([], _) => (),
|
|
|
|
// Replace the dummy span, if it exists.
|
|
|
|
([dummy @ DUMMY_SP], true) => *dummy = span,
|
|
|
|
([_, ..], true) => args.push(span),
|
|
|
|
([_, ..], false) => *args = Vec::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2022-07-31 10:11:00 -05:00
|
|
|
ArgumentNamed(n) => {
|
2022-04-29 11:48:58 -05:00
|
|
|
let n = Symbol::intern(n);
|
2021-03-25 13:29:11 -05:00
|
|
|
if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
|
|
|
|
match x.1.as_slice() {
|
|
|
|
// A non-empty format string has been seen already.
|
|
|
|
[] => (),
|
|
|
|
[_, ..] if arg.format == SIMPLE => x.1.push(span),
|
|
|
|
[_, ..] => x.1 = Vec::new(),
|
|
|
|
}
|
|
|
|
} else if arg.format == SIMPLE {
|
|
|
|
self.named.push((n, vec![span]));
|
|
|
|
} else {
|
|
|
|
self.named.push((n, Vec::new()));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-14 09:28:08 -06:00
|
|
|
impl Write {
|
2021-03-25 13:29:11 -05:00
|
|
|
/// Parses a format string into a collection of spans for each argument. This only keeps track
|
|
|
|
/// of empty format arguments. Will also lint usages of debug format strings outside of debug
|
|
|
|
/// impls.
|
|
|
|
fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
|
|
|
|
use rustc_parse_format::{ParseMode, Parser, Piece};
|
|
|
|
|
|
|
|
let str_sym = str_lit.symbol_unescaped.as_str();
|
|
|
|
let style = match str_lit.style {
|
|
|
|
StrStyle::Cooked => None,
|
|
|
|
StrStyle::Raw(n) => Some(n as usize),
|
|
|
|
};
|
|
|
|
|
2021-12-14 21:39:23 -06:00
|
|
|
let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
|
2021-03-25 13:29:11 -05:00
|
|
|
let mut args = SimpleFormatArgs::default();
|
|
|
|
|
|
|
|
while let Some(arg) = parser.next() {
|
|
|
|
let arg = match arg {
|
|
|
|
Piece::String(_) => continue,
|
|
|
|
Piece::NextArgument(arg) => arg,
|
|
|
|
};
|
|
|
|
let span = parser
|
|
|
|
.arg_places
|
|
|
|
.last()
|
2022-04-29 11:48:58 -05:00
|
|
|
.map_or(DUMMY_SP, |&x| str_lit.span.from_inner(InnerSpan::new(x.start, x.end)));
|
2021-03-25 13:29:11 -05:00
|
|
|
|
|
|
|
if !self.in_debug_impl && arg.format.ty == "?" {
|
|
|
|
// FIXME: modify rustc's fmt string parser to give us the current span
|
|
|
|
span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
|
|
|
|
}
|
|
|
|
|
|
|
|
args.push(arg, span);
|
|
|
|
}
|
|
|
|
|
2022-07-18 02:39:37 -05:00
|
|
|
parser.errors.is_empty().then_some(args)
|
2021-03-25 13:29:11 -05:00
|
|
|
}
|
|
|
|
|
2020-01-14 09:28:08 -06:00
|
|
|
/// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
|
|
|
|
/// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
|
|
|
|
/// the contents of the string, whether it's a raw string, and the span of the literal in the
|
|
|
|
/// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
|
|
|
|
/// `format_str` should be written to.
|
|
|
|
///
|
|
|
|
/// Example:
|
|
|
|
///
|
|
|
|
/// Calling this function on
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::fmt::Write;
|
|
|
|
/// # let mut buf = String::new();
|
|
|
|
/// # let something = "something";
|
|
|
|
/// writeln!(buf, "string to write: {}", something);
|
|
|
|
/// ```
|
|
|
|
/// will return
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// (Some("string to write: {}"), Some(buf))
|
|
|
|
/// ```
|
2021-03-25 13:29:11 -05:00
|
|
|
fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
|
2021-12-04 09:09:15 -06:00
|
|
|
let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None);
|
2021-03-25 13:29:11 -05:00
|
|
|
let expr = if is_write {
|
|
|
|
match parser
|
|
|
|
.parse_expr()
|
|
|
|
.map(rustc_ast::ptr::P::into_inner)
|
2022-03-14 06:02:53 -05:00
|
|
|
.map_err(DiagnosticBuilder::cancel)
|
2021-03-25 13:29:11 -05:00
|
|
|
{
|
|
|
|
// write!(e, ...)
|
|
|
|
Ok(p) if parser.eat(&token::Comma) => Some(p),
|
|
|
|
// write!(e) or error
|
|
|
|
e => return (None, e.ok()),
|
2018-04-04 22:46:39 -05:00
|
|
|
}
|
2021-03-25 13:29:11 -05:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2020-01-14 09:28:08 -06:00
|
|
|
|
|
|
|
let fmtstr = match parser.parse_str_lit() {
|
|
|
|
Ok(fmtstr) => fmtstr,
|
|
|
|
Err(_) => return (None, expr),
|
2018-07-22 17:19:07 -05:00
|
|
|
};
|
2021-03-25 13:29:11 -05:00
|
|
|
|
|
|
|
let args = match self.parse_fmt_string(cx, &fmtstr) {
|
|
|
|
Some(args) => args,
|
|
|
|
None => return (Some(fmtstr), expr),
|
|
|
|
};
|
|
|
|
|
2020-01-14 09:28:08 -06:00
|
|
|
let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
|
2021-03-25 13:29:11 -05:00
|
|
|
let mut unnamed_args = args.get_unnamed();
|
2020-01-14 09:28:08 -06:00
|
|
|
loop {
|
|
|
|
if !parser.eat(&token::Comma) {
|
|
|
|
return (Some(fmtstr), expr);
|
|
|
|
}
|
2021-03-25 13:29:11 -05:00
|
|
|
|
|
|
|
let comma_span = parser.prev_token.span;
|
2022-03-14 06:02:53 -05:00
|
|
|
let token_expr = if let Ok(expr) = parser.parse_expr().map_err(DiagnosticBuilder::cancel) {
|
2020-01-14 09:28:08 -06:00
|
|
|
expr
|
|
|
|
} else {
|
|
|
|
return (Some(fmtstr), None);
|
|
|
|
};
|
2021-03-25 13:29:11 -05:00
|
|
|
let (fmt_spans, lit) = match &token_expr.kind {
|
|
|
|
ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
|
|
|
|
ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
|
|
|
|
(ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
|
|
|
|
_ => continue,
|
|
|
|
},
|
|
|
|
_ => {
|
|
|
|
unnamed_args.next();
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2022-08-01 01:46:08 -05:00
|
|
|
let replacement: String = match lit.token_lit.kind {
|
2021-03-25 13:29:11 -05:00
|
|
|
LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
|
2022-08-01 01:46:08 -05:00
|
|
|
lit.token_lit.symbol.as_str().replace('{', "{{").replace('}', "}}")
|
2021-03-25 13:29:11 -05:00
|
|
|
},
|
|
|
|
LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
|
2022-08-01 01:46:08 -05:00
|
|
|
lit.token_lit.symbol.as_str().replace('{', "{{").replace('}', "}}")
|
2021-03-25 13:29:11 -05:00
|
|
|
},
|
2022-03-24 08:50:04 -05:00
|
|
|
LitKind::StrRaw(_)
|
|
|
|
| LitKind::Str
|
|
|
|
| LitKind::ByteStrRaw(_)
|
|
|
|
| LitKind::ByteStr
|
|
|
|
| LitKind::Integer
|
|
|
|
| LitKind::Float
|
|
|
|
| LitKind::Err => continue,
|
2022-08-01 01:46:08 -05:00
|
|
|
LitKind::Byte | LitKind::Char => match lit.token_lit.symbol.as_str() {
|
2021-03-25 13:29:11 -05:00
|
|
|
"\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
|
|
|
|
"\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
|
|
|
|
"\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
|
|
|
|
"\\'" => "'",
|
|
|
|
"{" => "{{",
|
|
|
|
"}" => "}}",
|
|
|
|
x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
|
|
|
|
x => x,
|
2021-01-29 01:31:08 -06:00
|
|
|
}
|
2021-03-25 13:29:11 -05:00
|
|
|
.into(),
|
2022-08-01 01:46:08 -05:00
|
|
|
LitKind::Bool => lit.token_lit.symbol.as_str().deref().into(),
|
2021-03-25 13:29:11 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
if !fmt_spans.is_empty() {
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
lint,
|
|
|
|
token_expr.span,
|
|
|
|
"literal with an empty format string",
|
|
|
|
|diag| {
|
|
|
|
diag.multipart_suggestion(
|
|
|
|
"try this",
|
|
|
|
iter::once((comma_span.to(token_expr.span), String::new()))
|
2021-04-22 04:31:13 -05:00
|
|
|
.chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
|
2021-03-25 13:29:11 -05:00
|
|
|
.collect(),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
2020-01-14 09:28:08 -06:00
|
|
|
}
|
2018-04-21 13:24:55 -05:00
|
|
|
}
|
|
|
|
}
|
2020-12-20 10:19:49 -06:00
|
|
|
|
|
|
|
fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
|
|
|
|
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
|
2021-01-15 03:56:44 -06:00
|
|
|
if fmt_str.symbol == kw::Empty {
|
2020-12-20 10:19:49 -06:00
|
|
|
let name = mac.path.segments[0].ident.name;
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
PRINTLN_EMPTY_STRING,
|
|
|
|
mac.span(),
|
|
|
|
&format!("using `{}!(\"\")`", name),
|
|
|
|
"replace it with",
|
|
|
|
format!("{}!()", name),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
|
|
|
|
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
|
|
|
|
if check_newlines(&fmt_str) {
|
|
|
|
let name = mac.path.segments[0].ident.name;
|
|
|
|
let suggested = format!("{}ln", name);
|
|
|
|
span_lint_and_then(
|
|
|
|
cx,
|
|
|
|
PRINT_WITH_NEWLINE,
|
|
|
|
mac.span(),
|
2021-03-25 13:29:11 -05:00
|
|
|
&format!("using `{}!()` with a format string that ends in a single newline", name),
|
2020-12-20 10:19:49 -06:00
|
|
|
|err| {
|
|
|
|
err.multipart_suggestion(
|
|
|
|
&format!("use `{}!` instead", suggested),
|
2021-05-20 05:30:31 -05:00
|
|
|
vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
|
2020-12-20 10:19:49 -06:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-04-21 13:24:55 -05:00
|
|
|
}
|
2018-12-11 00:28:25 -06:00
|
|
|
|
2019-11-02 23:41:22 -05:00
|
|
|
/// Checks if the format string contains a single newline that terminates it.
|
2019-05-23 13:11:38 -05:00
|
|
|
///
|
|
|
|
/// Literal and escaped newlines are both checked (only literal for raw strings).
|
2019-11-18 09:38:36 -06:00
|
|
|
fn check_newlines(fmtstr: &StrLit) -> bool {
|
2019-11-02 23:41:22 -05:00
|
|
|
let mut has_internal_newline = false;
|
|
|
|
let mut last_was_cr = false;
|
|
|
|
let mut should_lint = false;
|
2019-05-23 13:11:38 -05:00
|
|
|
|
2021-12-14 21:39:23 -06:00
|
|
|
let contents = fmtstr.symbol.as_str();
|
2019-11-18 09:38:36 -06:00
|
|
|
|
2019-11-02 23:41:22 -05:00
|
|
|
let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
|
|
|
|
let c = c.unwrap();
|
2018-12-11 00:28:25 -06:00
|
|
|
|
2019-11-02 23:41:22 -05:00
|
|
|
if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
|
|
|
|
should_lint = true;
|
|
|
|
} else {
|
|
|
|
last_was_cr = c == '\r';
|
|
|
|
if c == '\n' {
|
|
|
|
has_internal_newline = true;
|
2018-12-11 00:28:25 -06:00
|
|
|
}
|
|
|
|
}
|
2019-11-02 23:41:22 -05:00
|
|
|
};
|
|
|
|
|
2019-11-18 09:38:36 -06:00
|
|
|
match fmtstr.style {
|
2020-05-13 03:03:49 -05:00
|
|
|
StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
|
|
|
|
StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),
|
2018-12-11 00:28:25 -06:00
|
|
|
}
|
|
|
|
|
2019-11-02 23:41:22 -05:00
|
|
|
should_lint
|
2018-12-11 00:28:25 -06:00
|
|
|
}
|