Skip to content

Rollup of 6 pull requests #81032

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

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
f2d7c05
Don't try to add nested predicate to Rustdoc auto-trait `ParamEnv`
Aaron1011 Dec 21, 2020
988e2f9
First version of noop-lint
rylev Jan 5, 2021
58e3a4a
Add tests and support two more noop methods
rylev Jan 5, 2021
e29cefd
Fix tests
rylev Jan 5, 2021
9777e0c
Bless test where order of error message changed
rylev Jan 6, 2021
f3bbb98
Fix ui-full-deps suite
rylev Jan 6, 2021
ac50400
Fix core tests
rylev Jan 6, 2021
8ac6481
Only allow new lint when not bootstrapping - since beta doesn't know …
rylev Jan 7, 2021
cdcb3b5
Fix std tests
rylev Jan 7, 2021
fd81c87
Improve warning
rylev Jan 8, 2021
a356556
Fix tidy errors
rylev Jan 8, 2021
8ded785
Update error message
rylev Jan 11, 2021
7cf66b8
Fix tidy error
rylev Jan 11, 2021
7b7708e
Improve error messages
rylev Jan 12, 2021
59577b8
Increase accuracy of lint trigger
estebank Jan 13, 2021
af88b73
Clean up code rightward drift
estebank Jan 13, 2021
5ea1d0e
Don't ICE when computing a layout of a generator tainted by errors
tmiasko Jan 14, 2021
a56bffb
Use Option::map_or instead of `.map(..).unwrap_or(..)`
LingMan Jan 11, 2021
744f885
Remove unreachable panics from VecDeque
bugadani Jan 9, 2021
7a0f0b5
Remove doctree::Import
CraftSpider Jan 14, 2021
0584ddc
Address nit
CraftSpider Jan 14, 2021
d07bb13
Fix JSON test
CraftSpider Jan 15, 2021
a70813e
Add warning to compare.py about error messages
CraftSpider Jan 15, 2021
e0ef0c2
Rollup merge of #80254 - Aaron1011:rustdoc-auto-param-env, r=estebank
JohnTitor Jan 15, 2021
fb6e491
Rollup merge of #80723 - rylev:noop-lint-pass, r=estebank
JohnTitor Jan 15, 2021
fdeb2f2
Rollup merge of #80834 - bugadani:vecdeque, r=oli-obk
JohnTitor Jan 15, 2021
9053e65
Rollup merge of #80944 - LingMan:map_or, r=nagisa
JohnTitor Jan 15, 2021
11a63fb
Rollup merge of #81008 - tmiasko:generator-layout-err, r=tmandry
JohnTitor Jan 15, 2021
e2e9e34
Rollup merge of #81021 - CraftSpider:rustdoc-remove-import, r=jyn514
JohnTitor Jan 15, 2021
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
2 changes: 1 addition & 1 deletion compiler/rustc_ast_lowering/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
if !generic_args.parenthesized && !has_lifetimes {
generic_args.args = self
.elided_path_lifetimes(
first_generic_span.map(|s| s.shrink_to_lo()).unwrap_or(segment.ident.span),
first_generic_span.map_or(segment.ident.span, |s| s.shrink_to_lo()),
expected_lifetimes,
)
.map(GenericArg::Lifetime)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_ast_passes/src/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
gate_feature_post!(
&self,
negative_impls,
span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)),
span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
"negative trait bounds are not yet fully implemented; \
use marker types for now"
);
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_llvm/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1002,8 +1002,7 @@ pub unsafe fn with_llvm_pmb(
// reasonable defaults and prepare it to actually populate the pass
// manager.
let builder = llvm::LLVMPassManagerBuilderCreate();
let opt_size =
config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
let inline_threshold = config.inline_threshold;
let pgo_gen_path = get_pgo_gen_path(config);
let pgo_use_path = get_pgo_use_path(config);
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1832,8 +1832,9 @@ impl<'tcx> VariantInfo<'_, 'tcx> {
fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
match self {
VariantInfo::Generator { def_id, variant_index, .. } => {
let span =
cx.tcx.generator_layout(*def_id).variant_source_info[*variant_index].span;
let span = cx.tcx.generator_layout(*def_id).unwrap().variant_source_info
[*variant_index]
.span;
if !span.is_dummy() {
let loc = cx.lookup_debug_loc(span.lo());
return Some(SourceInfo {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ fn get_linker(
_ => match flavor {
LinkerFlavor::Lld(f) => Command::lld(linker, f),
LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
}
_ => Command::new(linker),
},
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/back/rpath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn get_rpath_flags(config: &mut RPathConfig<'_>) -> Vec<String> {

debug!("preparing the RPATH!");

let libs = config.used_crates.clone();
let libs = config.used_crates;
let libs = libs.iter().filter_map(|&(_, ref l)| l.option()).collect::<Vec<_>>();
let rpaths = get_rpaths(config, &libs);
let mut flags = rpaths_to_flags(&rpaths);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_data_structures/src/profiling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ impl SelfProfilerRef {
// If there is no SelfProfiler then the filter mask is set to NONE,
// ensuring that nothing ever tries to actually access it.
let event_filter_mask =
profiler.as_ref().map(|p| p.event_filter_mask).unwrap_or(EventFilter::empty());
profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);

SelfProfilerRef {
profiler,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,7 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
}

// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");

let num_frames = if backtrace { None } else { Some(2) };

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,7 @@ impl HandlerInner {
}

fn treat_err_as_bug(&self) -> bool {
self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c)
}

fn print_error_count(&mut self, registry: &Registry) {
Expand Down Expand Up @@ -913,7 +913,7 @@ impl HandlerInner {
// This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
// incrementing `err_count` by one, so we need to +1 the comparing.
// FIXME: Would be nice to increment err_count in a more coherent way.
if self.flags.treat_err_as_bug.map(|c| self.err_count() + 1 >= c).unwrap_or(false) {
if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c) {
// FIXME: don't abort here if report_delayed_bugs is off
self.span_bug(sp, msg);
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ impl<'a> StripUnconfigured<'a> {

/// If attributes are not allowed on expressions, emit an error for `attr`
pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
if !self.features.map_or(true, |features| features.stmt_expr_attributes) {
let mut err = feature_err(
&self.sess.parse_sess,
sym::stmt_expr_attributes,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/mbe/macro_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ fn inner_parse_loop<'root, 'tt>(
if idx == len && item.sep.is_some() {
// We have a separator, and it is the current token. We can advance past the
// separator token.
if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) {
item.idx += 1;
next_items.push(item);
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/mbe/macro_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ fn macro_rules_dummy_expander<'cx>(
}

fn trace_macros_note(cx_expansions: &mut FxHashMap<Span, Vec<String>>, sp: Span, message: String) {
let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
cx_expansions.entry(sp).or_default().push(message);
}

Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_expand/src/mbe/quoted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ pub(super) fn parse(
}
_ => token.span,
},
tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span),
tree => tree.as_ref().map_or(span, tokenstream::TokenTree::span),
}
}
tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(start_sp),
tree => tree.as_ref().map_or(start_sp, tokenstream::TokenTree::span),
};
if node_id != DUMMY_NODE_ID {
// Macros loaded from other crates have dummy node ids.
Expand Down Expand Up @@ -250,7 +250,7 @@ fn parse_kleene_op(
Some(op) => Ok(Ok((op, token.span))),
None => Ok(Err(token)),
},
tree => Err(tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span)),
tree => Err(tree.as_ref().map_or(span, tokenstream::TokenTree::span)),
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ impl WhereClause<'_> {
/// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
pub fn tail_span_for_suggestion(&self) -> Span {
let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end)
self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2118,7 +2118,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let consider = format!(
"{} {}...",
msg,
if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
if type_param_span.map_or(false, |(_, _, is_impl_trait)| is_impl_trait) {
format!(" `{}` to `{}`", sub, bound_kind)
} else {
format!("`{}: {}`", bound_kind, sub)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1533,7 +1533,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// Note: if these two lines are combined into one we get
// dynamic borrow errors on `self.inner`.
let known = self.inner.borrow_mut().type_variables().probe(v).known();
known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
known.map_or(typ, |t| self.shallow_resolve_ty(t))
}

ty::Infer(ty::IntVar(v)) => self
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ mod levels;
mod methods;
mod non_ascii_idents;
mod nonstandard_style;
mod noop_method_call;
mod panic_fmt;
mod passes;
mod redundant_semicolon;
Expand All @@ -81,6 +82,7 @@ use internal::*;
use methods::*;
use non_ascii_idents::*;
use nonstandard_style::*;
use noop_method_call::*;
use panic_fmt::PanicFmt;
use redundant_semicolon::*;
use traits::*;
Expand Down Expand Up @@ -168,6 +170,7 @@ macro_rules! late_lint_passes {
ClashingExternDeclarations: ClashingExternDeclarations::new(),
DropTraitConstraints: DropTraitConstraints,
TemporaryCStringAsPtr: TemporaryCStringAsPtr,
NoopMethodCall: NoopMethodCall,
PanicFmt: PanicFmt,
]
);
Expand Down
125 changes: 125 additions & 0 deletions compiler/rustc_lint/src/noop_method_call.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use crate::context::LintContext;
use crate::rustc_middle::ty::TypeFoldable;
use crate::LateContext;
use crate::LateLintPass;
use rustc_hir::def::DefKind;
use rustc_hir::{Expr, ExprKind};
use rustc_middle::ty;
use rustc_span::symbol::sym;

declare_lint! {
/// The `noop_method_call` lint detects specific calls to noop methods
/// such as a calling `<&T as Clone>::clone` where `T: !Clone`.
///
/// ### Example
///
/// ```rust
/// # #![allow(unused)]
/// struct Foo;
/// let foo = &Foo;
/// let clone: &Foo = foo.clone();
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// Some method calls are noops meaning that they do nothing. Usually such methods
/// are the result of blanket implementations that happen to create some method invocations
/// that end up not doing anything. For instance, `Clone` is implemented on all `&T`, but
/// calling `clone` on a `&T` where `T` does not implement clone, actually doesn't do anything
/// as references are copy. This lint detects these calls and warns the user about them.
pub NOOP_METHOD_CALL,
Warn,
"detects the use of well-known noop methods"
}

declare_lint_pass!(NoopMethodCall => [NOOP_METHOD_CALL]);

impl<'tcx> LateLintPass<'tcx> for NoopMethodCall {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
// We only care about method calls.
let (call, elements) = match expr.kind {
ExprKind::MethodCall(call, _, elements, _) => (call, elements),
_ => return,
};
// We only care about method calls corresponding to the `Clone`, `Deref` and `Borrow`
// traits and ignore any other method call.
let (trait_id, did) = match cx.typeck_results().type_dependent_def(expr.hir_id) {
// Verify we are dealing with a method/associated function.
Some((DefKind::AssocFn, did)) => match cx.tcx.trait_of_item(did) {
// Check that we're dealing with a trait method for one of the traits we care about.
Some(trait_id)
if [sym::Clone, sym::Deref, sym::Borrow]
.iter()
.any(|s| cx.tcx.is_diagnostic_item(*s, trait_id)) =>
{
(trait_id, did)
}
_ => return,
},
_ => return,
};
let substs = cx.typeck_results().node_substs(expr.hir_id);
if substs.needs_subst() {
// We can't resolve on types that require monomorphization, so we don't handle them if
// we need to perfom substitution.
return;
}
let param_env = cx.tcx.param_env(trait_id);
// Resolve the trait method instance.
let i = match ty::Instance::resolve(cx.tcx, param_env, did, substs) {
Ok(Some(i)) => i,
_ => return,
};
// (Re)check that it implements the noop diagnostic.
for (s, peel_ref) in [
(sym::noop_method_borrow, true),
(sym::noop_method_clone, false),
(sym::noop_method_deref, true),
]
.iter()
{
if cx.tcx.is_diagnostic_item(*s, i.def_id()) {
let method = &call.ident.name;
let receiver = &elements[0];
let receiver_ty = cx.typeck_results().expr_ty(receiver);
let receiver_ty = match receiver_ty.kind() {
// Remove one borrow from the receiver if appropriate to positively verify that
// the receiver `&self` type and the return type are the same, depending on the
// involved trait being checked.
ty::Ref(_, ty, _) if *peel_ref => ty,
// When it comes to `Clone` we need to check the `receiver_ty` directly.
// FIXME: we must come up with a better strategy for this.
_ => receiver_ty,
};
let expr_ty = cx.typeck_results().expr_ty_adjusted(expr);
if receiver_ty != expr_ty {
// This lint will only trigger if the receiver type and resulting expression \
// type are the same, implying that the method call is unnecessary.
return;
}
let expr_span = expr.span;
let note = format!(
"the type `{:?}` which `{}` is being called on is the same as \
the type returned from `{}`, so the method call does not do \
anything and can be removed",
receiver_ty, method, method,
);

let span = expr_span.with_lo(receiver.span.hi());
cx.struct_span_lint(NOOP_METHOD_CALL, span, |lint| {
let method = &call.ident.name;
let message = format!(
"call to `.{}()` on a reference in this situation does nothing",
&method,
);
lint.build(&message)
.span_label(span, "unnecessary method call")
.note(&note)
.emit()
});
}
}
}
}
3 changes: 1 addition & 2 deletions compiler/rustc_lint/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,8 +647,7 @@ pub fn transparent_newtype_field<'a, 'tcx>(
let param_env = tcx.param_env(variant.def_id);
for field in &variant.fields {
let field_ty = tcx.type_of(field.did);
let is_zst =
tcx.layout_of(param_env.and(field_ty)).map(|layout| layout.is_zst()).unwrap_or(false);
let is_zst = tcx.layout_of(param_env.and(field_ty)).map_or(false, |layout| layout.is_zst());

if !is_zst {
return Some(field);
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,8 +529,8 @@ trait UnusedDelimLint {
pprust::expr_to_string(value)
};
let keep_space = (
left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
left_pos.map_or(false, |s| s >= value.span.lo()),
right_pos.map_or(false, |s| s <= value.span.hi()),
);
self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_macros/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ fn add_query_description_impl(
};

let (tcx, desc) = modifiers.desc;
let tcx = tcx.as_ref().map(|t| quote! { #t }).unwrap_or(quote! { _ });
let tcx = tcx.as_ref().map_or(quote! { _ }, |t| quote! { #t });

let desc = quote! {
#[allow(unused_variables)]
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ impl<'a> CrateLoader<'a> {
self.verify_no_symbol_conflicts(&crate_root)?;

let private_dep =
self.sess.opts.externs.get(&name.as_str()).map(|e| e.is_private_dep).unwrap_or(false);
self.sess.opts.externs.get(&name.as_str()).map_or(false, |e| e.is_private_dep);

// Claim this crate number and cache it
let cnum = self.cstore.alloc_new_crate_num();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/native_libs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> {

impl Collector<'tcx> {
fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLib) {
if lib.name.as_ref().map(|&s| s == kw::Empty).unwrap_or(false) {
if lib.name.as_ref().map_or(false, |&s| s == kw::Empty) {
match span {
Some(span) => {
struct_span_err!(
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_middle/src/hir/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,7 @@ impl<'hir> Map<'hir> {
/// Given a node ID, gets a list of attributes associated with the AST
/// corresponding to the node-ID.
pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
let attrs = self.find_entry(id).map(|entry| match entry.node {
self.find_entry(id).map_or(&[], |entry| match entry.node {
Node::Param(a) => &a.attrs[..],
Node::Local(l) => &l.attrs[..],
Node::Item(i) => &i.attrs[..],
Expand All @@ -842,8 +842,7 @@ impl<'hir> Map<'hir> {
| Node::Block(..)
| Node::Lifetime(..)
| Node::Visibility(..) => &[],
});
attrs.unwrap_or(&[])
})
}

/// Gets the span of the definition of the specified HIR node.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/consts/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl<'tcx> ConstKind<'tcx> {
/// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the
/// unevaluated constant.
pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Self {
self.try_eval(tcx, param_env).and_then(Result::ok).map(ConstKind::Value).unwrap_or(self)
self.try_eval(tcx, param_env).and_then(Result::ok).map_or(self, ConstKind::Value)
}

#[inline]
Expand Down
Loading