Skip to content

Commit 798a5cf

Browse files
committed
Merge remote-tracking branch 'upstream/master' into rustup
2 parents 7072e45 + 949b834 commit 798a5cf

Some content is hidden

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

61 files changed

+225
-150
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1559,6 +1559,7 @@ Released 2018-09-13
15591559
[`deref_addrof`]: https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
15601560
[`derive_hash_xor_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_hash_xor_eq
15611561
[`derive_ord_xor_partial_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#derive_ord_xor_partial_ord
1562+
[`disallowed_method`]: https://rust-lang.github.io/rust-clippy/master/index.html#disallowed_method
15621563
[`diverging_sub_expression`]: https://rust-lang.github.io/rust-clippy/master/index.html#diverging_sub_expression
15631564
[`doc_markdown`]: https://rust-lang.github.io/rust-clippy/master/index.html#doc_markdown
15641565
[`double_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_comparisons

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
77

8-
[There are over 350 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
8+
[There are over 400 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
99

1010
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1111

clippy_lints/src/disallowed_method.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
use crate::utils::span_lint;
2+
3+
use rustc_data_structures::fx::FxHashSet;
4+
use rustc_hir::{Expr, ExprKind};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_session::{declare_tool_lint, impl_lint_pass};
7+
use rustc_span::Symbol;
8+
9+
declare_clippy_lint! {
10+
/// **What it does:** Lints for specific trait methods defined in clippy.toml
11+
///
12+
/// **Why is this bad?** Some methods are undesirable in certain contexts,
13+
/// and it would be beneficial to lint for them as needed.
14+
///
15+
/// **Known problems:** None.
16+
///
17+
/// **Example:**
18+
///
19+
/// ```rust,ignore
20+
/// // example code where clippy issues a warning
21+
/// foo.bad_method(); // Foo::bad_method is disallowed in the configuration
22+
/// ```
23+
/// Use instead:
24+
/// ```rust,ignore
25+
/// // example code which does not raise clippy warning
26+
/// goodStruct.bad_method(); // GoodStruct::bad_method is not disallowed
27+
/// ```
28+
pub DISALLOWED_METHOD,
29+
nursery,
30+
"use of a disallowed method call"
31+
}
32+
33+
#[derive(Clone, Debug)]
34+
pub struct DisallowedMethod {
35+
disallowed: FxHashSet<Vec<Symbol>>,
36+
}
37+
38+
impl DisallowedMethod {
39+
pub fn new(disallowed: &FxHashSet<String>) -> Self {
40+
Self {
41+
disallowed: disallowed
42+
.iter()
43+
.map(|s| s.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>())
44+
.collect(),
45+
}
46+
}
47+
}
48+
49+
impl_lint_pass!(DisallowedMethod => [DISALLOWED_METHOD]);
50+
51+
impl<'tcx> LateLintPass<'tcx> for DisallowedMethod {
52+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
53+
if let ExprKind::MethodCall(_path, _, _args, _) = &expr.kind {
54+
let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
55+
56+
let method_call = cx.get_def_path(def_id);
57+
if self.disallowed.contains(&method_call) {
58+
let method = method_call
59+
.iter()
60+
.map(|s| s.to_ident_string())
61+
.collect::<Vec<_>>()
62+
.join("::");
63+
64+
span_lint(
65+
cx,
66+
DISALLOWED_METHOD,
67+
expr.span,
68+
&format!("use of a disallowed method `{}`", method),
69+
);
70+
}
71+
}
72+
}
73+
}

clippy_lints/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ mod dbg_macro;
176176
mod default_trait_access;
177177
mod dereference;
178178
mod derive;
179+
mod disallowed_method;
179180
mod doc;
180181
mod double_comparison;
181182
mod double_parens;
@@ -526,6 +527,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
526527
&derive::DERIVE_ORD_XOR_PARTIAL_ORD,
527528
&derive::EXPL_IMPL_CLONE_ON_COPY,
528529
&derive::UNSAFE_DERIVE_DESERIALIZE,
530+
&disallowed_method::DISALLOWED_METHOD,
529531
&doc::DOC_MARKDOWN,
530532
&doc::MISSING_ERRORS_DOC,
531533
&doc::MISSING_SAFETY_DOC,
@@ -1119,6 +1121,9 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11191121
store.register_late_pass(|| box async_yields_async::AsyncYieldsAsync);
11201122
store.register_late_pass(|| box manual_strip::ManualStrip);
11211123
store.register_late_pass(|| box utils::internal_lints::MatchTypeOnDiagItem);
1124+
let disallowed_methods = conf.disallowed_methods.iter().cloned().collect::<FxHashSet<_>>();
1125+
store.register_late_pass(move || box disallowed_method::DisallowedMethod::new(&disallowed_methods));
1126+
11221127

11231128
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
11241129
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1808,6 +1813,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
18081813
store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![
18091814
LintId::of(&attrs::EMPTY_LINE_AFTER_OUTER_ATTR),
18101815
LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY),
1816+
LintId::of(&disallowed_method::DISALLOWED_METHOD),
18111817
LintId::of(&fallible_impl_from::FALLIBLE_IMPL_FROM),
18121818
LintId::of(&floating_point_arithmetic::IMPRECISE_FLOPS),
18131819
LintId::of(&floating_point_arithmetic::SUBOPTIMAL_FLOPS),

clippy_lints/src/loops.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2134,7 +2134,7 @@ enum VarState {
21342134
DontWarn,
21352135
}
21362136

2137-
/// Scan a for loop for variables that are incremented exactly once.
2137+
/// Scan a for loop for variables that are incremented exactly once and not used after that.
21382138
struct IncrementVisitor<'a, 'tcx> {
21392139
cx: &'a LateContext<'tcx>, // context reference
21402140
states: FxHashMap<HirId, VarState>, // incremented variables
@@ -2154,6 +2154,10 @@ impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
21542154
if let Some(def_id) = var_def_id(self.cx, expr) {
21552155
if let Some(parent) = get_parent_expr(self.cx, expr) {
21562156
let state = self.states.entry(def_id).or_insert(VarState::Initial);
2157+
if *state == VarState::IncrOnce {
2158+
*state = VarState::DontWarn;
2159+
return;
2160+
}
21572161

21582162
match parent.kind {
21592163
ExprKind::AssignOp(op, ref lhs, ref rhs) => {

clippy_lints/src/types.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -216,18 +216,19 @@ declare_clippy_lint! {
216216
}
217217

218218
declare_clippy_lint! {
219-
/// **What it does:** Checks for Rc<T> and Arc<T> when T is a mutable buffer type such as String or Vec
219+
/// **What it does:** Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`.
220220
///
221-
/// **Why is this bad?** Expressions such as Rc<String> have no advantage over Rc<str>, since
222-
/// it is larger and involves an extra level of indirection, and doesn't implement Borrow<str>.
221+
/// **Why is this bad?** Expressions such as `Rc<String>` usually have no advantage over `Rc<str>`, since
222+
/// it is larger and involves an extra level of indirection, and doesn't implement `Borrow<str>`.
223223
///
224-
/// While mutating a buffer type would still be possible with Rc::get_mut(), it only
225-
/// works if there are no additional references yet, which defeats the purpose of
224+
/// While mutating a buffer type would still be possible with `Rc::get_mut()`, it only
225+
/// works if there are no additional references yet, which usually defeats the purpose of
226226
/// enclosing it in a shared ownership type. Instead, additionally wrapping the inner
227-
/// type with an interior mutable container (such as RefCell or Mutex) would normally
227+
/// type with an interior mutable container (such as `RefCell` or `Mutex`) would normally
228228
/// be used.
229229
///
230-
/// **Known problems:** None.
230+
/// **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for
231+
/// cases where mutation only happens before there are any additional references.
231232
///
232233
/// **Example:**
233234
/// ```rust,ignore

clippy_lints/src/utils/conf.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,8 @@ define_Conf! {
164164
(max_fn_params_bools, "max_fn_params_bools": u64, 3),
165165
/// Lint: WILDCARD_IMPORTS. Whether to allow certain wildcard imports (prelude, super in tests).
166166
(warn_on_all_wildcard_imports, "warn_on_all_wildcard_imports": bool, false),
167+
/// Lint: DISALLOWED_METHOD. The list of blacklisted methods to lint about. NB: `bar` is not here since it has legitimate uses
168+
(disallowed_methods, "disallowed_methods": Vec<String>, Vec::<String>::new()),
167169
}
168170

169171
impl Default for Conf {

clippy_lints/src/utils/mod.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ use rustc_lint::{LateContext, Level, Lint, LintContext};
4747
use rustc_middle::hir::map::Map;
4848
use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
4949
use rustc_middle::ty::{self, layout::IntegerExt, Ty, TyCtxt, TypeFoldable};
50-
use rustc_mir::const_eval;
5150
use rustc_span::hygiene::{ExpnKind, MacroKind};
5251
use rustc_span::source_map::original_sp;
5352
use rustc_span::symbol::{self, kw, Symbol};
@@ -884,19 +883,11 @@ pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
884883

885884
/// Checks if an expression is constructing a tuple-like enum variant or struct
886885
pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
887-
fn has_no_arguments(cx: &LateContext<'_>, def_id: DefId) -> bool {
888-
cx.tcx.fn_sig(def_id).skip_binder().inputs().is_empty()
889-
}
890-
891886
if let ExprKind::Call(ref fun, _) = expr.kind {
892887
if let ExprKind::Path(ref qp) = fun.kind {
893888
let res = cx.qpath_res(qp, fun.hir_id);
894889
return match res {
895890
def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
896-
// FIXME: check the constness of the arguments, see https://github.com/rust-lang/rust-clippy/pull/5682#issuecomment-638681210
897-
def::Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) if has_no_arguments(cx, def_id) => {
898-
const_eval::is_const_fn(cx.tcx, def_id)
899-
},
900891
def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
901892
_ => false,
902893
};

clippy_lints/src/write.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,19 @@ impl EarlyLintPass for Write {
235235
}
236236

237237
fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
238+
fn is_build_script(cx: &EarlyContext<'_>) -> bool {
239+
// Cargo sets the crate name for build scripts to `build_script_build`
240+
cx.sess
241+
.opts
242+
.crate_name
243+
.as_ref()
244+
.map_or(false, |crate_name| crate_name == "build_script_build")
245+
}
246+
238247
if mac.path == sym!(println) {
239-
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
248+
if !is_build_script(cx) {
249+
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
250+
}
240251
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
241252
if fmt_str.symbol == Symbol::intern("") {
242253
span_lint_and_sugg(
@@ -251,7 +262,9 @@ impl EarlyLintPass for Write {
251262
}
252263
}
253264
} else if mac.path == sym!(print) {
254-
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
265+
if !is_build_script(cx) {
266+
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
267+
}
255268
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
256269
if check_newlines(&fmt_str) {
257270
span_lint_and_then(

clippy_workspace_tests/build.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#![deny(clippy::print_stdout)]
2+
3+
fn main() {
4+
// Test for #6041
5+
println!("Hello");
6+
print!("Hello");
7+
}

0 commit comments

Comments
 (0)