Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Check for MSRV attributes in late passes using the HIR #13821

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions book/src/development/adding_lints.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ pub struct ManualStrip {

impl ManualStrip {
pub fn new(conf: &'static Conf) -> Self {
Self { msrv: conf.msrv.clone() }
Self { msrv: conf.msrv }
}
}
```
Expand All @@ -468,24 +468,13 @@ The project's MSRV can then be matched against the feature MSRV in the LintPass
using the `Msrv::meets` method.

``` rust
if !self.msrv.meets(msrvs::STR_STRIP_PREFIX) {
if !self.msrv.meets(cx, msrvs::STR_STRIP_PREFIX) {
return;
}
```

The project's MSRV can also be specified as an attribute, which overrides
the value from `clippy.toml`. This can be accounted for using the
`extract_msrv_attr!(LintContext)` macro and passing
`LateContext`/`EarlyContext`.

```rust,ignore
impl<'tcx> LateLintPass<'tcx> for ManualStrip {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
...
}
extract_msrv_attr!(LateContext);
}
```
Early lint passes should instead use `MsrvStack` coupled with
`extract_msrv_attr!()`

Once the `msrv` is added to the lint, a relevant test case should be added to
the lint's test file, `tests/ui/manual_strip.rs` in this example. It should
Expand All @@ -511,8 +500,16 @@ in `clippy_config/src/conf.rs`:

```rust
define_Conf! {
/// Lint: LIST, OF, LINTS, <THE_NEWLY_ADDED_LINT>. The minimum rust version that the project supports
(msrv: Option<String> = None),
#[lints(
allow_attributes,
allow_attributes_without_reason,
..
<the newly added lint name>,
..
unused_trait_names,
use_self,
)]
msrv: Msrv = Msrv::default(),
...
}
```
Expand Down
2 changes: 1 addition & 1 deletion clippy_config/src/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ define_Conf! {
unused_trait_names,
use_self,
)]
msrv: Msrv = Msrv::empty(),
msrv: Msrv = Msrv::default(),
/// The minimum size (in bytes) to consider a type for passing by reference instead of by value.
#[lints(large_types_passed_by_value)]
pass_by_value_size_limit: u64 = 256,
Expand Down
6 changes: 3 additions & 3 deletions clippy_dev/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn main() {
category,
r#type,
msrv,
} => match new_lint::create(&pass, &name, &category, r#type.as_deref(), msrv) {
} => match new_lint::create(pass, &name, &category, r#type.as_deref(), msrv) {
Ok(()) => update_lints::update(utils::UpdateMode::Change),
Err(e) => eprintln!("Unable to create lint: {e}"),
},
Expand Down Expand Up @@ -138,9 +138,9 @@ enum DevCommand {
#[command(name = "new_lint")]
/// Create a new lint and run `cargo dev update_lints`
NewLint {
#[arg(short, long, value_parser = ["early", "late"], conflicts_with = "type", default_value = "late")]
#[arg(short, long, conflicts_with = "type", default_value = "late")]
/// Specify whether the lint runs during the early or late pass
pass: String,
pass: new_lint::Pass,
#[arg(
short,
long,
Expand Down
80 changes: 46 additions & 34 deletions clippy_dev/src/new_lint.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
use crate::utils::{clippy_project_root, clippy_version};
use clap::ValueEnum;
use indoc::{formatdoc, writedoc};
use std::fmt;
use std::fmt::Write as _;
use std::fmt::{self, Write as _};
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};

#[derive(Clone, Copy, PartialEq, ValueEnum)]
pub enum Pass {
Early,
Late,
}

impl fmt::Display for Pass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Pass::Early => "early",
Pass::Late => "late",
})
}
}

struct LintData<'a> {
pass: &'a str,
pass: Pass,
Comment on lines -11 to +26
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a nice cleanup 👍

name: &'a str,
category: &'a str,
ty: Option<&'a str>,
Expand Down Expand Up @@ -36,7 +51,7 @@ impl<T> Context for io::Result<T> {
/// # Errors
///
/// This function errors out if the files couldn't be created or written to.
pub fn create(pass: &str, name: &str, category: &str, mut ty: Option<&str>, msrv: bool) -> io::Result<()> {
pub fn create(pass: Pass, name: &str, category: &str, mut ty: Option<&str>, msrv: bool) -> io::Result<()> {
if category == "cargo" && ty.is_none() {
// `cargo` is a special category, these lints should always be in `clippy_lints/src/cargo`
ty = Some("cargo");
Expand All @@ -57,7 +72,7 @@ pub fn create(pass: &str, name: &str, category: &str, mut ty: Option<&str>, msrv
add_lint(&lint, msrv).context("Unable to add lint to clippy_lints/src/lib.rs")?;
}

if pass == "early" {
if pass == Pass::Early {
println!(
"\n\
NOTE: Use a late pass unless you need something specific from\n\
Expand Down Expand Up @@ -137,23 +152,17 @@ fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
let mut lib_rs = fs::read_to_string(path).context("reading")?;

let comment_start = lib_rs.find("// add lints here,").expect("Couldn't find comment");
let ctor_arg = if lint.pass == Pass::Late { "_" } else { "" };
let lint_pass = lint.pass;
let module_name = lint.name;
let camel_name = to_camel_case(lint.name);

let new_lint = if enable_msrv {
format!(
"store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(conf)));\n ",
lint_pass = lint.pass,
ctor_arg = if lint.pass == "late" { "_" } else { "" },
module_name = lint.name,
camel_name = to_camel_case(lint.name),
)
} else {
format!(
"store.register_{lint_pass}_pass(|{ctor_arg}| Box::new({module_name}::{camel_name}));\n ",
lint_pass = lint.pass,
ctor_arg = if lint.pass == "late" { "_" } else { "" },
module_name = lint.name,
camel_name = to_camel_case(lint.name),
)
format!("store.register_{lint_pass}_pass(|{ctor_arg}| Box::new({module_name}::{camel_name}));\n ",)
};

lib_rs.insert_str(comment_start, &new_lint);
Expand Down Expand Up @@ -243,11 +252,16 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
let mut result = String::new();

let (pass_type, pass_lifetimes, pass_import, context_import) = match lint.pass {
"early" => ("EarlyLintPass", "", "use rustc_ast::ast::*;", "EarlyContext"),
"late" => ("LateLintPass", "<'_>", "use rustc_hir::*;", "LateContext"),
_ => {
unreachable!("`pass_type` should only ever be `early` or `late`!");
},
Pass::Early => ("EarlyLintPass", "", "use rustc_ast::ast::*;", "EarlyContext"),
Pass::Late => ("LateLintPass", "<'_>", "use rustc_hir::*;", "LateContext"),
};
let (msrv_ty, msrv_ctor, extract_msrv) = match lint.pass {
Pass::Early => (
"MsrvStack",
"MsrvStack::new(conf.msrv)",
"\n extract_msrv_attr!();\n",
),
Pass::Late => ("Msrv", "conf.msrv", ""),
};

let lint_name = lint.name;
Expand All @@ -258,10 +272,10 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
result.push_str(&if enable_msrv {
formatdoc!(
r"
use clippy_utils::msrvs::{{self, Msrv}};
use clippy_utils::msrvs::{{self, {msrv_ty}}};
use clippy_config::Conf;
{pass_import}
use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
use rustc_lint::{{{context_import}, {pass_type}}};
use rustc_session::impl_lint_pass;

"
Expand All @@ -283,20 +297,18 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
formatdoc!(
r"
pub struct {name_camel} {{
msrv: Msrv,
msrv: {msrv_ty},
}}

impl {name_camel} {{
pub fn new(conf: &'static Conf) -> Self {{
Self {{ msrv: conf.msrv.clone() }}
Self {{ msrv: {msrv_ctor} }}
}}
}}

impl_lint_pass!({name_camel} => [{name_upper}]);

impl {pass_type}{pass_lifetimes} for {name_camel} {{
extract_msrv_attr!({context_import});
}}
impl {pass_type}{pass_lifetimes} for {name_camel} {{{extract_msrv}}}

// TODO: Add MSRV level to `clippy_config/src/msrvs.rs` if needed.
// TODO: Update msrv config comment in `clippy_config/src/conf.rs`
Expand Down Expand Up @@ -372,9 +384,9 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R

let mod_file_path = ty_dir.join("mod.rs");
let context_import = setup_mod_file(&mod_file_path, lint)?;
let pass_lifetimes = match context_import {
"LateContext" => "<'_>",
_ => "",
let (pass_lifetimes, msrv_ty, msrv_ref, msrv_cx) = match context_import {
"LateContext" => ("<'_>", "Msrv", "", "cx, "),
_ => ("", "MsrvStack", "&", ""),
};

let name_upper = lint.name.to_uppercase();
Expand All @@ -384,14 +396,14 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R
let _: fmt::Result = writedoc!(
lint_file_contents,
r#"
use clippy_utils::msrvs::{{self, Msrv}};
use clippy_utils::msrvs::{{self, {msrv_ty}}};
use rustc_lint::{{{context_import}, LintContext}};

use super::{name_upper};

// TODO: Adjust the parameters as necessary
pub(super) fn check(cx: &{context_import}{pass_lifetimes}, msrv: &Msrv) {{
if !msrv.meets(todo!("Add a new entry in `clippy_utils/src/msrvs`")) {{
pub(super) fn check(cx: &{context_import}{pass_lifetimes}, msrv: {msrv_ref}{msrv_ty}) {{
if !msrv.meets({msrv_cx}todo!("Add a new entry in `clippy_utils/src/msrvs`")) {{
return;
}}
todo!();
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/almost_complete_range.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::msrvs::{self, MsrvStack};
use clippy_utils::source::{trim_span, walk_span_to_context};
use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits};
use rustc_errors::Applicability;
Expand Down Expand Up @@ -32,12 +32,12 @@ declare_clippy_lint! {
impl_lint_pass!(AlmostCompleteRange => [ALMOST_COMPLETE_RANGE]);

pub struct AlmostCompleteRange {
msrv: Msrv,
msrv: MsrvStack,
}
impl AlmostCompleteRange {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
msrv: MsrvStack::new(conf.msrv),
}
}
}
Expand Down Expand Up @@ -97,7 +97,7 @@ impl EarlyLintPass for AlmostCompleteRange {
}
}

extract_msrv_attr!(EarlyContext);
extract_msrv_attr!();
}

fn is_incomplete_range(start: &Expr, end: &Expr) -> bool {
Expand Down
8 changes: 2 additions & 6 deletions clippy_lints/src/approx_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,7 @@ pub struct ApproxConstant {

impl ApproxConstant {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
Self { msrv: conf.msrv }
}

fn check_lit(&self, cx: &LateContext<'_>, lit: &LitKind, e: &Expr<'_>) {
Expand All @@ -91,7 +89,7 @@ impl ApproxConstant {
let s = s.as_str();
if s.parse::<f64>().is_ok() {
for &(constant, name, min_digits, msrv) in &KNOWN_CONSTS {
if is_approx_const(constant, s, min_digits) && msrv.is_none_or(|msrv| self.msrv.meets(msrv)) {
if is_approx_const(constant, s, min_digits) && msrv.is_none_or(|msrv| self.msrv.meets(cx, msrv)) {
span_lint_and_help(
cx,
APPROX_CONSTANT,
Expand All @@ -115,8 +113,6 @@ impl<'tcx> LateLintPass<'tcx> for ApproxConstant {
self.check_lit(cx, &lit.node, e);
}
}

extract_msrv_attr!(LateContext);
}

/// Returns `false` if the number of significant figures in `value` are
Expand Down
8 changes: 2 additions & 6 deletions clippy_lints/src/assigning_clones.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ pub struct AssigningClones {

impl AssigningClones {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
Self { msrv: conf.msrv }
}
}

Expand Down Expand Up @@ -90,7 +88,7 @@ impl<'tcx> LateLintPass<'tcx> for AssigningClones {
sym::clone if is_diag_trait_item(cx, fn_id, sym::Clone) => CloneTrait::Clone,
_ if fn_name.as_str() == "to_owned"
&& is_diag_trait_item(cx, fn_id, sym::ToOwned)
&& self.msrv.meets(msrvs::CLONE_INTO) =>
&& self.msrv.meets(cx, msrvs::CLONE_INTO) =>
{
CloneTrait::ToOwned
},
Expand Down Expand Up @@ -143,8 +141,6 @@ impl<'tcx> LateLintPass<'tcx> for AssigningClones {
);
}
}

extract_msrv_attr!(LateContext);
}

/// Checks if the data being cloned borrows from the place that is being assigned to:
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/attrs/deprecated_cfg_attr.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use super::{Attribute, DEPRECATED_CFG_ATTR, DEPRECATED_CLIPPY_CFG_ATTR, unnecessary_clippy_cfg};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::msrvs::{self, MsrvStack};
use rustc_ast::AttrStyle;
use rustc_errors::Applicability;
use rustc_lint::EarlyContext;
use rustc_span::sym;

pub(super) fn check(cx: &EarlyContext<'_>, attr: &Attribute, msrv: &Msrv) {
pub(super) fn check(cx: &EarlyContext<'_>, attr: &Attribute, msrv: &MsrvStack) {
// check cfg_attr
if attr.has_name(sym::cfg_attr)
&& let Some(items) = attr.meta_item_list()
Expand Down
Loading
Loading