From eceaf94f1936436e33ae235ca65bf2a6d4f77da5 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 18 Feb 2020 15:32:19 +0200 Subject: [PATCH] More manual clippy fixes --- .../src/handlers/add_custom_impl.rs | 4 +- crates/ra_assists/src/handlers/move_guard.rs | 6 +- crates/ra_hir/src/code_model.rs | 36 +++++----- crates/ra_hir_def/src/item_scope.rs | 2 +- crates/ra_hir_def/src/lib.rs | 4 +- crates/ra_hir_expand/src/builtin_macro.rs | 11 ++- crates/ra_hir_expand/src/quote.rs | 5 +- crates/ra_hir_ty/src/diagnostics.rs | 2 +- crates/ra_hir_ty/src/expr.rs | 2 +- crates/ra_hir_ty/src/infer/coerce.rs | 7 +- crates/ra_hir_ty/src/infer/expr.rs | 16 ++--- crates/ra_hir_ty/src/infer/unify.rs | 5 +- crates/ra_hir_ty/src/lib.rs | 5 +- crates/ra_hir_ty/src/op.rs | 24 +++---- crates/ra_hir_ty/src/test_db.rs | 7 +- crates/ra_hir_ty/src/tests.rs | 8 +-- crates/ra_hir_ty/src/traits.rs | 9 +-- crates/ra_hir_ty/src/traits/builtin.rs | 4 +- crates/ra_hir_ty/src/traits/chalk.rs | 3 +- crates/ra_ide/src/call_info.rs | 2 +- .../src/completion/complete_trait_impl.rs | 8 +-- .../ra_ide/src/completion/completion_item.rs | 4 +- .../ra_ide/src/display/function_signature.rs | 5 +- .../ra_ide/src/display/navigation_target.rs | 4 +- crates/ra_ide/src/references.rs | 2 +- crates/ra_ide/src/ssr.rs | 14 ++-- crates/ra_mbe/src/parser.rs | 17 ++--- crates/ra_parser/src/grammar/items.rs | 2 +- crates/ra_parser/src/parser.rs | 4 +- .../ra_project_model/src/cargo_workspace.rs | 2 +- crates/ra_project_model/src/lib.rs | 67 +++++++++++-------- xtask/src/install.rs | 9 ++- 32 files changed, 141 insertions(+), 159 deletions(-) diff --git a/crates/ra_assists/src/handlers/add_custom_impl.rs b/crates/ra_assists/src/handlers/add_custom_impl.rs index 4d3a72c186..74aa4b0016 100644 --- a/crates/ra_assists/src/handlers/add_custom_impl.rs +++ b/crates/ra_assists/src/handlers/add_custom_impl.rs @@ -43,7 +43,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option { .clone(); let trait_token = - ctx.token_at_offset().filter(|t| t.kind() == IDENT && *t.text() != attr_name).next()?; + ctx.token_at_offset().find(|t| t.kind() == IDENT && *t.text() != attr_name)?; let annotated = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?; let annotated_name = annotated.syntax().text().to_string(); @@ -86,7 +86,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option { .next_sibling_or_token() .filter(|t| t.kind() == WHITESPACE) .map(|t| t.text_range()) - .unwrap_or(TextRange::from_to(TextUnit::from(0), TextUnit::from(0))); + .unwrap_or_else(|| TextRange::from_to(TextUnit::from(0), TextUnit::from(0))); edit.delete(line_break_range); attr_range.len() + line_break_range.len() diff --git a/crates/ra_assists/src/handlers/move_guard.rs b/crates/ra_assists/src/handlers/move_guard.rs index a61a2ba3e1..1cc4986389 100644 --- a/crates/ra_assists/src/handlers/move_guard.rs +++ b/crates/ra_assists/src/handlers/move_guard.rs @@ -44,7 +44,7 @@ pub(crate) fn move_guard_to_arm_body(ctx: AssistCtx) -> Option { edit.target(guard.syntax().text_range()); let offseting_amount = match space_before_guard.and_then(|it| it.into_token()) { Some(tok) => { - if let Some(_) = ast::Whitespace::cast(tok.clone()) { + if ast::Whitespace::cast(tok.clone()).is_some() { let ele = tok.text_range(); edit.delete(ele); ele.len() @@ -98,11 +98,11 @@ pub(crate) fn move_arm_cond_to_match_guard(ctx: AssistCtx) -> Option { let then_block = if_expr.then_branch()?; // Not support if with else branch - if let Some(_) = if_expr.else_branch() { + if if_expr.else_branch().is_some() { return None; } // Not support moving if let to arm guard - if let Some(_) = cond.pat() { + if cond.pat().is_some() { return None; } diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index fe9149c9d8..1bdcda0694 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs @@ -988,20 +988,17 @@ impl Type { pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> { if let Ty::Apply(a_ty) = &self.ty.value { - match a_ty.ctor { - TypeCtor::Adt(AdtId::StructId(s)) => { - let var_def = s.into(); - return db - .field_types(var_def) - .iter() - .map(|(local_id, ty)| { - let def = StructField { parent: var_def.into(), id: local_id }; - let ty = ty.clone().subst(&a_ty.parameters); - (def, self.derived(ty)) - }) - .collect(); - } - _ => {} + if let TypeCtor::Adt(AdtId::StructId(s)) = a_ty.ctor { + let var_def = s.into(); + return db + .field_types(var_def) + .iter() + .map(|(local_id, ty)| { + let def = StructField { parent: var_def.into(), id: local_id }; + let ty = ty.clone().subst(&a_ty.parameters); + (def, self.derived(ty)) + }) + .collect(); } }; Vec::new() @@ -1010,14 +1007,11 @@ impl Type { pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec { let mut res = Vec::new(); if let Ty::Apply(a_ty) = &self.ty.value { - match a_ty.ctor { - TypeCtor::Tuple { .. } => { - for ty in a_ty.parameters.iter() { - let ty = ty.clone(); - res.push(self.derived(ty)); - } + if let TypeCtor::Tuple { .. } = a_ty.ctor { + for ty in a_ty.parameters.iter() { + let ty = ty.clone(); + res.push(self.derived(ty)); } - _ => {} } }; res diff --git a/crates/ra_hir_def/src/item_scope.rs b/crates/ra_hir_def/src/item_scope.rs index f8dc06d106..6e958ca75c 100644 --- a/crates/ra_hir_def/src/item_scope.rs +++ b/crates/ra_hir_def/src/item_scope.rs @@ -157,7 +157,7 @@ impl ItemScope { } pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator + 'a { - self.visible.iter().map(|(name, res)| (name.clone(), res.clone())) + self.visible.iter().map(|(name, res)| (name.clone(), *res)) } pub(crate) fn collect_legacy_macros(&self) -> FxHashMap { diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs index aa0b558b8e..564b5fec57 100644 --- a/crates/ra_hir_def/src/lib.rs +++ b/crates/ra_hir_def/src/lib.rs @@ -460,7 +460,7 @@ impl AsMacroCall for AstIdWithPath { resolver: impl Fn(path::ModPath) -> Option, ) -> Option { let def = resolver(self.path.clone())?; - Some(def.as_call_id(db, MacroCallKind::FnLike(self.ast_id.clone()))) + Some(def.as_call_id(db, MacroCallKind::FnLike(self.ast_id))) } } @@ -471,6 +471,6 @@ impl AsMacroCall for AstIdWithPath { resolver: impl Fn(path::ModPath) -> Option, ) -> Option { let def = resolver(self.path.clone())?; - Some(def.as_call_id(db, MacroCallKind::Attr(self.ast_id.clone()))) + Some(def.as_call_id(db, MacroCallKind::Attr(self.ast_id))) } } diff --git a/crates/ra_hir_expand/src/builtin_macro.rs b/crates/ra_hir_expand/src/builtin_macro.rs index 4adaa9b078..f2bb0bddbb 100644 --- a/crates/ra_hir_expand/src/builtin_macro.rs +++ b/crates/ra_hir_expand/src/builtin_macro.rs @@ -155,14 +155,11 @@ fn compile_error_expand( tt: &tt::Subtree, ) -> Result { if tt.count() == 1 { - match &tt.token_trees[0] { - tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => { - let s = it.text.as_str(); - if s.contains('"') { - return Ok(quote! { loop { #it }}); - } + if let tt::TokenTree::Leaf(tt::Leaf::Literal(it)) = &tt.token_trees[0] { + let s = it.text.as_str(); + if s.contains('"') { + return Ok(quote! { loop { #it }}); } - _ => {} }; } diff --git a/crates/ra_hir_expand/src/quote.rs b/crates/ra_hir_expand/src/quote.rs index b54e00b688..57e7eebf9e 100644 --- a/crates/ra_hir_expand/src/quote.rs +++ b/crates/ra_hir_expand/src/quote.rs @@ -15,14 +15,13 @@ macro_rules! __quote { ( @SUBTREE $delim:ident $($tt:tt)* ) => { { let children = $crate::__quote!($($tt)*); - let subtree = tt::Subtree { + tt::Subtree { delimiter: Some(tt::Delimiter { kind: tt::DelimiterKind::$delim, id: tt::TokenId::unspecified(), }), token_trees: $crate::quote::IntoTt::to_tokens(children), - }; - subtree + } } }; diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs index 5054189cc1..6eafdc8f6d 100644 --- a/crates/ra_hir_ty/src/diagnostics.rs +++ b/crates/ra_hir_ty/src/diagnostics.rs @@ -40,7 +40,7 @@ impl Diagnostic for MissingFields { use std::fmt::Write; let mut message = String::from("Missing structure fields:\n"); for field in &self.missed_fields { - write!(message, "- {}\n", field).unwrap(); + writeln!(message, "- {}", field).unwrap(); } message } diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs index f752a9f09a..0d11b537c8 100644 --- a/crates/ra_hir_ty/src/expr.rs +++ b/crates/ra_hir_ty/src/expr.rs @@ -138,7 +138,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> { _ => return, }; - if params.len() == 2 && ¶ms[0] == &mismatch.actual { + if params.len() == 2 && params[0] == mismatch.actual { let (_, source_map) = db.body_with_source_map(self.func.into()); if let Some(source_ptr) = source_map.expr_syntax(id) { diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs index 4a0eabdfc6..fb6a51b127 100644 --- a/crates/ra_hir_ty/src/infer/coerce.rs +++ b/crates/ra_hir_ty/src/infer/coerce.rs @@ -26,7 +26,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { /// Note that it is only possible that one type are coerced to another. /// Coercing both types to another least upper bound type is not possible in rustc, /// which will simply result in "incompatible types" error. - pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { + pub(super) fn coerce_merge_branch(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { if self.coerce(ty1, ty2) { ty2.clone() } else if self.coerce(ty2, ty1) { @@ -252,15 +252,14 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { let unsize_generic_index = { let mut index = None; let mut multiple_param = false; - field_tys[last_field_id].value.walk(&mut |ty| match ty { - &Ty::Bound(idx) => { + field_tys[last_field_id].value.walk(&mut |ty| { + if let &Ty::Bound(idx) = ty { if index.is_none() { index = Some(idx); } else if Some(idx) != index { multiple_param = true; } } - _ => {} }); if multiple_param { diff --git a/crates/ra_hir_ty/src/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs index 0af94ae324..9d5f756257 100644 --- a/crates/ra_hir_ty/src/infer/expr.rs +++ b/crates/ra_hir_ty/src/infer/expr.rs @@ -35,8 +35,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, ); } - let ty = self.resolve_ty_as_possible(ty); - ty + self.resolve_ty_as_possible(ty) } /// Infer type of expression with possibly implicit coerce to the expected type. @@ -155,8 +154,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { }; self.register_obligations_for_call(&callee_ty); self.check_call_arguments(args, ¶m_tys); - let ret_ty = self.normalize_associated_types_in(ret_ty); - ret_ty + self.normalize_associated_types_in(ret_ty) } Expr::MethodCall { receiver, args, method_name, generic_args } => self .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), @@ -280,14 +278,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { } Expr::Await { expr } => { let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); - let ty = - self.resolve_associated_type(inner_ty, self.resolve_future_future_output()); - ty + self.resolve_associated_type(inner_ty, self.resolve_future_future_output()) } Expr::Try { expr } => { let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); - let ty = self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok()); - ty + self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok()) } Expr::Cast { expr, type_ref } => { let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); @@ -611,8 +606,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { self.unify(&expected_receiver_ty, &actual_receiver_ty); self.check_call_arguments(args, ¶m_tys); - let ret_ty = self.normalize_associated_types_in(ret_ty); - ret_ty + self.normalize_associated_types_in(ret_ty) } fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { diff --git a/crates/ra_hir_ty/src/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs index 1dc842f40e..9c79965724 100644 --- a/crates/ra_hir_ty/src/infer/unify.rs +++ b/crates/ra_hir_ty/src/infer/unify.rs @@ -140,13 +140,12 @@ where impl Canonicalized { pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { ty.walk_mut_binders( - &mut |ty, binders| match ty { - &mut Ty::Bound(idx) => { + &mut |ty, binders| { + if let &mut Ty::Bound(idx) = ty { if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { *ty = Ty::Infer(self.free_vars[idx as usize - binders]); } } - _ => {} }, 0, ); diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index 302bb8aa2c..13c5e6c6b7 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -763,8 +763,8 @@ pub trait TypeWalk { Self: Sized, { self.walk_mut_binders( - &mut |ty, binders| match ty { - &mut Ty::Bound(idx) => { + &mut |ty, binders| { + if let &mut Ty::Bound(idx) = ty { if idx as usize >= binders && (idx as usize - binders) < substs.len() { *ty = substs.0[idx as usize - binders].clone(); } else if idx as usize >= binders + substs.len() { @@ -772,7 +772,6 @@ pub trait TypeWalk { *ty = Ty::Bound(idx - substs.len() as u32); } } - _ => {} }, 0, ); diff --git a/crates/ra_hir_ty/src/op.rs b/crates/ra_hir_ty/src/op.rs index ae253ca048..54e2bd05a1 100644 --- a/crates/ra_hir_ty/src/op.rs +++ b/crates/ra_hir_ty/src/op.rs @@ -30,20 +30,18 @@ pub(super) fn binary_op_return_ty(op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Ty { pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty { match op { BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool), - BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => { - match lhs_ty { - Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { - TypeCtor::Int(..) - | TypeCtor::Float(..) - | TypeCtor::Str - | TypeCtor::Char - | TypeCtor::Bool => lhs_ty, - _ => Ty::Unknown, - }, - Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, + BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { .. }) => match lhs_ty { + Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { + TypeCtor::Int(..) + | TypeCtor::Float(..) + | TypeCtor::Str + | TypeCtor::Char + | TypeCtor::Bool => lhs_ty, _ => Ty::Unknown, - } - } + }, + Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, + _ => Ty::Unknown, + }, BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => Ty::Unknown, BinaryOp::CmpOp(CmpOp::Ord { .. }) | BinaryOp::Assignment { op: Some(_) } diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs index 1a31b587bb..c794f7b847 100644 --- a/crates/ra_hir_ty/src/test_db.rs +++ b/crates/ra_hir_ty/src/test_db.rs @@ -86,15 +86,14 @@ impl TestDB { pub fn diagnostics(&self) -> String { let mut buf = String::new(); let crate_graph = self.crate_graph(); - for krate in crate_graph.iter().next() { + for krate in crate_graph.iter() { let crate_def_map = self.crate_def_map(krate); let mut fns = Vec::new(); for (module_id, _) in crate_def_map.modules.iter() { for decl in crate_def_map[module_id].scope.declarations() { - match decl { - ModuleDefId::FunctionId(f) => fns.push(f), - _ => (), + if let ModuleDefId::FunctionId(f) = decl { + fns.push(f) } } diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs index d1f10e6752..240cc03a2c 100644 --- a/crates/ra_hir_ty/src/tests.rs +++ b/crates/ra_hir_ty/src/tests.rs @@ -101,9 +101,9 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { (src_ptr.value.range(), node.text().to_string().replace("\n", " ")) }; let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; - write!( + writeln!( acc, - "{}{} '{}': {}\n", + "{}{} '{}': {}", macro_prefix, range, ellipsize(text, 15), @@ -118,9 +118,9 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { for (src_ptr, mismatch) in &mismatches { let range = src_ptr.value.range(); let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; - write!( + writeln!( acc, - "{}{}: expected {}, got {}\n", + "{}{}: expected {}, got {}", macro_prefix, range, mismatch.expected.display(&db), diff --git a/crates/ra_hir_ty/src/traits.rs b/crates/ra_hir_ty/src/traits.rs index ff8e75b48e..e83449957e 100644 --- a/crates/ra_hir_ty/src/traits.rs +++ b/crates/ra_hir_ty/src/traits.rs @@ -248,12 +248,9 @@ fn solution_from_chalk( let value = subst .value .into_iter() - .map(|p| { - let ty = match p.ty() { - Some(ty) => from_chalk(db, ty.clone()), - None => unimplemented!(), - }; - ty + .map(|p| match p.ty() { + Some(ty) => from_chalk(db, ty.clone()), + None => unimplemented!(), }) .collect(); let result = Canonical { value, num_vars: subst.binders.len() }; diff --git a/crates/ra_hir_ty/src/traits/builtin.rs b/crates/ra_hir_ty/src/traits/builtin.rs index 67120abf6f..a537420a53 100644 --- a/crates/ra_hir_ty/src/traits/builtin.rs +++ b/crates/ra_hir_ty/src/traits/builtin.rs @@ -122,7 +122,7 @@ fn closure_fn_trait_impl_datum( substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), }; - let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()); + let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data); BuiltinImplData { num_vars: num_args as usize + 1, @@ -137,7 +137,7 @@ fn closure_fn_trait_output_assoc_ty_value( krate: CrateId, data: super::ClosureFnTraitImplData, ) -> BuiltinImplAssocTyValueData { - let impl_ = Impl::ClosureFnTraitImpl(data.clone()); + let impl_ = Impl::ClosureFnTraitImpl(data); let num_args: u16 = match &db.body(data.def)[data.expr] { Expr::Lambda { args, .. } => args.len() as u16, diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs index 306909ec23..1bdf13e480 100644 --- a/crates/ra_hir_ty/src/traits/chalk.rs +++ b/crates/ra_hir_ty/src/traits/chalk.rs @@ -409,8 +409,7 @@ where fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical { let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); let value = self.value.to_chalk(db); - let canonical = chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }; - canonical + chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] } } fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical) -> Canonical { diff --git a/crates/ra_ide/src/call_info.rs b/crates/ra_ide/src/call_info.rs index f2b29306e6..7c6322cb48 100644 --- a/crates/ra_ide/src/call_info.rs +++ b/crates/ra_ide/src/call_info.rs @@ -128,7 +128,7 @@ impl FnCallNode { }), FnCallNode::MethodCallExpr(call_expr) => { - call_expr.syntax().children().filter_map(ast::NameRef::cast).nth(0) + call_expr.syntax().children().filter_map(ast::NameRef::cast).next() } FnCallNode::MacroCallExpr(call_expr) => call_expr.path()?.segment()?.name_ref(), diff --git a/crates/ra_ide/src/completion/complete_trait_impl.rs b/crates/ra_ide/src/completion/complete_trait_impl.rs index 6ff10c0170..83628e35c2 100644 --- a/crates/ra_ide/src/completion/complete_trait_impl.rs +++ b/crates/ra_ide/src/completion/complete_trait_impl.rs @@ -59,7 +59,7 @@ pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext .as_ref() .and_then(|node| node.parent()) .and_then(|node| node.parent()) - .and_then(|node| ast::ImplBlock::cast(node)); + .and_then(ast::ImplBlock::cast); if let (Some(trigger), Some(impl_block)) = (trigger, impl_block) { match trigger.kind() { @@ -110,17 +110,17 @@ fn add_function_impl( ctx: &CompletionContext, func: &hir::Function, ) { - let display = FunctionSignature::from_hir(ctx.db, func.clone()); + let display = FunctionSignature::from_hir(ctx.db, *func); let fn_name = func.name(ctx.db).to_string(); - let label = if func.params(ctx.db).len() > 0 { + let label = if !func.params(ctx.db).is_empty() { format!("fn {}(..)", fn_name) } else { format!("fn {}()", fn_name) }; - let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label.clone()) + let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label) .lookup_by(fn_name) .set_documentation(func.docs(ctx.db)); diff --git a/crates/ra_ide/src/completion/completion_item.rs b/crates/ra_ide/src/completion/completion_item.rs index 93f3363709..61867c0ffd 100644 --- a/crates/ra_ide/src/completion/completion_item.rs +++ b/crates/ra_ide/src/completion/completion_item.rs @@ -159,7 +159,7 @@ impl CompletionItem { /// Short one-line additional information, like a type pub fn detail(&self) -> Option<&str> { - self.detail.as_ref().map(|it| it.as_str()) + self.detail.as_deref() } /// A doc-comment pub fn documentation(&self) -> Option { @@ -167,7 +167,7 @@ impl CompletionItem { } /// What string is used for filtering. pub fn lookup(&self) -> &str { - self.lookup.as_ref().map(|it| it.as_str()).unwrap_or_else(|| self.label()) + self.lookup.as_deref().unwrap_or_else(|| self.label()) } pub fn kind(&self) -> Option { diff --git a/crates/ra_ide/src/display/function_signature.rs b/crates/ra_ide/src/display/function_signature.rs index c23e08e9a3..b85fd80754 100644 --- a/crates/ra_ide/src/display/function_signature.rs +++ b/crates/ra_ide/src/display/function_signature.rs @@ -54,9 +54,8 @@ impl FunctionSignature { pub(crate) fn from_struct(db: &RootDatabase, st: hir::Struct) -> Option { let node: ast::StructDef = st.source(db).value; - match node.kind() { - ast::StructKind::Record(_) => return None, - _ => (), + if let ast::StructKind::Record(_) = node.kind() { + return None; }; let params = st diff --git a/crates/ra_ide/src/display/navigation_target.rs b/crates/ra_ide/src/display/navigation_target.rs index 906aab1eba..096c41c815 100644 --- a/crates/ra_ide/src/display/navigation_target.rs +++ b/crates/ra_ide/src/display/navigation_target.rs @@ -64,11 +64,11 @@ impl NavigationTarget { } pub fn docs(&self) -> Option<&str> { - self.docs.as_ref().map(String::as_str) + self.docs.as_deref() } pub fn description(&self) -> Option<&str> { - self.description.as_ref().map(String::as_str) + self.description.as_deref() } /// A "most interesting" range withing the `full_range`. diff --git a/crates/ra_ide/src/references.rs b/crates/ra_ide/src/references.rs index de924fad27..97c08ade50 100644 --- a/crates/ra_ide/src/references.rs +++ b/crates/ra_ide/src/references.rs @@ -268,7 +268,7 @@ fn decl_access( }; let stmt = find_node_at_offset::(syntax, range.start())?; - if let Some(_) = stmt.initializer() { + if stmt.initializer().is_some() { let pat = stmt.pat()?; if let ast::Pat::BindPat(it) = pat { if it.name()?.text().as_str() == name { diff --git a/crates/ra_ide/src/ssr.rs b/crates/ra_ide/src/ssr.rs index 14eb0b8b25..902c29fc62 100644 --- a/crates/ra_ide/src/ssr.rs +++ b/crates/ra_ide/src/ssr.rs @@ -85,8 +85,11 @@ impl FromStr for SsrQuery { fn from_str(query: &str) -> Result { let mut it = query.split("==>>"); let pattern = it.next().expect("at least empty string").trim(); - let mut template = - it.next().ok_or(SsrError("Cannot find delemiter `==>>`".into()))?.trim().to_string(); + let mut template = it + .next() + .ok_or_else(|| SsrError("Cannot find delemiter `==>>`".into()))? + .trim() + .to_string(); if it.next().is_some() { return Err(SsrError("More than one delimiter found".into())); } @@ -131,11 +134,12 @@ fn traverse(node: &SyntaxNode, go: &mut impl FnMut(&SyntaxNode) -> bool) { } fn split_by_var(s: &str) -> Result<(&str, &str, &str), SsrError> { - let end_of_name = s.find(":").ok_or(SsrError("Use $:expr".into()))?; + let end_of_name = s.find(':').ok_or_else(|| SsrError("Use $:expr".into()))?; let name = &s[0..end_of_name]; is_name(name)?; let type_begin = end_of_name + 1; - let type_length = s[type_begin..].find(|c| !char::is_ascii_alphanumeric(&c)).unwrap_or(s.len()); + let type_length = + s[type_begin..].find(|c| !char::is_ascii_alphanumeric(&c)).unwrap_or_else(|| s.len()); let type_name = &s[type_begin..type_begin + type_length]; Ok((name, type_name, &s[type_begin + type_length..])) } @@ -182,7 +186,7 @@ fn find(pattern: &SsrPattern, code: &SyntaxNode) -> SsrMatches { pattern.text() == code.text() } (SyntaxElement::Node(ref pattern), SyntaxElement::Node(ref code)) => { - if placeholders.iter().find(|&n| n.0.as_str() == pattern.text()).is_some() { + if placeholders.iter().any(|n| n.0.as_str() == pattern.text()) { match_.binding.insert(Var(pattern.text().to_string()), code.clone()); true } else { diff --git a/crates/ra_mbe/src/parser.rs b/crates/ra_mbe/src/parser.rs index 1cdebc2166..10a6f300a7 100644 --- a/crates/ra_mbe/src/parser.rs +++ b/crates/ra_mbe/src/parser.rs @@ -45,15 +45,15 @@ impl PartialEq for Separator { } } -pub(crate) fn parse_template<'a>( - template: &'a tt::Subtree, -) -> impl Iterator, ExpandError>> { +pub(crate) fn parse_template( + template: &tt::Subtree, +) -> impl Iterator, ExpandError>> { parse_inner(template, Mode::Template) } -pub(crate) fn parse_pattern<'a>( - pattern: &'a tt::Subtree, -) -> impl Iterator, ExpandError>> { +pub(crate) fn parse_pattern( + pattern: &tt::Subtree, +) -> impl Iterator, ExpandError>> { parse_inner(pattern, Mode::Pattern) } @@ -63,10 +63,7 @@ enum Mode { Template, } -fn parse_inner<'a>( - src: &'a tt::Subtree, - mode: Mode, -) -> impl Iterator, ExpandError>> { +fn parse_inner(src: &tt::Subtree, mode: Mode) -> impl Iterator, ExpandError>> { let mut src = TtIter::new(src); std::iter::from_fn(move || { let first = src.next()?; diff --git a/crates/ra_parser/src/grammar/items.rs b/crates/ra_parser/src/grammar/items.rs index 54284c933e..f8b43866cb 100644 --- a/crates/ra_parser/src/grammar/items.rs +++ b/crates/ra_parser/src/grammar/items.rs @@ -21,7 +21,7 @@ use super::*; // struct S; pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) { attributes::inner_attributes(p); - while !p.at(EOF) && !(stop_on_r_curly && p.at(T!['}'])) { + while !(stop_on_r_curly && p.at(T!['}']) || p.at(EOF)) { item_or_macro(p, stop_on_r_curly, ItemFlavor::Mod) } } diff --git a/crates/ra_parser/src/parser.rs b/crates/ra_parser/src/parser.rs index 1071c46dc8..76e2d4f7d0 100644 --- a/crates/ra_parser/src/parser.rs +++ b/crates/ra_parser/src/parser.rs @@ -126,13 +126,13 @@ impl<'t> Parser<'t> { } fn at_composite2(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind) -> bool { - let t1 = self.token_source.lookahead_nth(n + 0); + let t1 = self.token_source.lookahead_nth(n); let t2 = self.token_source.lookahead_nth(n + 1); t1.kind == k1 && t1.is_jointed_to_next && t2.kind == k2 } fn at_composite3(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind, k3: SyntaxKind) -> bool { - let t1 = self.token_source.lookahead_nth(n + 0); + let t1 = self.token_source.lookahead_nth(n); let t2 = self.token_source.lookahead_nth(n + 1); let t3 = self.token_source.lookahead_nth(n + 2); (t1.kind == k1 && t1.is_jointed_to_next) diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index 34fd73bb74..4fea459d5b 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -197,7 +197,7 @@ impl CargoWorkspace { let pkg_data = &mut packages[pkg]; pkg_by_id.insert(id, pkg); for meta_tgt in meta_pkg.targets { - let is_proc_macro = meta_tgt.kind.as_slice() == &["proc-macro"]; + let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"]; let tgt = targets.alloc(TargetData { pkg, name: meta_tgt.name, diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 9e67d24989..e35f7fbbcb 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -197,8 +197,9 @@ impl ProjectWorkspace { if let (Some(&from), Some(&to)) = (crates.get(&from_crate_id), crates.get(&to_crate_id)) { - if let Err(_) = - crate_graph.add_dep(from, CrateName::new(&dep.name).unwrap(), to) + if crate_graph + .add_dep(from, CrateName::new(&dep.name).unwrap(), to) + .is_err() { log::error!( "cyclic dependency {:?} -> {:?}", @@ -237,8 +238,7 @@ impl ProjectWorkspace { if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) { - if let Err(_) = - crate_graph.add_dep(from, CrateName::new(name).unwrap(), to) + if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err() { log::error!("cyclic dependency between sysroot crates") } @@ -279,11 +279,14 @@ impl ProjectWorkspace { } if tgt.is_proc_macro(&cargo) { if let Some(proc_macro) = libproc_macro { - if let Err(_) = crate_graph.add_dep( - crate_id, - CrateName::new("proc_macro").unwrap(), - proc_macro, - ) { + if crate_graph + .add_dep( + crate_id, + CrateName::new("proc_macro").unwrap(), + proc_macro, + ) + .is_err() + { log::error!( "cyclic dependency on proc_macro for {}", pkg.name(&cargo) @@ -299,15 +302,19 @@ impl ProjectWorkspace { // Set deps to the core, std and to the lib target of the current package for &from in pkg_crates.get(&pkg).into_iter().flatten() { if let Some(to) = lib_tgt { - if to != from { - if let Err(_) = crate_graph.add_dep( - from, - // For root projects with dashes in their name, - // cargo metadata does not do any normalization, - // so we do it ourselves currently - CrateName::normalize_dashes(pkg.name(&cargo)), - to, - ) { + if to != from + && crate_graph + .add_dep( + from, + // For root projects with dashes in their name, + // cargo metadata does not do any normalization, + // so we do it ourselves currently + CrateName::normalize_dashes(pkg.name(&cargo)), + to, + ) + .is_err() + { + { log::error!( "cyclic dependency between targets of {}", pkg.name(&cargo) @@ -318,22 +325,25 @@ impl ProjectWorkspace { // core is added as a dependency before std in order to // mimic rustcs dependency order if let Some(core) = libcore { - if let Err(_) = - crate_graph.add_dep(from, CrateName::new("core").unwrap(), core) + if crate_graph + .add_dep(from, CrateName::new("core").unwrap(), core) + .is_err() { log::error!("cyclic dependency on core for {}", pkg.name(&cargo)) } } if let Some(alloc) = liballoc { - if let Err(_) = - crate_graph.add_dep(from, CrateName::new("alloc").unwrap(), alloc) + if crate_graph + .add_dep(from, CrateName::new("alloc").unwrap(), alloc) + .is_err() { log::error!("cyclic dependency on alloc for {}", pkg.name(&cargo)) } } if let Some(std) = libstd { - if let Err(_) = - crate_graph.add_dep(from, CrateName::new("std").unwrap(), std) + if crate_graph + .add_dep(from, CrateName::new("std").unwrap(), std) + .is_err() { log::error!("cyclic dependency on std for {}", pkg.name(&cargo)) } @@ -347,11 +357,10 @@ impl ProjectWorkspace { for dep in pkg.dependencies(&cargo) { if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) { for &from in pkg_crates.get(&pkg).into_iter().flatten() { - if let Err(_) = crate_graph.add_dep( - from, - CrateName::new(&dep.name).unwrap(), - to, - ) { + if crate_graph + .add_dep(from, CrateName::new(&dep.name).unwrap(), to) + .is_err() + { log::error!( "cyclic dependency {} -> {}", pkg.name(&cargo), diff --git a/xtask/src/install.rs b/xtask/src/install.rs index cc6fecc85f..3df021acc3 100644 --- a/xtask/src/install.rs +++ b/xtask/src/install.rs @@ -94,8 +94,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { }) }; - let installed_extensions; - if cfg!(unix) { + let installed_extensions = if cfg!(unix) { run!("npm --version").context("`npm` is required to build the VS Code plugin")?; run!("npm install")?; @@ -103,7 +102,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { let code = find_code(|bin| run!("{} --version", bin).is_ok())?; run!("{} --install-extension rust-analyzer.vsix --force", code)?; - installed_extensions = run!("{} --list-extensions", code; echo = false)?; + run!("{} --list-extensions", code; echo = false)? } else { run!("cmd.exe /c npm --version") .context("`npm` is required to build the VS Code plugin")?; @@ -113,8 +112,8 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { let code = find_code(|bin| run!("cmd.exe /c {}.cmd --version", bin).is_ok())?; run!(r"cmd.exe /c {}.cmd --install-extension rust-analyzer.vsix --force", code)?; - installed_extensions = run!("cmd.exe /c {}.cmd --list-extensions", code; echo = false)?; - } + run!("cmd.exe /c {}.cmd --list-extensions", code; echo = false)? + }; if !installed_extensions.contains("rust-analyzer") { bail!(