More manual clippy fixes

This commit is contained in:
Kirill Bulatov 2020-02-18 15:32:19 +02:00
parent b8ddcb0652
commit eceaf94f19
32 changed files with 141 additions and 159 deletions

View file

@ -43,7 +43,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
.clone(); .clone();
let trait_token = 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 = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?;
let annotated_name = annotated.syntax().text().to_string(); let annotated_name = annotated.syntax().text().to_string();
@ -86,7 +86,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
.next_sibling_or_token() .next_sibling_or_token()
.filter(|t| t.kind() == WHITESPACE) .filter(|t| t.kind() == WHITESPACE)
.map(|t| t.text_range()) .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); edit.delete(line_break_range);
attr_range.len() + line_break_range.len() attr_range.len() + line_break_range.len()

View file

@ -44,7 +44,7 @@ pub(crate) fn move_guard_to_arm_body(ctx: AssistCtx) -> Option<Assist> {
edit.target(guard.syntax().text_range()); edit.target(guard.syntax().text_range());
let offseting_amount = match space_before_guard.and_then(|it| it.into_token()) { let offseting_amount = match space_before_guard.and_then(|it| it.into_token()) {
Some(tok) => { Some(tok) => {
if let Some(_) = ast::Whitespace::cast(tok.clone()) { if ast::Whitespace::cast(tok.clone()).is_some() {
let ele = tok.text_range(); let ele = tok.text_range();
edit.delete(ele); edit.delete(ele);
ele.len() ele.len()
@ -98,11 +98,11 @@ pub(crate) fn move_arm_cond_to_match_guard(ctx: AssistCtx) -> Option<Assist> {
let then_block = if_expr.then_branch()?; let then_block = if_expr.then_branch()?;
// Not support if with else branch // Not support if with else branch
if let Some(_) = if_expr.else_branch() { if if_expr.else_branch().is_some() {
return None; return None;
} }
// Not support moving if let to arm guard // Not support moving if let to arm guard
if let Some(_) = cond.pat() { if cond.pat().is_some() {
return None; return None;
} }

View file

@ -988,20 +988,17 @@ impl Type {
pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> { pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> {
if let Ty::Apply(a_ty) = &self.ty.value { if let Ty::Apply(a_ty) = &self.ty.value {
match a_ty.ctor { if let TypeCtor::Adt(AdtId::StructId(s)) = a_ty.ctor {
TypeCtor::Adt(AdtId::StructId(s)) => { let var_def = s.into();
let var_def = s.into(); return db
return db .field_types(var_def)
.field_types(var_def) .iter()
.iter() .map(|(local_id, ty)| {
.map(|(local_id, ty)| { let def = StructField { parent: var_def.into(), id: local_id };
let def = StructField { parent: var_def.into(), id: local_id }; let ty = ty.clone().subst(&a_ty.parameters);
let ty = ty.clone().subst(&a_ty.parameters); (def, self.derived(ty))
(def, self.derived(ty)) })
}) .collect();
.collect();
}
_ => {}
} }
}; };
Vec::new() Vec::new()
@ -1010,14 +1007,11 @@ impl Type {
pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec<Type> { pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec<Type> {
let mut res = Vec::new(); let mut res = Vec::new();
if let Ty::Apply(a_ty) = &self.ty.value { if let Ty::Apply(a_ty) = &self.ty.value {
match a_ty.ctor { if let TypeCtor::Tuple { .. } = a_ty.ctor {
TypeCtor::Tuple { .. } => { for ty in a_ty.parameters.iter() {
for ty in a_ty.parameters.iter() { let ty = ty.clone();
let ty = ty.clone(); res.push(self.derived(ty));
res.push(self.derived(ty));
}
} }
_ => {}
} }
}; };
res res

View file

@ -157,7 +157,7 @@ impl ItemScope {
} }
pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Name, PerNs)> + 'a { pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Name, PerNs)> + '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<Name, MacroDefId> { pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {

View file

@ -460,7 +460,7 @@ impl AsMacroCall for AstIdWithPath<ast::MacroCall> {
resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
) -> Option<MacroCallId> { ) -> Option<MacroCallId> {
let def = resolver(self.path.clone())?; 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<ast::ModuleItem> {
resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
) -> Option<MacroCallId> { ) -> Option<MacroCallId> {
let def = resolver(self.path.clone())?; 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)))
} }
} }

View file

@ -155,14 +155,11 @@ fn compile_error_expand(
tt: &tt::Subtree, tt: &tt::Subtree,
) -> Result<tt::Subtree, mbe::ExpandError> { ) -> Result<tt::Subtree, mbe::ExpandError> {
if tt.count() == 1 { if tt.count() == 1 {
match &tt.token_trees[0] { if let tt::TokenTree::Leaf(tt::Leaf::Literal(it)) = &tt.token_trees[0] {
tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => { let s = it.text.as_str();
let s = it.text.as_str(); if s.contains('"') {
if s.contains('"') { return Ok(quote! { loop { #it }});
return Ok(quote! { loop { #it }});
}
} }
_ => {}
}; };
} }

View file

@ -15,14 +15,13 @@ macro_rules! __quote {
( @SUBTREE $delim:ident $($tt:tt)* ) => { ( @SUBTREE $delim:ident $($tt:tt)* ) => {
{ {
let children = $crate::__quote!($($tt)*); let children = $crate::__quote!($($tt)*);
let subtree = tt::Subtree { tt::Subtree {
delimiter: Some(tt::Delimiter { delimiter: Some(tt::Delimiter {
kind: tt::DelimiterKind::$delim, kind: tt::DelimiterKind::$delim,
id: tt::TokenId::unspecified(), id: tt::TokenId::unspecified(),
}), }),
token_trees: $crate::quote::IntoTt::to_tokens(children), token_trees: $crate::quote::IntoTt::to_tokens(children),
}; }
subtree
} }
}; };

View file

@ -40,7 +40,7 @@ impl Diagnostic for MissingFields {
use std::fmt::Write; use std::fmt::Write;
let mut message = String::from("Missing structure fields:\n"); let mut message = String::from("Missing structure fields:\n");
for field in &self.missed_fields { for field in &self.missed_fields {
write!(message, "- {}\n", field).unwrap(); writeln!(message, "- {}", field).unwrap();
} }
message message
} }

View file

@ -138,7 +138,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
_ => return, _ => return,
}; };
if params.len() == 2 && &params[0] == &mismatch.actual { if params.len() == 2 && params[0] == mismatch.actual {
let (_, source_map) = db.body_with_source_map(self.func.into()); let (_, source_map) = db.body_with_source_map(self.func.into());
if let Some(source_ptr) = source_map.expr_syntax(id) { if let Some(source_ptr) = source_map.expr_syntax(id) {

View file

@ -26,7 +26,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
/// Note that it is only possible that one type are coerced to another. /// 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, /// Coercing both types to another least upper bound type is not possible in rustc,
/// which will simply result in "incompatible types" error. /// 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) { if self.coerce(ty1, ty2) {
ty2.clone() ty2.clone()
} else if self.coerce(ty2, ty1) { } else if self.coerce(ty2, ty1) {
@ -252,15 +252,14 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
let unsize_generic_index = { let unsize_generic_index = {
let mut index = None; let mut index = None;
let mut multiple_param = false; let mut multiple_param = false;
field_tys[last_field_id].value.walk(&mut |ty| match ty { field_tys[last_field_id].value.walk(&mut |ty| {
&Ty::Bound(idx) => { if let &Ty::Bound(idx) = ty {
if index.is_none() { if index.is_none() {
index = Some(idx); index = Some(idx);
} else if Some(idx) != index { } else if Some(idx) != index {
multiple_param = true; multiple_param = true;
} }
} }
_ => {}
}); });
if multiple_param { if multiple_param {

View file

@ -35,8 +35,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() },
); );
} }
let ty = self.resolve_ty_as_possible(ty); self.resolve_ty_as_possible(ty)
ty
} }
/// Infer type of expression with possibly implicit coerce to the expected type. /// 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.register_obligations_for_call(&callee_ty);
self.check_call_arguments(args, &param_tys); self.check_call_arguments(args, &param_tys);
let ret_ty = self.normalize_associated_types_in(ret_ty); self.normalize_associated_types_in(ret_ty)
ret_ty
} }
Expr::MethodCall { receiver, args, method_name, generic_args } => self Expr::MethodCall { receiver, args, method_name, generic_args } => self
.infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), .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 } => { Expr::Await { expr } => {
let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
let ty = self.resolve_associated_type(inner_ty, self.resolve_future_future_output())
self.resolve_associated_type(inner_ty, self.resolve_future_future_output());
ty
} }
Expr::Try { expr } => { Expr::Try { expr } => {
let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
let ty = self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok()); self.resolve_associated_type(inner_ty, self.resolve_ops_try_ok())
ty
} }
Expr::Cast { expr, type_ref } => { Expr::Cast { expr, type_ref } => {
let _inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 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.unify(&expected_receiver_ty, &actual_receiver_ty);
self.check_call_arguments(args, &param_tys); self.check_call_arguments(args, &param_tys);
let ret_ty = self.normalize_associated_types_in(ret_ty); self.normalize_associated_types_in(ret_ty)
ret_ty
} }
fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) {

View file

@ -140,13 +140,12 @@ where
impl<T> Canonicalized<T> { impl<T> Canonicalized<T> {
pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
ty.walk_mut_binders( ty.walk_mut_binders(
&mut |ty, binders| match ty { &mut |ty, binders| {
&mut Ty::Bound(idx) => { if let &mut Ty::Bound(idx) = ty {
if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() {
*ty = Ty::Infer(self.free_vars[idx as usize - binders]); *ty = Ty::Infer(self.free_vars[idx as usize - binders]);
} }
} }
_ => {}
}, },
0, 0,
); );

View file

@ -763,8 +763,8 @@ pub trait TypeWalk {
Self: Sized, Self: Sized,
{ {
self.walk_mut_binders( self.walk_mut_binders(
&mut |ty, binders| match ty { &mut |ty, binders| {
&mut Ty::Bound(idx) => { if let &mut Ty::Bound(idx) = ty {
if idx as usize >= binders && (idx as usize - binders) < substs.len() { if idx as usize >= binders && (idx as usize - binders) < substs.len() {
*ty = substs.0[idx as usize - binders].clone(); *ty = substs.0[idx as usize - binders].clone();
} else if idx as usize >= binders + substs.len() { } else if idx as usize >= binders + substs.len() {
@ -772,7 +772,6 @@ pub trait TypeWalk {
*ty = Ty::Bound(idx - substs.len() as u32); *ty = Ty::Bound(idx - substs.len() as u32);
} }
} }
_ => {}
}, },
0, 0,
); );

View file

@ -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 { pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty {
match op { match op {
BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool), BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool),
BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => { BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { .. }) => match lhs_ty {
match lhs_ty { Ty::Apply(ApplicationTy { ctor, .. }) => match ctor {
Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { TypeCtor::Int(..)
TypeCtor::Int(..) | TypeCtor::Float(..)
| TypeCtor::Float(..) | TypeCtor::Str
| TypeCtor::Str | TypeCtor::Char
| TypeCtor::Char | TypeCtor::Bool => lhs_ty,
| TypeCtor::Bool => lhs_ty,
_ => Ty::Unknown,
},
Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty,
_ => Ty::Unknown, _ => 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::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => Ty::Unknown,
BinaryOp::CmpOp(CmpOp::Ord { .. }) BinaryOp::CmpOp(CmpOp::Ord { .. })
| BinaryOp::Assignment { op: Some(_) } | BinaryOp::Assignment { op: Some(_) }

View file

@ -86,15 +86,14 @@ impl TestDB {
pub fn diagnostics(&self) -> String { pub fn diagnostics(&self) -> String {
let mut buf = String::new(); let mut buf = String::new();
let crate_graph = self.crate_graph(); 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 crate_def_map = self.crate_def_map(krate);
let mut fns = Vec::new(); let mut fns = Vec::new();
for (module_id, _) in crate_def_map.modules.iter() { for (module_id, _) in crate_def_map.modules.iter() {
for decl in crate_def_map[module_id].scope.declarations() { for decl in crate_def_map[module_id].scope.declarations() {
match decl { if let ModuleDefId::FunctionId(f) = decl {
ModuleDefId::FunctionId(f) => fns.push(f), fns.push(f)
_ => (),
} }
} }

View file

@ -101,9 +101,9 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
(src_ptr.value.range(), node.text().to_string().replace("\n", " ")) (src_ptr.value.range(), node.text().to_string().replace("\n", " "))
}; };
let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
write!( writeln!(
acc, acc,
"{}{} '{}': {}\n", "{}{} '{}': {}",
macro_prefix, macro_prefix,
range, range,
ellipsize(text, 15), ellipsize(text, 15),
@ -118,9 +118,9 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
for (src_ptr, mismatch) in &mismatches { for (src_ptr, mismatch) in &mismatches {
let range = src_ptr.value.range(); let range = src_ptr.value.range();
let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
write!( writeln!(
acc, acc,
"{}{}: expected {}, got {}\n", "{}{}: expected {}, got {}",
macro_prefix, macro_prefix,
range, range,
mismatch.expected.display(&db), mismatch.expected.display(&db),

View file

@ -248,12 +248,9 @@ fn solution_from_chalk(
let value = subst let value = subst
.value .value
.into_iter() .into_iter()
.map(|p| { .map(|p| match p.ty() {
let ty = match p.ty() { Some(ty) => from_chalk(db, ty.clone()),
Some(ty) => from_chalk(db, ty.clone()), None => unimplemented!(),
None => unimplemented!(),
};
ty
}) })
.collect(); .collect();
let result = Canonical { value, num_vars: subst.binders.len() }; let result = Canonical { value, num_vars: subst.binders.len() };

View file

@ -122,7 +122,7 @@ fn closure_fn_trait_impl_datum(
substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), 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 { BuiltinImplData {
num_vars: num_args as usize + 1, num_vars: num_args as usize + 1,
@ -137,7 +137,7 @@ fn closure_fn_trait_output_assoc_ty_value(
krate: CrateId, krate: CrateId,
data: super::ClosureFnTraitImplData, data: super::ClosureFnTraitImplData,
) -> BuiltinImplAssocTyValueData { ) -> BuiltinImplAssocTyValueData {
let impl_ = Impl::ClosureFnTraitImpl(data.clone()); let impl_ = Impl::ClosureFnTraitImpl(data);
let num_args: u16 = match &db.body(data.def)[data.expr] { let num_args: u16 = match &db.body(data.def)[data.expr] {
Expr::Lambda { args, .. } => args.len() as u16, Expr::Lambda { args, .. } => args.len() as u16,

View file

@ -409,8 +409,7 @@ where
fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical<T::Chalk> { fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT);
let value = self.value.to_chalk(db); let value = self.value.to_chalk(db);
let canonical = chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }; chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }
canonical
} }
fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> { fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {

View file

@ -128,7 +128,7 @@ impl FnCallNode {
}), }),
FnCallNode::MethodCallExpr(call_expr) => { 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(), FnCallNode::MacroCallExpr(call_expr) => call_expr.path()?.segment()?.name_ref(),

View file

@ -59,7 +59,7 @@ pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext
.as_ref() .as_ref()
.and_then(|node| node.parent()) .and_then(|node| node.parent())
.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) { if let (Some(trigger), Some(impl_block)) = (trigger, impl_block) {
match trigger.kind() { match trigger.kind() {
@ -110,17 +110,17 @@ fn add_function_impl(
ctx: &CompletionContext, ctx: &CompletionContext,
func: &hir::Function, 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 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) format!("fn {}(..)", fn_name)
} else { } else {
format!("fn {}()", fn_name) 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) .lookup_by(fn_name)
.set_documentation(func.docs(ctx.db)); .set_documentation(func.docs(ctx.db));

View file

@ -159,7 +159,7 @@ impl CompletionItem {
/// Short one-line additional information, like a type /// Short one-line additional information, like a type
pub fn detail(&self) -> Option<&str> { pub fn detail(&self) -> Option<&str> {
self.detail.as_ref().map(|it| it.as_str()) self.detail.as_deref()
} }
/// A doc-comment /// A doc-comment
pub fn documentation(&self) -> Option<Documentation> { pub fn documentation(&self) -> Option<Documentation> {
@ -167,7 +167,7 @@ impl CompletionItem {
} }
/// What string is used for filtering. /// What string is used for filtering.
pub fn lookup(&self) -> &str { 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<CompletionItemKind> { pub fn kind(&self) -> Option<CompletionItemKind> {

View file

@ -54,9 +54,8 @@ impl FunctionSignature {
pub(crate) fn from_struct(db: &RootDatabase, st: hir::Struct) -> Option<Self> { pub(crate) fn from_struct(db: &RootDatabase, st: hir::Struct) -> Option<Self> {
let node: ast::StructDef = st.source(db).value; let node: ast::StructDef = st.source(db).value;
match node.kind() { if let ast::StructKind::Record(_) = node.kind() {
ast::StructKind::Record(_) => return None, return None;
_ => (),
}; };
let params = st let params = st

View file

@ -64,11 +64,11 @@ impl NavigationTarget {
} }
pub fn docs(&self) -> Option<&str> { pub fn docs(&self) -> Option<&str> {
self.docs.as_ref().map(String::as_str) self.docs.as_deref()
} }
pub fn description(&self) -> Option<&str> { 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`. /// A "most interesting" range withing the `full_range`.

View file

@ -268,7 +268,7 @@ fn decl_access(
}; };
let stmt = find_node_at_offset::<ast::LetStmt>(syntax, range.start())?; let stmt = find_node_at_offset::<ast::LetStmt>(syntax, range.start())?;
if let Some(_) = stmt.initializer() { if stmt.initializer().is_some() {
let pat = stmt.pat()?; let pat = stmt.pat()?;
if let ast::Pat::BindPat(it) = pat { if let ast::Pat::BindPat(it) = pat {
if it.name()?.text().as_str() == name { if it.name()?.text().as_str() == name {

View file

@ -85,8 +85,11 @@ impl FromStr for SsrQuery {
fn from_str(query: &str) -> Result<SsrQuery, SsrError> { fn from_str(query: &str) -> Result<SsrQuery, SsrError> {
let mut it = query.split("==>>"); let mut it = query.split("==>>");
let pattern = it.next().expect("at least empty string").trim(); let pattern = it.next().expect("at least empty string").trim();
let mut template = let mut template = it
it.next().ok_or(SsrError("Cannot find delemiter `==>>`".into()))?.trim().to_string(); .next()
.ok_or_else(|| SsrError("Cannot find delemiter `==>>`".into()))?
.trim()
.to_string();
if it.next().is_some() { if it.next().is_some() {
return Err(SsrError("More than one delimiter found".into())); 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> { fn split_by_var(s: &str) -> Result<(&str, &str, &str), SsrError> {
let end_of_name = s.find(":").ok_or(SsrError("Use $<name>:expr".into()))?; let end_of_name = s.find(':').ok_or_else(|| SsrError("Use $<name>:expr".into()))?;
let name = &s[0..end_of_name]; let name = &s[0..end_of_name];
is_name(name)?; is_name(name)?;
let type_begin = end_of_name + 1; 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]; let type_name = &s[type_begin..type_begin + type_length];
Ok((name, type_name, &s[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() pattern.text() == code.text()
} }
(SyntaxElement::Node(ref pattern), SyntaxElement::Node(ref code)) => { (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()); match_.binding.insert(Var(pattern.text().to_string()), code.clone());
true true
} else { } else {

View file

@ -45,15 +45,15 @@ impl PartialEq for Separator {
} }
} }
pub(crate) fn parse_template<'a>( pub(crate) fn parse_template(
template: &'a tt::Subtree, template: &tt::Subtree,
) -> impl Iterator<Item = Result<Op<'a>, ExpandError>> { ) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
parse_inner(template, Mode::Template) parse_inner(template, Mode::Template)
} }
pub(crate) fn parse_pattern<'a>( pub(crate) fn parse_pattern(
pattern: &'a tt::Subtree, pattern: &tt::Subtree,
) -> impl Iterator<Item = Result<Op<'a>, ExpandError>> { ) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
parse_inner(pattern, Mode::Pattern) parse_inner(pattern, Mode::Pattern)
} }
@ -63,10 +63,7 @@ enum Mode {
Template, Template,
} }
fn parse_inner<'a>( fn parse_inner(src: &tt::Subtree, mode: Mode) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
src: &'a tt::Subtree,
mode: Mode,
) -> impl Iterator<Item = Result<Op<'a>, ExpandError>> {
let mut src = TtIter::new(src); let mut src = TtIter::new(src);
std::iter::from_fn(move || { std::iter::from_fn(move || {
let first = src.next()?; let first = src.next()?;

View file

@ -21,7 +21,7 @@ use super::*;
// struct S; // struct S;
pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) { pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) {
attributes::inner_attributes(p); 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) item_or_macro(p, stop_on_r_curly, ItemFlavor::Mod)
} }
} }

View file

@ -126,13 +126,13 @@ impl<'t> Parser<'t> {
} }
fn at_composite2(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind) -> bool { 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); let t2 = self.token_source.lookahead_nth(n + 1);
t1.kind == k1 && t1.is_jointed_to_next && t2.kind == k2 t1.kind == k1 && t1.is_jointed_to_next && t2.kind == k2
} }
fn at_composite3(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind, k3: SyntaxKind) -> bool { 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 t2 = self.token_source.lookahead_nth(n + 1);
let t3 = self.token_source.lookahead_nth(n + 2); let t3 = self.token_source.lookahead_nth(n + 2);
(t1.kind == k1 && t1.is_jointed_to_next) (t1.kind == k1 && t1.is_jointed_to_next)

View file

@ -197,7 +197,7 @@ impl CargoWorkspace {
let pkg_data = &mut packages[pkg]; let pkg_data = &mut packages[pkg];
pkg_by_id.insert(id, pkg); pkg_by_id.insert(id, pkg);
for meta_tgt in meta_pkg.targets { 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 { let tgt = targets.alloc(TargetData {
pkg, pkg,
name: meta_tgt.name, name: meta_tgt.name,

View file

@ -197,8 +197,9 @@ impl ProjectWorkspace {
if let (Some(&from), Some(&to)) = if let (Some(&from), Some(&to)) =
(crates.get(&from_crate_id), crates.get(&to_crate_id)) (crates.get(&from_crate_id), crates.get(&to_crate_id))
{ {
if let Err(_) = if crate_graph
crate_graph.add_dep(from, CrateName::new(&dep.name).unwrap(), to) .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
.is_err()
{ {
log::error!( log::error!(
"cyclic dependency {:?} -> {:?}", "cyclic dependency {:?} -> {:?}",
@ -237,8 +238,7 @@ impl ProjectWorkspace {
if let (Some(&from), Some(&to)) = if let (Some(&from), Some(&to)) =
(sysroot_crates.get(&from), sysroot_crates.get(&to)) (sysroot_crates.get(&from), sysroot_crates.get(&to))
{ {
if let Err(_) = if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
crate_graph.add_dep(from, CrateName::new(name).unwrap(), to)
{ {
log::error!("cyclic dependency between sysroot crates") log::error!("cyclic dependency between sysroot crates")
} }
@ -279,11 +279,14 @@ impl ProjectWorkspace {
} }
if tgt.is_proc_macro(&cargo) { if tgt.is_proc_macro(&cargo) {
if let Some(proc_macro) = libproc_macro { if let Some(proc_macro) = libproc_macro {
if let Err(_) = crate_graph.add_dep( if crate_graph
crate_id, .add_dep(
CrateName::new("proc_macro").unwrap(), crate_id,
proc_macro, CrateName::new("proc_macro").unwrap(),
) { proc_macro,
)
.is_err()
{
log::error!( log::error!(
"cyclic dependency on proc_macro for {}", "cyclic dependency on proc_macro for {}",
pkg.name(&cargo) pkg.name(&cargo)
@ -299,15 +302,19 @@ impl ProjectWorkspace {
// Set deps to the core, std and to the lib target of the current package // 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() { for &from in pkg_crates.get(&pkg).into_iter().flatten() {
if let Some(to) = lib_tgt { if let Some(to) = lib_tgt {
if to != from { if to != from
if let Err(_) = crate_graph.add_dep( && crate_graph
from, .add_dep(
// For root projects with dashes in their name, from,
// cargo metadata does not do any normalization, // For root projects with dashes in their name,
// so we do it ourselves currently // cargo metadata does not do any normalization,
CrateName::normalize_dashes(pkg.name(&cargo)), // so we do it ourselves currently
to, CrateName::normalize_dashes(pkg.name(&cargo)),
) { to,
)
.is_err()
{
{
log::error!( log::error!(
"cyclic dependency between targets of {}", "cyclic dependency between targets of {}",
pkg.name(&cargo) pkg.name(&cargo)
@ -318,22 +325,25 @@ impl ProjectWorkspace {
// core is added as a dependency before std in order to // core is added as a dependency before std in order to
// mimic rustcs dependency order // mimic rustcs dependency order
if let Some(core) = libcore { if let Some(core) = libcore {
if let Err(_) = if crate_graph
crate_graph.add_dep(from, CrateName::new("core").unwrap(), core) .add_dep(from, CrateName::new("core").unwrap(), core)
.is_err()
{ {
log::error!("cyclic dependency on core for {}", pkg.name(&cargo)) log::error!("cyclic dependency on core for {}", pkg.name(&cargo))
} }
} }
if let Some(alloc) = liballoc { if let Some(alloc) = liballoc {
if let Err(_) = if crate_graph
crate_graph.add_dep(from, CrateName::new("alloc").unwrap(), alloc) .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
.is_err()
{ {
log::error!("cyclic dependency on alloc for {}", pkg.name(&cargo)) log::error!("cyclic dependency on alloc for {}", pkg.name(&cargo))
} }
} }
if let Some(std) = libstd { if let Some(std) = libstd {
if let Err(_) = if crate_graph
crate_graph.add_dep(from, CrateName::new("std").unwrap(), std) .add_dep(from, CrateName::new("std").unwrap(), std)
.is_err()
{ {
log::error!("cyclic dependency on std for {}", pkg.name(&cargo)) log::error!("cyclic dependency on std for {}", pkg.name(&cargo))
} }
@ -347,11 +357,10 @@ impl ProjectWorkspace {
for dep in pkg.dependencies(&cargo) { for dep in pkg.dependencies(&cargo) {
if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) { if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
for &from in pkg_crates.get(&pkg).into_iter().flatten() { for &from in pkg_crates.get(&pkg).into_iter().flatten() {
if let Err(_) = crate_graph.add_dep( if crate_graph
from, .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
CrateName::new(&dep.name).unwrap(), .is_err()
to, {
) {
log::error!( log::error!(
"cyclic dependency {} -> {}", "cyclic dependency {} -> {}",
pkg.name(&cargo), pkg.name(&cargo),

View file

@ -94,8 +94,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> {
}) })
}; };
let installed_extensions; let installed_extensions = if cfg!(unix) {
if cfg!(unix) {
run!("npm --version").context("`npm` is required to build the VS Code plugin")?; run!("npm --version").context("`npm` is required to build the VS Code plugin")?;
run!("npm install")?; run!("npm install")?;
@ -103,7 +102,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> {
let code = find_code(|bin| run!("{} --version", bin).is_ok())?; let code = find_code(|bin| run!("{} --version", bin).is_ok())?;
run!("{} --install-extension rust-analyzer.vsix --force", code)?; run!("{} --install-extension rust-analyzer.vsix --force", code)?;
installed_extensions = run!("{} --list-extensions", code; echo = false)?; run!("{} --list-extensions", code; echo = false)?
} else { } else {
run!("cmd.exe /c npm --version") run!("cmd.exe /c npm --version")
.context("`npm` is required to build the VS Code plugin")?; .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())?; 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)?; 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") { if !installed_extensions.contains("rust-analyzer") {
bail!( bail!(