more clippy fixes

This commit is contained in:
Matthias Krüger 2021-11-07 10:33:27 +01:00
parent 88b4ea8fb6
commit 5c454551da
27 changed files with 140 additions and 184 deletions

View File

@ -541,15 +541,13 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
ast::ExprKind::TryBlock(_) => {
gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
}
ast::ExprKind::Block(_, opt_label) => {
if let Some(label) = opt_label {
gate_feature_post!(
&self,
label_break_value,
label.ident.span,
"labels on blocks are unstable"
);
}
ast::ExprKind::Block(_, Some(label)) => {
gate_feature_post!(
&self,
label_break_value,
label.ident.span,
"labels on blocks are unstable"
);
}
_ => {}
}

View File

@ -1405,11 +1405,7 @@ impl<'a> State<'a> {
}
}
crate fn print_record_struct_body(
&mut self,
fields: &Vec<ast::FieldDef>,
span: rustc_span::Span,
) {
crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
self.nbsp();
self.bopen();
self.hardbreak_if_not_bol();

View File

@ -655,7 +655,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
// If the region is live at at least one location in the promoted MIR,
// then add a liveness constraint to the main MIR for this region
// at the location provided as an argument to this method
if let Some(_) = liveness_constraints.get_elements(region).next() {
if liveness_constraints.get_elements(region).next().is_some() {
self.cx
.borrowck_context
.constraints

View File

@ -547,7 +547,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
if let Some(snippet) = &template_snippet {
if let Some(pos) = snippet.find(needle) {
let end = pos
+ &snippet[pos..]
+ snippet[pos..]
.find(|c| matches!(c, '\n' | ';' | '\\' | '"'))
.unwrap_or(snippet[pos..].len() - 1);
let inner = InnerSpan::new(pos, end);

View File

@ -1095,10 +1095,10 @@ fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut d
}
fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
fn find_sanitizer_runtime(sess: &Session, filename: &String) -> PathBuf {
fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
let session_tlib =
filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
let path = session_tlib.join(&filename);
let path = session_tlib.join(filename);
if path.exists() {
return session_tlib;
} else {

View File

@ -34,7 +34,7 @@ impl<T> Steal<T> {
#[track_caller]
pub fn borrow(&self) -> MappedReadGuard<'_, T> {
let borrow = self.value.borrow();
if let None = &*borrow {
if borrow.is_none() {
panic!("attempted to read from stolen value: {}", std::any::type_name::<T>());
}
ReadGuard::map(borrow, |opt| opt.as_ref().unwrap())

View File

@ -1466,7 +1466,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let mut returned_async_output_error = false;
for &sp in values {
if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
if &[sp] != err.span.primary_spans() {
if [sp] != err.span.primary_spans() {
let mut span: MultiSpan = sp.into();
span.push_span_label(
sp,

View File

@ -47,7 +47,7 @@ use std::ffi::OsString;
use std::io::{self, BufWriter, Write};
use std::lazy::SyncLazy;
use std::marker::PhantomPinned;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::{env, fs, iter};
@ -536,7 +536,7 @@ where
None
}
fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
let input_path = input_path.canonicalize().ok();
if input_path.is_none() {
return false;
@ -552,7 +552,7 @@ fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
check_output(output_paths, check)
}
fn escape_dep_filename(filename: &String) -> String {
fn escape_dep_filename(filename: &str) -> String {
// Apparently clang and gcc *only* escape spaces:
// https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
filename.replace(" ", "\\ ")

View File

@ -3130,18 +3130,13 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
false
}
if let rustc_hir::ExprKind::Unary(ref un_op, ref expr_deref) = expr.kind {
if let rustc_hir::UnOp::Deref = un_op {
if is_null_ptr(cx, expr_deref) {
cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| {
let mut err = lint.build("dereferencing a null pointer");
err.span_label(
expr.span,
"this code causes undefined behavior when executed",
);
err.emit();
});
}
if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind {
if is_null_ptr(cx, expr_deref) {
cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| {
let mut err = lint.build("dereferencing a null pointer");
err.span_label(expr.span, "this code causes undefined behavior when executed");
err.emit();
});
}
}
}
@ -3196,7 +3191,7 @@ impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels {
let snippet = template_snippet.as_str();
if let Some(pos) = snippet.find(needle) {
let end = pos
+ &snippet[pos..]
+ snippet[pos..]
.find(|c| c == ':')
.unwrap_or(snippet[pos..].len() - 1);
let inner = InnerSpan::new(pos, end);

View File

@ -101,33 +101,31 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind {
fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
match &ty.kind {
TyKind::Path(qpath) => {
if let QPath::Resolved(_, path) = qpath {
if let Some(last) = path.segments.iter().last() {
if lint_ty_kind_usage(cx, last) {
cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
lint.build("usage of `ty::TyKind`")
.help("try using `Ty` instead")
.emit();
})
} else {
if ty.span.from_expansion() {
return;
}
if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
if path.segments.len() > 1 {
cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
lint.build(&format!("usage of qualified `ty::{}`", t))
.span_suggestion(
path.span,
"try using it unqualified",
t,
// The import probably needs to be changed
Applicability::MaybeIncorrect,
)
.emit();
})
}
TyKind::Path(QPath::Resolved(_, path)) => {
if let Some(last) = path.segments.iter().last() {
if lint_ty_kind_usage(cx, last) {
cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
lint.build("usage of `ty::TyKind`")
.help("try using `Ty` instead")
.emit();
})
} else {
if ty.span.from_expansion() {
return;
}
if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
if path.segments.len() > 1 {
cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
lint.build(&format!("usage of qualified `ty::{}`", t))
.span_suggestion(
path.span,
"try using it unqualified",
t,
// The import probably needs to be changed
Applicability::MaybeIncorrect,
)
.emit();
})
}
}
}
@ -169,37 +167,30 @@ fn lint_ty_kind_usage(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> bool {
}
fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, ty: &Ty<'_>) -> Option<String> {
if let TyKind::Path(qpath) = &ty.kind {
if let QPath::Resolved(_, path) = qpath {
match path.res {
Res::Def(_, def_id) => {
if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id)
{
return Some(format!(
"{}{}",
name,
gen_args(path.segments.last().unwrap())
));
}
if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind {
match path.res {
Res::Def(_, def_id) => {
if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id) {
return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
}
// Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
Res::SelfTy(None, Some((did, _))) => {
if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
if let Some(name @ (sym::Ty | sym::TyCtxt)) =
cx.tcx.get_diagnostic_name(adt.did)
{
// NOTE: This path is currently unreachable as `Ty<'tcx>` is
// defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
// is not actually allowed.
//
// I(@lcnr) still kept this branch in so we don't miss this
// if we ever change it in the future.
return Some(format!("{}<{}>", name, substs[0]));
}
}
}
_ => (),
}
// Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
Res::SelfTy(None, Some((did, _))) => {
if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
if let Some(name @ (sym::Ty | sym::TyCtxt)) =
cx.tcx.get_diagnostic_name(adt.did)
{
// NOTE: This path is currently unreachable as `Ty<'tcx>` is
// defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
// is not actually allowed.
//
// I(@lcnr) still kept this branch in so we don't miss this
// if we ever change it in the future.
return Some(format!("{}<{}>", name, substs[0]));
}
}
}
_ => (),
}
}

View File

@ -24,11 +24,9 @@ fn parse_attributes(field: &syn::Field) -> Attributes {
}
if meta.path().is_ident("project") {
if let Meta::List(list) = meta {
if let Some(nested) = list.nested.iter().next() {
if let NestedMeta::Meta(meta) = nested {
attrs.project = meta.path().get_ident().cloned();
any_attr = true;
}
if let Some(NestedMeta::Meta(meta)) = list.nested.iter().next() {
attrs.project = meta.path().get_ident().cloned();
any_attr = true;
}
}
}

View File

@ -309,7 +309,7 @@ impl Collector<'tcx> {
.libs
.iter()
.filter_map(|lib| lib.name.as_ref())
.any(|n| &n.as_str() == &lib.name);
.any(|n| n.as_str() == lib.name);
if new_name.is_empty() {
self.tcx.sess.err(&format!(
"an empty renaming target was specified for library `{}`",

View File

@ -210,10 +210,10 @@ impl<'tcx> CheckConstVisitor<'tcx> {
required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
match missing_gates.as_slice() {
&[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),
[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),
&[missing_primary, ref missing_secondary @ ..] => {
let mut err = feature_err(&tcx.sess.parse_sess, missing_primary, span, &msg);
[missing_primary, ref missing_secondary @ ..] => {
let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg);
// If multiple feature gates would be required to enable this expression, include
// them as help messages. Don't emit a separate error for each missing feature gate.

View File

@ -1346,12 +1346,10 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
} else {
// Search in module.
let mod_path = &path[..path.len() - 1];
if let PathResult::Module(module) =
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
{
if let ModuleOrUniformRoot::Module(module) = module {
self.r.add_module_candidates(module, &mut names, &filter_fn);
}
self.r.add_module_candidates(module, &mut names, &filter_fn);
}
}

View File

@ -1931,20 +1931,18 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
break;
}
}
hir::TyKind::Path(ref qpath) => {
if let QPath::Resolved(_, path) = qpath {
let last_segment = &path.segments[path.segments.len() - 1];
let generics = last_segment.args();
for arg in generics.args.iter() {
if let GenericArg::Lifetime(lt) = arg {
if lt.name.ident() == name {
elide_use = Some(lt.span);
break;
}
hir::TyKind::Path(QPath::Resolved(_, path)) => {
let last_segment = &path.segments[path.segments.len() - 1];
let generics = last_segment.args();
for arg in generics.args.iter() {
if let GenericArg::Lifetime(lt) = arg {
if lt.name.ident() == name {
elide_use = Some(lt.span);
break;
}
}
break;
}
break;
}
_ => {}
}

View File

@ -914,7 +914,7 @@ pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateCo
pub(super) fn build_target_config(
opts: &Options,
target_override: Option<Target>,
sysroot: &PathBuf,
sysroot: &Path,
) -> Target {
let target_result = target_override.map_or_else(
|| Target::search(&opts.target_triple, sysroot),

View File

@ -881,7 +881,7 @@ mod parse {
match v {
Some(s) => {
if !slot.is_empty() {
slot.push_str(",");
slot.push(',');
}
slot.push_str(s);
true

View File

@ -194,10 +194,8 @@ impl<S: Encoder> Encodable<S> for RealFileName {
encoder.emit_enum(|encoder| match *self {
RealFileName::LocalPath(ref local_path) => {
encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| {
Ok({
encoder
.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
})
encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
Ok(())
})
}
@ -206,12 +204,9 @@ impl<S: Encoder> Encodable<S> for RealFileName {
// For privacy and build reproducibility, we must not embed host-dependant path in artifacts
// if they have been remapped by --remap-path-prefix
assert!(local_path.is_none());
Ok({
encoder
.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
encoder
.emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
})
encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
encoder.emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
Ok(())
}),
})
}

View File

@ -2071,7 +2071,7 @@ impl Target {
/// JSON decoding.
pub fn search(
target_triple: &TargetTriple,
sysroot: &PathBuf,
sysroot: &Path,
) -> Result<(Target, TargetWarnings), String> {
use rustc_serialize::json;
use std::env;

View File

@ -2000,19 +2000,14 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
let sized_trait = self.tcx.lang_items().sized_trait();
debug!("maybe_suggest_unsized_generics: generics.params={:?}", generics.params);
debug!("maybe_suggest_unsized_generics: generics.where_clause={:?}", generics.where_clause);
let param = generics
.params
.iter()
.filter(|param| param.span == span)
.filter(|param| {
// Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
// `Sized` bound is there intentionally and we don't need to suggest relaxing it.
param
.bounds
.iter()
.all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
})
.next();
let param = generics.params.iter().filter(|param| param.span == span).find(|param| {
// Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
// `Sized` bound is there intentionally and we don't need to suggest relaxing it.
param
.bounds
.iter()
.all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
});
let param = match param {
Some(param) => param,
_ => return,

View File

@ -446,7 +446,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
if let hir::ExprKind::Lit(_) = expr.kind {
if let Ok(src) = sm.span_to_snippet(sp) {
if let Some(_) = replace_prefix(&src, "b\"", "\"") {
if replace_prefix(&src, "b\"", "\"").is_some() {
let pos = sp.lo() + BytePos(1);
return Some((
sp.with_hi(pos),
@ -462,7 +462,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
if let hir::ExprKind::Lit(_) = expr.kind {
if let Ok(src) = sm.span_to_snippet(sp) {
if let Some(_) = replace_prefix(&src, "\"", "b\"") {
if replace_prefix(&src, "\"", "b\"").is_some() {
return Some((
sp.shrink_to_lo(),
"consider adding a leading `b`",

View File

@ -2058,8 +2058,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) -> Option<(&Vec<ty::FieldDef>, SubstsRef<'tcx>)> {
debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_t);
let mut autoderef = self.autoderef(span, base_t);
while let Some((base_t, _)) = autoderef.next() {
for (base_t, _) in self.autoderef(span, base_t) {
match base_t.kind() {
ty::Adt(base_def, substs) if !base_def.is_enum() => {
let fields = &base_def.non_enum_variant().fields;

View File

@ -176,7 +176,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
.type_var_origin(ty)
.map(|origin| origin.span)
.unwrap_or(rustc_span::DUMMY_SP);
let oty = self.inner.borrow().opaque_types_vars.get(ty).map(|v| *v);
let oty = self.inner.borrow().opaque_types_vars.get(ty).copied();
if let Some(opaque_ty) = oty {
debug!(
"fallback_opaque_type_vars(ty={:?}): falling back to opaque type {:?}",

View File

@ -1045,34 +1045,32 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
call_expr: &'tcx hir::Expr<'tcx>,
) {
if let hir::ExprKind::Call(path, _) = &call_expr.kind {
if let hir::ExprKind::Path(qpath) = &path.kind {
if let hir::QPath::Resolved(_, path) = &qpath {
for error in errors {
if let ty::PredicateKind::Trait(predicate) =
error.obligation.predicate.kind().skip_binder()
if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &path.kind {
for error in errors {
if let ty::PredicateKind::Trait(predicate) =
error.obligation.predicate.kind().skip_binder()
{
// If any of the type arguments in this path segment caused the
// `FulfillmentError`, point at its span (#61860).
for arg in path
.segments
.iter()
.filter_map(|seg| seg.args.as_ref())
.flat_map(|a| a.args.iter())
{
// If any of the type arguments in this path segment caused the
// `FulfillmentError`, point at its span (#61860).
for arg in path
.segments
.iter()
.filter_map(|seg| seg.args.as_ref())
.flat_map(|a| a.args.iter())
{
if let hir::GenericArg::Type(hir_ty) = &arg {
if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) =
&hir_ty.kind
{
// Avoid ICE with associated types. As this is best
// effort only, it's ok to ignore the case. It
// would trigger in `is_send::<T::AssocType>();`
// from `typeck-default-trait-impl-assoc-type.rs`.
} else {
let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, hir_ty);
let ty = self.resolve_vars_if_possible(ty);
if ty == predicate.self_ty() {
error.obligation.cause.make_mut().span = hir_ty.span;
}
if let hir::GenericArg::Type(hir_ty) = &arg {
if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) =
&hir_ty.kind
{
// Avoid ICE with associated types. As this is best
// effort only, it's ok to ignore the case. It
// would trigger in `is_send::<T::AssocType>();`
// from `typeck-default-trait-impl-assoc-type.rs`.
} else {
let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, hir_ty);
let ty = self.resolve_vars_if_possible(ty);
if ty == predicate.self_ty() {
error.obligation.cause.make_mut().span = hir_ty.span;
}
}
}

View File

@ -1208,7 +1208,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let edition_fix = candidates
.iter()
.find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
.map(|&d| d);
.copied();
err.help("items from traits can only be used if the trait is in scope");
let msg = format!(

View File

@ -399,12 +399,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
};
if let Ref(_, rty, _) = lhs_ty.kind() {
if {
self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span)
&& self
.lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
.is_ok()
} {
if self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span)
&& self.lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign)).is_ok()
{
if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
let msg = &format!(
"`{}{}` can be used on `{}`, you can dereference `{}`",

View File

@ -435,9 +435,7 @@ fn check_gat_where_clauses(
let written_predicates: ty::GenericPredicates<'_> =
tcx.explicit_predicates_of(trait_item.def_id);
let mut clauses: Vec<_> = clauses
.drain_filter(|clause| {
written_predicates.predicates.iter().find(|p| &p.0 == clause).is_none()
})
.drain_filter(|clause| !written_predicates.predicates.iter().any(|p| &p.0 == clause))
.map(|clause| format!("{}", clause))
.collect();
// We sort so that order is predictable