Skip to content

Commit 249b6fe

Browse files
committed
Auto merge of rust-lang#6415 - flip1995:rollup-fz7872l, r=flip1995
Rollup of 4 pull requests Successful merges: - rust-lang#6308 (add `internal-lints` feature to enable clippys internal lints (off by default)) - rust-lang#6395 (switch Version/VersionReq usages to RustcVersion ) - rust-lang#6402 (Add Collapsible match lint) - rust-lang#6407 (CONTRIBUTING: update bors queue url from buildbot2.rlo to bors.rlo) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup changelog: rollup
2 parents 4785da6 + c9da866 commit 249b6fe

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+1041
-238
lines changed

.github/workflows/clippy_bors.yml

+6-6
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,14 @@ jobs:
128128
SYSROOT=$(rustc --print sysroot)
129129
echo "$SYSROOT/bin" >> $GITHUB_PATH
130130
131-
- name: Build
132-
run: cargo build --features deny-warnings
131+
- name: Build with internal lints
132+
run: cargo build --features deny-warnings,internal-lints
133133

134-
- name: Test
135-
run: cargo test --features deny-warnings
134+
- name: Test with internal lints
135+
run: cargo test --features deny-warnings,internal-lints
136136

137-
- name: Test clippy_lints
138-
run: cargo test --features deny-warnings
137+
- name: Test clippy_lints with internal lints
138+
run: cargo test --features deny-warnings,internal-lints
139139
working-directory: clippy_lints
140140

141141
- name: Test rustc_tools_util

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1770,6 +1770,7 @@ Released 2018-09-13
17701770
[`cmp_owned`]: https://rust-lang.github.io/rust-clippy/master/index.html#cmp_owned
17711771
[`cognitive_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity
17721772
[`collapsible_if`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if
1773+
[`collapsible_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_match
17731774
[`comparison_chain`]: https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain
17741775
[`comparison_to_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#comparison_to_empty
17751776
[`copy_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_iterator

CONTRIBUTING.md

+7-2
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,16 @@ All contributors are expected to follow the [Rust Code of Conduct].
1414

1515
- [Contributing to Clippy](#contributing-to-clippy)
1616
- [Getting started](#getting-started)
17+
- [High level approach](#high-level-approach)
1718
- [Finding something to fix/improve](#finding-something-to-fiximprove)
1819
- [Writing code](#writing-code)
1920
- [Getting code-completion for rustc internals to work](#getting-code-completion-for-rustc-internals-to-work)
2021
- [How Clippy works](#how-clippy-works)
2122
- [Fixing build failures caused by Rust](#fixing-build-failures-caused-by-rust)
23+
- [Patching git-subtree to work with big repos](#patching-git-subtree-to-work-with-big-repos)
24+
- [Performing the sync](#performing-the-sync)
25+
- [Syncing back changes in Clippy to [`rust-lang/rust`]](#syncing-back-changes-in-clippy-to-rust-langrust)
26+
- [Defining remotes](#defining-remotes)
2227
- [Issue and PR triage](#issue-and-pr-triage)
2328
- [Bors and Homu](#bors-and-homu)
2429
- [Contributions](#contributions)
@@ -320,8 +325,8 @@ commands [here][homu_instructions].
320325
[l-crash]: https://github.com/rust-lang/rust-clippy/labels/L-crash
321326
[l-bug]: https://github.com/rust-lang/rust-clippy/labels/L-bug
322327
[homu]: https://github.com/rust-lang/homu
323-
[homu_instructions]: https://buildbot2.rust-lang.org/homu/
324-
[homu_queue]: https://buildbot2.rust-lang.org/homu/queue/clippy
328+
[homu_instructions]: https://bors.rust-lang.org/
329+
[homu_queue]: https://bors.rust-lang.org/queue/clippy
325330
326331
## Contributions
327332

Cargo.toml

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ path = "src/driver.rs"
3232
clippy_lints = { version = "0.0.212", path = "clippy_lints" }
3333
# end automatic update
3434
semver = "0.11"
35-
rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util"}
35+
rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util" }
3636
tempfile = { version = "3.1.0", optional = true }
3737

3838
[dev-dependencies]
@@ -49,8 +49,9 @@ derive-new = "0.5"
4949
rustc-workspace-hack = "1.0.0"
5050

5151
[build-dependencies]
52-
rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util"}
52+
rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util" }
5353

5454
[features]
5555
deny-warnings = []
5656
integration = ["tempfile"]
57+
internal-lints = ["clippy_lints/internal-lints"]

clippy_dev/src/lib.rs

+23-9
Original file line numberDiff line numberDiff line change
@@ -146,16 +146,30 @@ pub fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String>
146146
}
147147

148148
#[must_use]
149-
pub fn gen_register_lint_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
150-
let pre = " store.register_lints(&[".to_string();
151-
let post = " ]);".to_string();
152-
let mut inner = lints
149+
pub fn gen_register_lint_list<'a>(
150+
internal_lints: impl Iterator<Item = &'a Lint>,
151+
usable_lints: impl Iterator<Item = &'a Lint>,
152+
) -> Vec<String> {
153+
let header = " store.register_lints(&[".to_string();
154+
let footer = " ]);".to_string();
155+
let internal_lints = internal_lints
156+
.sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
157+
.map(|l| {
158+
format!(
159+
" #[cfg(feature = \"internal-lints\")]\n &{}::{},",
160+
l.module,
161+
l.name.to_uppercase()
162+
)
163+
});
164+
let other_lints = usable_lints
165+
.sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
153166
.map(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
154-
.sorted()
155-
.collect::<Vec<String>>();
156-
inner.insert(0, pre);
157-
inner.push(post);
158-
inner
167+
.sorted();
168+
let mut lint_list = vec![header];
169+
lint_list.extend(internal_lints);
170+
lint_list.extend(other_lints);
171+
lint_list.push(footer);
172+
lint_list
159173
}
160174

161175
/// Gathers all files in `src/clippy_lints` and gathers all lints inside

clippy_dev/src/update_lints.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub fn run(update_mode: UpdateMode) {
6868
"end register lints",
6969
false,
7070
update_mode == UpdateMode::Change,
71-
|| gen_register_lint_list(usable_lints.iter().chain(internal_lints.iter())),
71+
|| gen_register_lint_list(internal_lints.iter(), usable_lints.iter()),
7272
)
7373
.changed;
7474

clippy_lints/Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ smallvec = { version = "1", features = ["union"] }
2828
toml = "0.5.3"
2929
unicode-normalization = "0.1"
3030
semver = "0.11"
31+
rustc-semver="1.1.0"
3132
# NOTE: cargo requires serde feat in its url dep
3233
# see <https://github.com/rust-lang/rust/pull/63587#issuecomment-522343864>
3334
url = { version = "2.1.0", features = ["serde"] }
@@ -36,3 +37,5 @@ syn = { version = "1", features = ["full"] }
3637

3738
[features]
3839
deny-warnings = []
40+
# build clippy with internal lints enabled, off by default
41+
internal-lints = []

clippy_lints/src/collapsible_match.rs

+172
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
use crate::utils::visitors::LocalUsedVisitor;
2+
use crate::utils::{span_lint_and_then, SpanlessEq};
3+
use if_chain::if_chain;
4+
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
5+
use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind, QPath, StmtKind};
6+
use rustc_lint::{LateContext, LateLintPass};
7+
use rustc_middle::ty::{DefIdTree, TyCtxt};
8+
use rustc_session::{declare_lint_pass, declare_tool_lint};
9+
use rustc_span::{MultiSpan, Span};
10+
11+
declare_clippy_lint! {
12+
/// **What it does:** Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together
13+
/// without adding any branches.
14+
///
15+
/// Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only
16+
/// cases where merging would most likely make the code more readable.
17+
///
18+
/// **Why is this bad?** It is unnecessarily verbose and complex.
19+
///
20+
/// **Known problems:** None.
21+
///
22+
/// **Example:**
23+
///
24+
/// ```rust
25+
/// fn func(opt: Option<Result<u64, String>>) {
26+
/// let n = match opt {
27+
/// Some(n) => match n {
28+
/// Ok(n) => n,
29+
/// _ => return,
30+
/// }
31+
/// None => return,
32+
/// };
33+
/// }
34+
/// ```
35+
/// Use instead:
36+
/// ```rust
37+
/// fn func(opt: Option<Result<u64, String>>) {
38+
/// let n = match opt {
39+
/// Some(Ok(n)) => n,
40+
/// _ => return,
41+
/// };
42+
/// }
43+
/// ```
44+
pub COLLAPSIBLE_MATCH,
45+
style,
46+
"Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
47+
}
48+
49+
declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]);
50+
51+
impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch {
52+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
53+
if let ExprKind::Match(_expr, arms, _source) = expr.kind {
54+
if let Some(wild_arm) = arms.iter().rfind(|arm| arm_is_wild_like(arm, cx.tcx)) {
55+
for arm in arms {
56+
check_arm(arm, wild_arm, cx);
57+
}
58+
}
59+
}
60+
}
61+
}
62+
63+
fn check_arm(arm: &Arm<'_>, wild_outer_arm: &Arm<'_>, cx: &LateContext<'_>) {
64+
if_chain! {
65+
let expr = strip_singleton_blocks(arm.body);
66+
if let ExprKind::Match(expr_in, arms_inner, _) = expr.kind;
67+
// the outer arm pattern and the inner match
68+
if expr_in.span.ctxt() == arm.pat.span.ctxt();
69+
// there must be no more than two arms in the inner match for this lint
70+
if arms_inner.len() == 2;
71+
// no if guards on the inner match
72+
if arms_inner.iter().all(|arm| arm.guard.is_none());
73+
// match expression must be a local binding
74+
// match <local> { .. }
75+
if let ExprKind::Path(QPath::Resolved(None, path)) = expr_in.kind;
76+
if let Res::Local(binding_id) = path.res;
77+
// one of the branches must be "wild-like"
78+
if let Some(wild_inner_arm_idx) = arms_inner.iter().rposition(|arm_inner| arm_is_wild_like(arm_inner, cx.tcx));
79+
let (wild_inner_arm, non_wild_inner_arm) =
80+
(&arms_inner[wild_inner_arm_idx], &arms_inner[1 - wild_inner_arm_idx]);
81+
if !pat_contains_or(non_wild_inner_arm.pat);
82+
// the binding must come from the pattern of the containing match arm
83+
// ..<local>.. => match <local> { .. }
84+
if let Some(binding_span) = find_pat_binding(arm.pat, binding_id);
85+
// the "wild-like" branches must be equal
86+
if SpanlessEq::new(cx).eq_expr(wild_inner_arm.body, wild_outer_arm.body);
87+
// the binding must not be used in the if guard
88+
if !matches!(arm.guard, Some(Guard::If(guard)) if LocalUsedVisitor::new(binding_id).check_expr(guard));
89+
// ...or anywhere in the inner match
90+
if !arms_inner.iter().any(|arm| LocalUsedVisitor::new(binding_id).check_arm(arm));
91+
then {
92+
span_lint_and_then(
93+
cx,
94+
COLLAPSIBLE_MATCH,
95+
expr.span,
96+
"Unnecessary nested match",
97+
|diag| {
98+
let mut help_span = MultiSpan::from_spans(vec![binding_span, non_wild_inner_arm.pat.span]);
99+
help_span.push_span_label(binding_span, "Replace this binding".into());
100+
help_span.push_span_label(non_wild_inner_arm.pat.span, "with this pattern".into());
101+
diag.span_help(help_span, "The outer pattern can be modified to include the inner pattern.");
102+
},
103+
);
104+
}
105+
}
106+
}
107+
108+
fn strip_singleton_blocks<'hir>(mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
109+
while let ExprKind::Block(block, _) = expr.kind {
110+
match (block.stmts, block.expr) {
111+
([stmt], None) => match stmt.kind {
112+
StmtKind::Expr(e) | StmtKind::Semi(e) => expr = e,
113+
_ => break,
114+
},
115+
([], Some(e)) => expr = e,
116+
_ => break,
117+
}
118+
}
119+
expr
120+
}
121+
122+
/// A "wild-like" pattern is wild ("_") or `None`.
123+
/// For this lint to apply, both the outer and inner match expressions
124+
/// must have "wild-like" branches that can be combined.
125+
fn arm_is_wild_like(arm: &Arm<'_>, tcx: TyCtxt<'_>) -> bool {
126+
if arm.guard.is_some() {
127+
return false;
128+
}
129+
match arm.pat.kind {
130+
PatKind::Binding(..) | PatKind::Wild => true,
131+
PatKind::Path(QPath::Resolved(None, path)) if is_none_ctor(path.res, tcx) => true,
132+
_ => false,
133+
}
134+
}
135+
136+
fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option<Span> {
137+
let mut span = None;
138+
pat.walk_short(|p| match &p.kind {
139+
// ignore OR patterns
140+
PatKind::Or(_) => false,
141+
PatKind::Binding(_bm, _, _ident, _) => {
142+
let found = p.hir_id == hir_id;
143+
if found {
144+
span = Some(p.span);
145+
}
146+
!found
147+
},
148+
_ => true,
149+
});
150+
span
151+
}
152+
153+
fn pat_contains_or(pat: &Pat<'_>) -> bool {
154+
let mut result = false;
155+
pat.walk(|p| {
156+
let is_or = matches!(p.kind, PatKind::Or(_));
157+
result |= is_or;
158+
!is_or
159+
});
160+
result
161+
}
162+
163+
fn is_none_ctor(res: Res, tcx: TyCtxt<'_>) -> bool {
164+
if let Some(none_id) = tcx.lang_items().option_none_variant() {
165+
if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), id) = res {
166+
if let Some(variant_id) = tcx.parent(id) {
167+
return variant_id == none_id;
168+
}
169+
}
170+
}
171+
false
172+
}

clippy_lints/src/default.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,7 @@ fn field_reassigned_by_stmt<'tcx>(this: &Stmt<'tcx>, binding_name: Symbol) -> Op
280280
// only take assignments to fields where the left-hand side field is a field of
281281
// the same binding as the previous statement
282282
if let ExprKind::Field(ref binding, field_ident) = assign_lhs.kind;
283-
if let ExprKind::Path(ref qpath) = binding.kind;
284-
if let QPath::Resolved(_, path) = qpath;
283+
if let ExprKind::Path(QPath::Resolved(_, path)) = binding.kind;
285284
if let Some(second_binding_name) = path.segments.last();
286285
if second_binding_name.ident.name == binding_name;
287286
then {

clippy_lints/src/if_let_some_result.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ declare_lint_pass!(OkIfLet => [IF_LET_SOME_RESULT]);
4141
impl<'tcx> LateLintPass<'tcx> for OkIfLet {
4242
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
4343
if_chain! { //begin checking variables
44-
if let ExprKind::Match(ref op, ref body, source) = expr.kind; //test if expr is a match
45-
if let MatchSource::IfLetDesugar { .. } = source; //test if it is an If Let
44+
if let ExprKind::Match(ref op, ref body, MatchSource::IfLetDesugar { .. }) = expr.kind; //test if expr is if let
4645
if let ExprKind::MethodCall(_, ok_span, ref result_types, _) = op.kind; //check is expr.ok() has type Result<T,E>.ok(, _)
4746
if let PatKind::TupleStruct(QPath::Resolved(_, ref x), ref y, _) = body[0].pat.kind; //get operation
4847
if method_chain_args(op, &["ok"]).is_some(); //test to see if using ok() methoduse std::marker::Sized;

clippy_lints/src/implicit_return.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) {
6868
if_chain! {
6969
if let StmtKind::Semi(expr, ..) = &stmt.kind;
7070
// make sure it's a break, otherwise we want to skip
71-
if let ExprKind::Break(.., break_expr) = &expr.kind;
72-
if let Some(break_expr) = break_expr;
71+
if let ExprKind::Break(.., Some(break_expr)) = &expr.kind;
7372
then {
7473
lint(cx, expr.span, break_expr.span, LINT_BREAK);
7574
}

clippy_lints/src/implicit_saturating_sub.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
5959
if let Some(target) = subtracts_one(cx, e);
6060

6161
// Extracting out the variable name
62-
if let ExprKind::Path(ref assign_path) = target.kind;
63-
if let QPath::Resolved(_, ref ares_path) = assign_path;
62+
if let ExprKind::Path(QPath::Resolved(_, ref ares_path)) = target.kind;
6463

6564
then {
6665
// Handle symmetric conditions in the if statement

clippy_lints/src/large_const_arrays.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeConstArrays {
5252
if let ItemKind::Const(hir_ty, _) = &item.kind;
5353
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
5454
if let ty::Array(element_type, cst) = ty.kind();
55-
if let ConstKind::Value(val) = cst.val;
56-
if let ConstValue::Scalar(element_count) = val;
55+
if let ConstKind::Value(ConstValue::Scalar(element_count)) = cst.val;
5756
if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
5857
if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
5958
if self.maximum_allowed_size < element_count * element_size;

clippy_lints/src/large_stack_arrays.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeStackArrays {
4343
if_chain! {
4444
if let ExprKind::Repeat(_, _) = expr.kind;
4545
if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind();
46-
if let ConstKind::Value(val) = cst.val;
47-
if let ConstValue::Scalar(element_count) = val;
46+
if let ConstKind::Value(ConstValue::Scalar(element_count)) = cst.val;
4847
if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx);
4948
if let Ok(element_size) = cx.layout_of(element_type).map(|l| l.size.bytes());
5049
if self.maximum_allowed_size < element_count * element_size;

0 commit comments

Comments
 (0)