11692: round of clippy fixes. r=Veykril a=matthiaskrgr

Split these up into smaller chunks so I can easily revert parts of it if needed.

Co-authored-by: Matthias Krüger <matthias.krueger@famsik.de>
This commit is contained in:
bors[bot] 2022-03-12 15:53:05 +00:00 committed by GitHub
commit 5fcf979f8a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
77 changed files with 215 additions and 271 deletions

View file

@ -394,9 +394,9 @@ struct FileMeta {
}
fn parse_crate(crate_str: String) -> (String, CrateOrigin, Option<String>) {
if let Some((a, b)) = crate_str.split_once("@") {
let (version, origin) = match b.split_once(":") {
Some(("CratesIo", data)) => match data.split_once(",") {
if let Some((a, b)) = crate_str.split_once('@') {
let (version, origin) = match b.split_once(':') {
Some(("CratesIo", data)) => match data.split_once(',') {
Some((version, url)) => {
(version, CrateOrigin::CratesIo { repo: Some(url.to_owned()) })
}

View file

@ -82,8 +82,8 @@ impl From<GenericParam> for GenericParamId {
fn from(id: GenericParam) -> Self {
match id {
GenericParam::LifetimeParam(it) => GenericParamId::LifetimeParamId(it.id),
GenericParam::ConstParam(it) => GenericParamId::ConstParamId(it.id.into()),
GenericParam::TypeParam(it) => GenericParamId::TypeParamId(it.id.into()),
GenericParam::ConstParam(it) => GenericParamId::ConstParamId(it.id),
GenericParam::TypeParam(it) => GenericParamId::TypeParamId(it.id),
}
}
}

View file

@ -231,7 +231,7 @@ impl Crate {
return None;
}
let doc_url = doc_attr_q.tt_values().map(|tt| {
let doc_url = doc_attr_q.tt_values().filter_map(|tt| {
let name = tt.token_trees.iter()
.skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident { text, ..} )) if text == "html_root_url"))
.nth(2);
@ -240,7 +240,7 @@ impl Crate {
Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
_ => None
}
}).flatten().next();
}).next();
doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
}
@ -1530,11 +1530,7 @@ impl SelfParam {
let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
let environment = db.trait_environment(self.func.into());
Type {
krate,
env: environment.clone(),
ty: ctx.lower_ty(&db.function_data(self.func).params[0].1),
}
Type { krate, env: environment, ty: ctx.lower_ty(&db.function_data(self.func).params[0].1) }
}
}
@ -1816,14 +1812,12 @@ impl Macro {
pub fn is_builtin_derive(&self, db: &dyn HirDatabase) -> bool {
match self.id {
MacroId::Macro2Id(it) => match it.lookup(db.upcast()).expander {
MacroExpander::BuiltInDerive(_) => true,
_ => false,
},
MacroId::MacroRulesId(it) => match it.lookup(db.upcast()).expander {
MacroExpander::BuiltInDerive(_) => true,
_ => false,
},
MacroId::Macro2Id(it) => {
matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
}
MacroId::MacroRulesId(it) => {
matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
}
MacroId::ProcMacroId(_) => false,
}
}

View file

@ -398,7 +398,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
}
pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
self.imp.scope_at_offset(&node, offset)
self.imp.scope_at_offset(node, offset)
}
pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {

View file

@ -603,7 +603,7 @@ fn resolve_hir_path_(
// within the trait's associated types.
if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
if let Some(type_alias_id) =
db.trait_data(trait_id).associated_type_by_name(&unresolved.name)
db.trait_data(trait_id).associated_type_by_name(unresolved.name)
{
return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
}

View file

@ -667,7 +667,7 @@ impl DocsRangeMap {
let InFile { file_id, value: source } = self.source_map.source_of_id(idx);
match source {
Either::Left(attr) => {
let string = get_doc_string_in_attr(&attr)?;
let string = get_doc_string_in_attr(attr)?;
let text_range = string.open_quote_text_range()?;
let range = TextRange::at(
text_range.end() + original_line_src_range.start() + relative_range.start(),

View file

@ -421,12 +421,12 @@ impl BodySourceMap {
}
pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
let src = node.map(|it| AstPtr::new(it));
let src = node.map(AstPtr::new);
self.expr_map.get(&src).cloned()
}
pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
let src = node.map(|it| AstPtr::new(it));
let src = node.map(AstPtr::new);
self.expansions.get(&src).cloned()
}
@ -449,7 +449,7 @@ impl BodySourceMap {
}
pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
let src = node.map(|it| AstPtr::new(it));
let src = node.map(AstPtr::new);
self.label_map.get(&src).cloned()
}
@ -457,7 +457,7 @@ impl BodySourceMap {
self.field_map_back[&expr].clone()
}
pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
let src = node.map(|it| AstPtr::new(it));
let src = node.map(AstPtr::new);
self.field_map.get(&src).cloned()
}

View file

@ -941,17 +941,15 @@ impl From<ast::LiteralKind> for Literal {
LiteralKind::IntNumber(lit) => {
if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
Literal::Float(Default::default(), builtin)
} else if let builtin @ Some(_) =
lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
{
} else if let builtin @ Some(_) = lit.suffix().and_then(BuiltinInt::from_suffix) {
Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
} else {
let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
let builtin = lit.suffix().and_then(BuiltinUint::from_suffix);
Literal::Uint(lit.value().unwrap_or(0), builtin)
}
}
LiteralKind::FloatNumber(lit) => {
let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
let ty = lit.suffix().and_then(BuiltinFloat::from_suffix);
Literal::Float(Default::default(), ty)
}
LiteralKind::ByteString(bs) => {

View file

@ -66,7 +66,7 @@ impl FunctionData {
.by_key("rustc_legacy_const_generics")
.tt_values()
.next()
.map(|arg| parse_rustc_legacy_const_generics(arg))
.map(parse_rustc_legacy_const_generics)
.unwrap_or_default();
Arc::new(FunctionData {

View file

@ -72,7 +72,7 @@ impl TypeOrConstParamData {
pub fn type_param(&self) -> Option<&TypeParamData> {
match self {
TypeOrConstParamData::TypeParamData(x) => Some(&x),
TypeOrConstParamData::TypeParamData(x) => Some(x),
TypeOrConstParamData::ConstParamData(_) => None,
}
}

View file

@ -500,7 +500,7 @@ impl<'a> Printer<'a> {
if i != 0 {
w!(self, ", ");
}
self.print_type_ref(&typeref);
self.print_type_ref(typeref);
}
if *varargs {
if !args.is_empty() {
@ -509,7 +509,7 @@ impl<'a> Printer<'a> {
w!(self, "...");
}
w!(self, ") -> ");
self.print_type_ref(&return_type);
self.print_type_ref(return_type);
}
TypeRef::Macro(_ast_id) => {
w!(self, "<macro>");

View file

@ -178,7 +178,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
if tree {
let tree = format!("{:#?}", parse.syntax_node())
.split_inclusive("\n")
.split_inclusive('\n')
.map(|line| format!("// {}", line))
.collect::<String>();
format_to!(expn_text, "\n{}", tree)
@ -191,7 +191,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
if let Some((tree, map, _)) = arg.as_deref() {
let tt_range = call.token_tree().unwrap().syntax().text_range();
let mut ranges = Vec::new();
extract_id_ranges(&mut ranges, &map, &tree);
extract_id_ranges(&mut ranges, map, tree);
for (range, id) in ranges {
let idx = (tt_range.start() + range.end()).into();
text_edits.push((idx..idx, format!("#{}", id.0)));
@ -269,7 +269,7 @@ fn reindent(indent: IndentLevel, pp: String) -> String {
let mut res = lines.next().unwrap().to_string();
for line in lines {
if line.trim().is_empty() {
res.push_str(&line)
res.push_str(line)
} else {
format_to!(res, "{}{}", indent, line)
}

View file

@ -52,7 +52,7 @@ impl DefMap {
return Ok(ResolvedAttr::Other);
}
}
None => return Err(UnresolvedMacro { path: ast_id.path.clone() }),
None => return Err(UnresolvedMacro { path: ast_id.path }),
};
Ok(ResolvedAttr::Macro(attr_macro_as_call_id(

View file

@ -504,10 +504,8 @@ impl DefCollector<'_> {
} else {
PathKind::Abs
};
let path = ModPath::from_segments(
path_kind.clone(),
[krate.clone(), name![prelude], edition].into_iter(),
);
let path =
ModPath::from_segments(path_kind, [krate.clone(), name![prelude], edition].into_iter());
// Fall back to the older `std::prelude::v1` for compatibility with Rust <1.52.0
// FIXME remove this fallback
let fallback_path =
@ -570,7 +568,7 @@ impl DefCollector<'_> {
let proc_macro_id =
ProcMacroLoc { container: module_id, id, expander, kind }.intern(self.db);
self.define_proc_macro(def.name.clone(), proc_macro_id.into());
self.define_proc_macro(def.name.clone(), proc_macro_id);
if let ProcMacroKind::CustomDerive { helpers } = def.kind {
self.def_map
.exported_derives

View file

@ -120,7 +120,7 @@ impl Path {
let res = Path {
type_anchor: self.type_anchor.clone(),
mod_path: Interned::new(ModPath::from_segments(
self.mod_path.kind.clone(),
self.mod_path.kind,
self.mod_path.segments()[..self.mod_path.segments().len() - 1].iter().cloned(),
)),
generic_args: self.generic_args[..self.generic_args.len() - 1].to_vec().into(),

View file

@ -245,7 +245,7 @@ impl TypeRef {
f(type_ref);
match type_ref {
TypeRef::Fn(params, _) => {
params.iter().for_each(|(_, param_type)| go(&param_type, f))
params.iter().for_each(|(_, param_type)| go(param_type, f))
}
TypeRef::Tuple(types) => types.iter().for_each(|t| go(t, f)),
TypeRef::RawPtr(type_ref, _)

View file

@ -88,9 +88,8 @@ fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
debug!("parsed item has no name");
ExpandError::Other("missing name".into())
})?;
let name_token_id = token_map
.token_by_range(name.syntax().text_range())
.unwrap_or_else(|| TokenId::unspecified());
let name_token_id =
token_map.token_by_range(name.syntax().text_range()).unwrap_or_else(TokenId::unspecified);
let name_token = tt::Ident { id: name_token_id, text: name.text().into() };
let type_or_const_params =
params.map_or(0, |type_param_list| type_param_list.type_or_const_params().count());

View file

@ -446,7 +446,7 @@ fn concat_bytes_expand(
match token.kind() {
syntax::SyntaxKind::BYTE => bytes.push(token.text().to_string()),
syntax::SyntaxKind::BYTE_STRING => {
let components = unquote_byte_string(lit).unwrap_or_else(|| Vec::new());
let components = unquote_byte_string(lit).unwrap_or_else(Vec::new);
components.into_iter().for_each(|x| bytes.push(x.to_string()));
}
_ => {

View file

@ -149,11 +149,11 @@ pub fn expand_speculative(
let token_range = token_to_map.text_range();
// Build the subtree and token mapping for the speculative args
let censor = censor_for_macro_input(&loc, &speculative_args);
let mut fixups = fixup::fixup_syntax(&speculative_args);
let censor = censor_for_macro_input(&loc, speculative_args);
let mut fixups = fixup::fixup_syntax(speculative_args);
fixups.replace.extend(censor.into_iter().map(|node| (node, Vec::new())));
let (mut tt, spec_args_tmap, _) = mbe::syntax_node_to_token_tree_with_modifications(
&speculative_args,
speculative_args,
fixups.token_map,
fixups.next_id,
fixups.replace,

View file

@ -146,7 +146,7 @@ pub fn expand_eager_macro(
if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
let res = eager.expand(db, arg_id, &subtree);
if let Some(err) = res.err {
diagnostic_sink(err.into());
diagnostic_sink(err);
}
let loc = MacroCallLoc {
@ -207,7 +207,7 @@ fn eager_macro_recur(
// Collect replacement
for child in children {
let def = match child.path().and_then(|path| ModPath::from_src(db, path, &hygiene)) {
let def = match child.path().and_then(|path| ModPath::from_src(db, path, hygiene)) {
Some(path) => macro_resolver(path.clone()).ok_or_else(|| UnresolvedMacro { path })?,
None => {
diagnostic_sink(ExpandError::Other("malformed macro invocation".into()));

View file

@ -176,7 +176,7 @@ mod tests {
);
let mut actual = tt.to_string();
actual.push_str("\n");
actual.push('\n');
expect.indent(false);
expect.assert_eq(&actual);

View file

@ -261,7 +261,7 @@ mod tests {
// }
let struct_name = mk_ident("Foo");
let fields = [mk_ident("name"), mk_ident("id")];
let fields = fields.iter().map(|it| quote!(#it: self.#it.clone(), ).token_trees).flatten();
let fields = fields.iter().flat_map(|it| quote!(#it: self.#it.clone(), ).token_trees);
let list = tt::Subtree {
delimiter: Some(tt::Delimiter {

View file

@ -235,14 +235,14 @@ pub fn eval_const(expr: &Expr, ctx: &mut ConstEvalCtx<'_>) -> Result<ComputedExp
Ok(ComputedExpr::Literal(Literal::Int(r, None)))
}
BinaryOp::LogicOp(_) => Err(ConstEvalError::TypeError),
_ => return Err(ConstEvalError::NotSupported("bin op on this operators")),
_ => Err(ConstEvalError::NotSupported("bin op on this operators")),
}
}
Expr::Block { statements, tail, .. } => {
let mut prev_values = HashMap::<Name, Option<ComputedExpr>>::default();
for statement in &**statements {
match statement {
&hir_def::expr::Statement::Let { pat, initializer, .. } => {
match *statement {
hir_def::expr::Statement::Let { pat, initializer, .. } => {
let pat = &ctx.pats[pat];
let name = match pat {
Pat::Bind { name, subpat, .. } if subpat.is_none() => name.clone(),
@ -261,7 +261,7 @@ pub fn eval_const(expr: &Expr, ctx: &mut ConstEvalCtx<'_>) -> Result<ComputedExp
ctx.local_data.insert(name, value);
}
}
&hir_def::expr::Statement::Expr { .. } => {
hir_def::expr::Statement::Expr { .. } => {
return Err(ConstEvalError::NotSupported("this kind of statement"))
}
}
@ -293,7 +293,7 @@ pub fn eval_const(expr: &Expr, ctx: &mut ConstEvalCtx<'_>) -> Result<ComputedExp
pub fn eval_usize(expr: Idx<Expr>, mut ctx: ConstEvalCtx<'_>) -> Option<u64> {
let expr = &ctx.exprs[expr];
if let Ok(ce) = eval_const(&expr, &mut ctx) {
if let Ok(ce) = eval_const(expr, &mut ctx) {
match ce {
ComputedExpr::Literal(Literal::Int(x, _)) => return x.try_into().ok(),
ComputedExpr::Literal(Literal::Uint(x, _)) => return x.try_into().ok(),

View file

@ -82,7 +82,7 @@ pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> T
let trait_env = owner
.as_generic_def_id()
.map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
let mut table = unify::InferenceTable::new(db, trait_env.clone());
let mut table = unify::InferenceTable::new(db, trait_env);
let ty_with_vars = table.normalize_associated_types_in(ty);
table.resolve_obligations_as_possible();

View file

@ -1059,7 +1059,7 @@ pub(crate) fn generic_predicates_for_param_query(
| WherePredicate::TypeBound { target, bound, .. } => {
match target {
WherePredicateTypeTarget::TypeRef(type_ref) => {
if ctx.lower_ty_only_param(type_ref) != Some(param_id.into()) {
if ctx.lower_ty_only_param(type_ref) != Some(param_id) {
return false;
}
}

View file

@ -278,7 +278,7 @@ impl InherentImpls {
impls.collect_def_map(db, &crate_def_map);
impls.shrink_to_fit();
return Arc::new(impls);
Arc::new(impls)
}
pub(crate) fn inherent_impls_in_block_query(
@ -291,7 +291,7 @@ impl InherentImpls {
impls.shrink_to_fit();
return Some(Arc::new(impls));
}
return None;
None
}
fn shrink_to_fit(&mut self) {
@ -663,7 +663,7 @@ pub fn iterate_method_candidates_dyn(
iterate_method_candidates_for_self_ty(
ty,
db,
env.clone(),
env,
traits_in_scope,
visible_from_module,
name,
@ -693,7 +693,7 @@ fn iterate_method_candidates_with_autoref(
iterate_method_candidates_by_receiver(
receiver_ty,
first_adjustment.clone(),
&rest,
rest,
db,
env.clone(),
traits_in_scope,
@ -731,7 +731,7 @@ fn iterate_method_candidates_with_autoref(
first_adjustment.with_autoref(Mutability::Mut),
deref_chain,
db,
env.clone(),
env,
traits_in_scope,
visible_from_module,
name,
@ -973,7 +973,7 @@ fn iterate_inherent_methods(
// already happens in `is_valid_candidate` above; if not, we
// check it here
if receiver_ty.is_none()
&& inherent_impl_substs(db, env.clone(), impl_def, &self_ty).is_none()
&& inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
{
cov_mark::hit!(impl_self_type_match_without_receiver);
continue;
@ -1105,7 +1105,7 @@ pub(crate) fn inherent_impl_substs(
// Unknown, and in that case we want the result to contain Unknown in those
// places again.
let suffix =
Substitution::from_iter(Interner, substs.iter(Interner).cloned().skip(self_ty_vars));
Substitution::from_iter(Interner, substs.iter(Interner).skip(self_ty_vars).cloned());
Some(fallback_bound_vars(suffix, self_ty_vars))
}
@ -1152,7 +1152,7 @@ pub fn implements_trait(
env: Arc<TraitEnvironment>,
trait_: TraitId,
) -> bool {
let goal = generic_implements_goal(db, env.clone(), trait_, &ty);
let goal = generic_implements_goal(db, env.clone(), trait_, ty);
let solution = db.trait_solve(env.krate, goal.cast(Interner));
solution.is_some()
@ -1164,7 +1164,7 @@ pub fn implements_trait_unique(
env: Arc<TraitEnvironment>,
trait_: TraitId,
) -> bool {
let goal = generic_implements_goal(db, env.clone(), trait_, &ty);
let goal = generic_implements_goal(db, env.clone(), trait_, ty);
let solution = db.trait_solve(env.krate, goal.cast(Interner));
matches!(solution, Some(crate::Solution::Unique(_)))

View file

@ -337,7 +337,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
(self_param.name().unwrap().syntax().text_range(), "self".to_string())
} else {
(node.value.text_range(), node.value.text().to_string().replace("\n", " "))
(node.value.text_range(), node.value.text().to_string().replace('\n', " "))
};
let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
format_to!(

View file

@ -128,6 +128,6 @@ mod unsafe_tls {
// type.
let static_p: &DebugContext<'static> =
unsafe { std::mem::transmute::<&DebugContext, &DebugContext<'static>>(&ctx) };
PROGRAM.set(static_p, || op())
PROGRAM.set(static_p, op)
}
}

View file

@ -79,7 +79,7 @@ pub(crate) fn annotations(
.map(|variant| {
variant.source(db).and_then(|node| name_range(db, node, file_id))
})
.filter_map(std::convert::identity)
.flatten()
.for_each(|range| {
annotations.push(Annotation {
range,
@ -170,10 +170,9 @@ pub(crate) fn resolve_annotation(db: &RootDatabase, mut annotation: Annotation)
result
.into_iter()
.flat_map(|res| res.references)
.map(|(file_id, access)| {
.flat_map(|(file_id, access)| {
access.into_iter().map(move |(range, _)| FileRange { file_id, range })
})
.flatten()
.collect()
});
}

View file

@ -283,7 +283,7 @@ fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
let final_node = delimiter_node
.next_sibling_or_token()
.and_then(|it| it.into_token())
.filter(|node| is_single_line_ws(node))
.filter(is_single_line_ws)
.unwrap_or(delimiter_node);
return Some(TextRange::new(node.text_range().start(), final_node.text_range().end()));

View file

@ -138,7 +138,7 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
collapse_ws(param_list.syntax(), &mut detail);
}
if let Some(ret_type) = it.ret_type() {
detail.push_str(" ");
detail.push(' ');
collapse_ws(ret_type.syntax(), &mut detail);
}

View file

@ -145,7 +145,7 @@ pub(crate) fn hover(
if result.is_none() {
// fallbacks, show keywords or types
let res = descended.iter().find_map(|token| render::keyword(sema, config, &token));
let res = descended.iter().find_map(|token| render::keyword(sema, config, token));
if let Some(res) = res {
return Some(RangeInfo::new(original_token.text_range(), res));
}

View file

@ -103,7 +103,7 @@ pub(super) fn try_expr(
let adts = inner_ty.as_adt().zip(body_ty.as_adt());
if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
let famous_defs = FamousDefs(sema, sema.scope(try_expr.syntax()).krate());
// special case for two options, there is no value in showing them
if let Some(option_enum) = famous_defs.core_option_Option() {
if inner == option_enum && body == option_enum {

View file

@ -47,7 +47,7 @@ pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: boo
//FIXME: like, real html escaping
fn html_escape(text: &str) -> String {
text.replace("<", "&lt;").replace(">", "&gt;")
text.replace('<', "&lt;").replace('>', "&gt;")
}
const STYLE: &str = "

View file

@ -78,7 +78,7 @@ pub(super) fn ra_fixture(
Some(())
}
const RUSTDOC_FENCE: &'static str = "```";
const RUSTDOC_FENCE: &str = "```";
/// Injection of syntax highlighting of doctests.
pub(super) fn doc_comment(

View file

@ -41,7 +41,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext) ->
let match_arm_list = match_expr.match_arm_list()?;
let target_range = ctx.sema.original_range(match_expr.syntax()).range;
if let None = cursor_at_trivial_match_arm_list(&ctx, &match_expr, &match_arm_list) {
if let None = cursor_at_trivial_match_arm_list(ctx, &match_expr, &match_arm_list) {
let arm_list_range = ctx.sema.original_range(match_arm_list.syntax()).range;
let cursor_in_range = arm_list_range.contains_range(ctx.selection_trimmed());
if cursor_in_range {

View file

@ -1448,7 +1448,7 @@ fn make_body(
.filter(|it| text_range.contains_range(it.text_range()))
.map(|it| match &it {
syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
rewrite_body_segment(ctx, &fun.params, &handler, &n),
rewrite_body_segment(ctx, &fun.params, &handler, n),
),
_ => it,
})
@ -1518,7 +1518,7 @@ fn make_body(
make::expr_path(make::path_from_text("ControlFlow::Continue")),
make::arg_list(iter::once(make::expr_unit())),
);
with_tail_expr(block, controlflow_continue.into())
with_tail_expr(block, controlflow_continue)
}
FlowHandler::IfOption { .. } => {
let none = make::expr_path(make::ext::ident_path("None"));

View file

@ -103,7 +103,7 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext) -> Option<(
//for change_visibility and usages for first point mentioned above in the process
let (usages_to_be_processed, record_fields) = module.get_usages_and_record_fields(ctx);
let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, &ctx);
let import_paths_to_be_removed = module.resolve_imports(curr_parent_module, ctx);
module.body_items = module.change_visibility(record_fields)?;
if module.body_items.len() == 0 {
return None;
@ -190,20 +190,18 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext) -> Option<(
}
if let Some(impl_) = impl_parent {
let node_to_be_removed;
// Remove complete impl block if it has only one child (as such it will be empty
// after deleting that child)
if impl_child_count == 1 {
node_to_be_removed = impl_.syntax()
let node_to_be_removed = if impl_child_count == 1 {
impl_.syntax()
} else {
//Remove selected node
node_to_be_removed = &node;
}
&node
};
builder.delete(node_to_be_removed.text_range());
// Remove preceding indentation from node
if let Some(range) = indent_range_before_given_node(&node_to_be_removed) {
if let Some(range) = indent_range_before_given_node(node_to_be_removed) {
builder.delete(range);
}
@ -267,7 +265,7 @@ impl Module {
match (item.syntax()) {
ast::Adt(it) => {
if let Some( nod ) = ctx.sema.to_def(&it) {
let node_def = Definition::Adt(nod.into());
let node_def = Definition::Adt(nod);
self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
//Enum Fields are not allowed to explicitly specify pub, it is implied
@ -301,25 +299,25 @@ impl Module {
},
ast::TypeAlias(it) => {
if let Some( nod ) = ctx.sema.to_def(&it) {
let node_def = Definition::TypeAlias(nod.into());
let node_def = Definition::TypeAlias(nod);
self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
}
},
ast::Const(it) => {
if let Some( nod ) = ctx.sema.to_def(&it) {
let node_def = Definition::Const(nod.into());
let node_def = Definition::Const(nod);
self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
}
},
ast::Static(it) => {
if let Some( nod ) = ctx.sema.to_def(&it) {
let node_def = Definition::Static(nod.into());
let node_def = Definition::Static(nod);
self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
}
},
ast::Fn(it) => {
if let Some( nod ) = ctx.sema.to_def(&it) {
let node_def = Definition::Function(nod.into());
let node_def = Definition::Function(nod);
self.expand_and_group_usages_file_wise(ctx, node_def, &mut refs);
}
},
@ -333,7 +331,7 @@ impl Module {
}
});
return (refs, adt_fields);
(refs, adt_fields)
}
fn expand_and_group_usages_file_wise(
@ -417,12 +415,9 @@ impl Module {
replacements.append(&mut impl_item_replacements);
record_field_parents.into_iter().for_each(|x| {
x.1.descendants().filter_map(|x| ast::RecordField::cast(x)).for_each(|desc| {
let is_record_field_present = record_fields
.clone()
.into_iter()
.find(|x| x.to_string() == desc.to_string())
.is_some();
x.1.descendants().filter_map(ast::RecordField::cast).for_each(|desc| {
let is_record_field_present =
record_fields.clone().into_iter().any(|x| x.to_string() == desc.to_string());
if is_record_field_present {
replacements.push((desc.visibility(), desc.syntax().clone()));
}
@ -520,7 +515,7 @@ impl Module {
let mut exists_inside_sel = false;
let mut exists_outside_sel = false;
usage_res.clone().into_iter().for_each(|x| {
let mut non_use_nodes_itr = (&x.1).into_iter().filter_map(|x| {
let mut non_use_nodes_itr = (&x.1).iter().filter_map(|x| {
if find_node_at_range::<ast::Use>(file.syntax(), x.range).is_none() {
let path_opt = find_node_at_range::<ast::Path>(file.syntax(), x.range);
return path_opt;
@ -531,15 +526,11 @@ impl Module {
if non_use_nodes_itr
.clone()
.find(|x| !selection_range.contains_range(x.syntax().text_range()))
.is_some()
.any(|x| !selection_range.contains_range(x.syntax().text_range()))
{
exists_outside_sel = true;
}
if non_use_nodes_itr
.find(|x| selection_range.contains_range(x.syntax().text_range()))
.is_some()
{
if non_use_nodes_itr.any(|x| selection_range.contains_range(x.syntax().text_range())) {
exists_inside_sel = true;
}
});
@ -556,14 +547,14 @@ impl Module {
let file_id = x.0;
let mut use_opt: Option<ast::Use> = None;
if file_id == curr_file_id {
(&x.1).into_iter().for_each(|x| {
(&x.1).iter().for_each(|x| {
let node_opt: Option<ast::Use> = find_node_at_range(file.syntax(), x.range);
if let Some(node) = node_opt {
use_opt = Some(node);
}
});
}
return use_opt;
use_opt
});
let mut use_tree_str_opt: Option<Vec<ast::Path>> = None;
@ -646,7 +637,7 @@ impl Module {
return Some(item);
}
return None;
None
}
fn process_use_stmt_for_import_resolve(
@ -700,7 +691,7 @@ fn does_source_exists_outside_sel_in_same_mod(
if let Some(ast_module) = &curr_parent_module {
if let Some(hir_module) = x.parent(ctx.db()) {
have_same_parent =
compare_hir_and_ast_module(&ast_module, hir_module, ctx).is_some();
compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some();
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
@ -722,14 +713,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Function(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -739,14 +728,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Adt(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -756,14 +743,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Variant(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -773,14 +758,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Const(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -790,14 +773,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Static(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -807,14 +788,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::Trait(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -824,14 +803,12 @@ fn does_source_exists_outside_sel_in_same_mod(
}
Definition::TypeAlias(x) => {
if let Some(source) = x.source(ctx.db()) {
let have_same_parent;
if let Some(ast_module) = &curr_parent_module {
have_same_parent =
compare_hir_and_ast_module(&ast_module, x.module(ctx.db()), ctx).is_some();
let have_same_parent = if let Some(ast_module) = &curr_parent_module {
compare_hir_and_ast_module(ast_module, x.module(ctx.db()), ctx).is_some()
} else {
let source_file_id = source.file_id.original_file(ctx.db());
have_same_parent = source_file_id == curr_file_id;
}
source_file_id == curr_file_id
};
if have_same_parent {
source_exists_outside_sel_in_same_mod =
@ -842,7 +819,7 @@ fn does_source_exists_outside_sel_in_same_mod(
_ => {}
}
return source_exists_outside_sel_in_same_mod;
source_exists_outside_sel_in_same_mod
}
fn get_replacements_for_visibilty_change(
@ -890,7 +867,7 @@ fn get_replacements_for_visibilty_change(
}
});
return (body_items, replacements, record_field_parents, impls);
(body_items, replacements, record_field_parents, impls)
}
fn get_use_tree_paths_from_path(
@ -943,15 +920,13 @@ fn compare_hir_and_ast_module(
return None;
}
return Some(());
Some(())
}
fn indent_range_before_given_node(node: &SyntaxNode) -> Option<TextRange> {
let x = node.siblings_with_tokens(syntax::Direction::Prev).find(|x| {
return x.kind() == WHITESPACE;
})?;
return Some(x.text_range());
node.siblings_with_tokens(syntax::Direction::Prev)
.find(|x| x.kind() == WHITESPACE)
.map(|x| x.text_range())
}
#[cfg(test)]

View file

@ -52,7 +52,7 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option
}
}
let reference_modifier = match get_receiver_type(&ctx, &to_extract) {
let reference_modifier = match get_receiver_type(ctx, &to_extract) {
Some(receiver_type) if receiver_type.is_mutable_reference() => "&mut ",
Some(receiver_type) if receiver_type.is_reference() => "&",
_ => "",

View file

@ -156,7 +156,7 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext)
}
None => {
let offset = strukt.syntax().text_range().end();
let snippet = format!("\n\n{}", impl_def.syntax().to_string());
let snippet = format!("\n\n{}", impl_def.syntax());
builder.insert(offset, snippet);
}
}

View file

@ -52,7 +52,7 @@ pub(crate) fn generate_documentation_template(
let parent_syntax = ast_func.syntax();
let text_range = parent_syntax.text_range();
let indent_level = IndentLevel::from_node(&parent_syntax);
let indent_level = IndentLevel::from_node(parent_syntax);
acc.add(
AssistId("generate_documentation_template", AssistKind::Generate),
@ -202,7 +202,7 @@ fn all_parent_mods_public(hir_func: &hir::Function, ctx: &AssistContext) -> bool
/// Returns the name of the current crate
fn crate_name(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
let krate = ctx.sema.scope(&ast_func.syntax()).module()?.krate();
let krate = ctx.sema.scope(ast_func.syntax()).module()?.krate();
Some(krate.display_name(ctx.db())?.to_string())
}
@ -338,7 +338,7 @@ fn function_call(
is_unsafe: bool,
) -> Option<String> {
let name = ast_func.name()?;
let arguments = arguments_from_params(&param_list);
let arguments = arguments_from_params(param_list);
let function_call = if param_list.self_param().is_some() {
format!("{}.{}({})", self_name?, name, arguments)
} else if let Some(implementation) = self_partial_type(ast_func) {

View file

@ -305,7 +305,7 @@ fn inline(
let body = fn_body.clone_for_update();
let usages_for_locals = |local| {
Definition::Local(local)
.usages(&sema)
.usages(sema)
.all()
.references
.remove(&function_def_file_id)
@ -369,12 +369,12 @@ fn inline(
// inline single use literals
[usage] if matches!(expr, ast::Expr::Literal(_)) => {
cov_mark::hit!(inline_call_inline_literal);
inline_direct(usage, &expr);
inline_direct(usage, expr);
}
// inline direct local arguments
[_, ..] if expr_as_name_ref(&expr).is_some() => {
[_, ..] if expr_as_name_ref(expr).is_some() => {
cov_mark::hit!(inline_call_inline_locals);
usages.into_iter().for_each(|usage| inline_direct(usage, &expr));
usages.iter().for_each(|usage| inline_direct(usage, expr));
}
// can't inline, emit a let statement
_ => {

View file

@ -40,7 +40,7 @@ pub(crate) fn merge_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option
}
let current_expr = current_arm.expr()?;
let current_text_range = current_arm.syntax().text_range();
let current_arm_types = get_arm_types(&ctx, &current_arm);
let current_arm_types = get_arm_types(ctx, &current_arm);
// We check if the following match arms match this one. We could, but don't,
// compare to the previous match arm as well.
@ -99,14 +99,11 @@ fn are_same_types(
arm: &ast::MatchArm,
ctx: &AssistContext,
) -> bool {
let arm_types = get_arm_types(&ctx, &arm);
let arm_types = get_arm_types(ctx, arm);
for (other_arm_type_name, other_arm_type) in arm_types {
match (current_arm_types.get(&other_arm_type_name), other_arm_type) {
(Some(Some(current_arm_type)), Some(other_arm_type))
if other_arm_type.original == current_arm_type.original =>
{
()
}
if other_arm_type.original == current_arm_type.original => {}
_ => return false,
}
}
@ -163,7 +160,7 @@ fn get_arm_types(
}
}
recurse(&mut mapping, &context, &arm.pat());
recurse(&mut mapping, context, &arm.pat());
mapping
}

View file

@ -57,7 +57,7 @@ fn remove_separators(acc: &mut Assists, literal: ast::IntNumber) -> Option<()> {
AssistId("reformat_number_literal", AssistKind::RefactorInline),
"Remove digit separators",
range,
|builder| builder.replace(range, literal.text().replace("_", "")),
|builder| builder.replace(range, literal.text().replace('_', "")),
)
}

View file

@ -44,7 +44,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext) -> Opt
let range = call.syntax().text_range();
let resolved_call = ctx.sema.resolve_method_call(&call)?;
let current_module = ctx.sema.scope(&call.syntax()).module()?;
let current_module = ctx.sema.scope(call.syntax()).module()?;
let target_module_def = ModuleDef::from(resolved_call);
let item_in_ns = ItemInNs::from(target_module_def);
let receiver_path = current_module

View file

@ -86,7 +86,7 @@ fn gen_clone_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
None => {
let pattern = make::path_pat(variant_name.clone());
let variant_expr = make::expr_path(variant_name);
arms.push(make::match_arm(Some(pattern.into()), None, variant_expr));
arms.push(make::match_arm(Some(pattern), None, variant_expr));
}
}
}
@ -117,7 +117,7 @@ fn gen_clone_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
let mut fields = vec![];
for (i, _) in field_list.fields().enumerate() {
let f_path = make::expr_path(make::ext::ident_path("self"));
let target = make::expr_field(f_path, &format!("{}", i)).into();
let target = make::expr_field(f_path, &format!("{}", i));
fields.push(gen_clone_call(target));
}
let struct_name = make::expr_path(make::ext::ident_path("Self"));
@ -151,7 +151,7 @@ fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
for variant in list.variants() {
let name = variant.name()?;
let variant_name = make::ext::path_from_idents(["Self", &format!("{}", name)])?;
let target = make::expr_path(make::ext::ident_path("f").into());
let target = make::expr_path(make::ext::ident_path("f"));
match variant.field_list() {
Some(ast::FieldList::RecordFieldList(list)) => {
@ -206,7 +206,7 @@ fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
// => <expr>.field(field)
let method_name = make::name_ref("field");
let field_path = &format!("{}", name);
let field_path = &name.to_string();
let field_path = make::expr_path(make::ext::ident_path(field_path));
let args = make::arg_list(vec![field_path]);
expr = make::expr_method_call(expr, method_name, args);
@ -227,11 +227,7 @@ fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
let macro_call = make::expr_macro_call(macro_name, args);
let variant_name = make::path_pat(variant_name);
arms.push(make::match_arm(
Some(variant_name.into()),
None,
macro_call.into(),
));
arms.push(make::match_arm(Some(variant_name), None, macro_call));
}
}
}
@ -264,7 +260,7 @@ fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
let f_path = make::expr_path(make::ext::ident_path("self"));
let f_path = make::expr_ref(f_path, false);
let f_path = make::expr_field(f_path, &format!("{}", name)).into();
let f_path = make::expr_field(f_path, &format!("{}", name));
let args = make::arg_list([f_name, f_path]);
expr = make::expr_method_call(expr, make::name_ref("field"), args);
}
@ -278,7 +274,7 @@ fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
for (i, _) in field_list.fields().enumerate() {
let f_path = make::expr_path(make::ext::ident_path("self"));
let f_path = make::expr_ref(f_path, false);
let f_path = make::expr_field(f_path, &format!("{}", i)).into();
let f_path = make::expr_field(f_path, &format!("{}", i));
let method = make::name_ref("field");
expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
}
@ -406,7 +402,7 @@ fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
}
fn gen_record_pat_field(field_name: &str, pat_name: &str) -> ast::RecordPatField {
let pat = make::ext::simple_ident_pat(make::name(&pat_name));
let pat = make::ext::simple_ident_pat(make::name(pat_name));
let name_ref = make::name_ref(field_name);
make::record_pat_field(name_ref, pat.into())
}
@ -455,10 +451,10 @@ fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
let field_name = field.name()?.to_string();
let l_name = &format!("l_{}", field_name);
l_fields.push(gen_record_pat_field(&field_name, &l_name));
l_fields.push(gen_record_pat_field(&field_name, l_name));
let r_name = &format!("r_{}", field_name);
r_fields.push(gen_record_pat_field(&field_name, &r_name));
r_fields.push(gen_record_pat_field(&field_name, r_name));
let lhs = make::expr_path(make::ext::ident_path(l_name));
let rhs = make::expr_path(make::ext::ident_path(r_name));

View file

@ -29,7 +29,7 @@ pub(crate) fn complete_cfg(acc: &mut Completions, ctx: &CompletionContext) {
Some("target_endian") => ["little", "big"].into_iter().for_each(add_completion),
Some(name) => {
if let Some(krate) = ctx.krate {
krate.potential_cfg(ctx.db).get_cfg_values(&name).cloned().for_each(|s| {
krate.potential_cfg(ctx.db).get_cfg_values(name).cloned().for_each(|s| {
let insert_text = format!(r#""{}""#, s);
let mut item =
CompletionItem::new(SymbolKind::BuiltinAttr, ctx.source_range(), s);

View file

@ -46,7 +46,6 @@ pub(crate) fn complete_derive(acc: &mut Completions, ctx: &CompletionContext) {
acc.add_resolution(ctx, name, def);
}
}
return;
}
None if is_absolute_path => acc.add_crate_roots(ctx),
// only show modules in a fresh UseTree

View file

@ -14,7 +14,7 @@ pub(super) fn complete_repr(acc: &mut Completions, ctx: &CompletionContext, inpu
ast::Expr::PathExpr(path) => path.path()?.as_single_name_ref(),
ast::Expr::CallExpr(call) => match call.expr()? {
ast::Expr::PathExpr(path) => path.path()?.as_single_name_ref(),
_ => return None,
_ => None,
},
_ => None,
})

View file

@ -31,7 +31,7 @@ pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
CompletionItem::new(CompletionItemKind::Binding, ctx.source_range(), label)
};
let mut item = match &comma_wrapper {
Some(fmt) => mk_item(&fmt(&label)),
Some(fmt) => mk_item(&fmt(label)),
None => mk_item(label),
};
item.lookup_by(lookup);
@ -40,7 +40,7 @@ pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
match param_kind {
ParamKind::Function(function) => {
fill_fn_params(ctx, function, &param_list, add_new_item_to_acc);
fill_fn_params(ctx, function, param_list, add_new_item_to_acc);
}
ParamKind::Closure(closure) => {
let stmt_list = closure.syntax().ancestors().find_map(ast::StmtList::cast)?;

View file

@ -51,7 +51,7 @@ pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
None => return,
};
let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, &dot_receiver) {
let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, dot_receiver) {
Some(it) => it,
None => return,
};
@ -265,7 +265,7 @@ fn add_custom_postfix_completions(
Some(imports) => imports,
None => return,
};
let body = snippet.postfix_snippet(&receiver_text);
let body = snippet.postfix_snippet(receiver_text);
let mut builder =
postfix_snippet(trigger, snippet.description.as_deref().unwrap_or_default(), &body);
builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));

View file

@ -74,7 +74,7 @@ pub(crate) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon
}
_ => {
// Add associated types on type parameters and `Self`.
ctx.scope.assoc_type_shorthand_candidates(&resolution, |_, alias| {
ctx.scope.assoc_type_shorthand_candidates(resolution, |_, alias| {
acc.add_type_alias(ctx, alias);
None::<()>
});

View file

@ -112,7 +112,7 @@ fn add_custom_completions(
None => return,
};
let body = snip.snippet();
let mut builder = snippet(ctx, cap, &trigger, &body);
let mut builder = snippet(ctx, cap, trigger, &body);
builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));
for import in imports.into_iter() {
builder.add_import(import);

View file

@ -150,9 +150,9 @@ impl IdentClass {
sema: &Semantics<RootDatabase>,
lifetime: &ast::Lifetime,
) -> Option<IdentClass> {
NameRefClass::classify_lifetime(sema, &lifetime)
NameRefClass::classify_lifetime(sema, lifetime)
.map(IdentClass::NameRefClass)
.or_else(|| NameClass::classify_lifetime(sema, &lifetime).map(IdentClass::NameClass))
.or_else(|| NameClass::classify_lifetime(sema, lifetime).map(IdentClass::NameClass))
}
pub fn definitions(self) -> ArrayVec<Definition, 2> {
@ -306,7 +306,7 @@ impl NameClass {
if let Some(it) = ast::LifetimeParam::cast(parent.clone()) {
sema.to_def(&it).map(Into::into).map(Definition::GenericParam)
} else if let Some(it) = ast::Label::cast(parent.clone()) {
} else if let Some(it) = ast::Label::cast(parent) {
sema.to_def(&it).map(Definition::Label)
} else {
None

View file

@ -108,7 +108,7 @@ impl FamousDefs<'_, '_> {
self.test(),
self.proc_macro(),
])
.filter_map(|it| it)
.flatten()
}
fn find_trait(&self, path: &str) -> Option<Trait> {

View file

@ -3,7 +3,7 @@
use std::collections::VecDeque;
use base_db::FileId;
use hir::{ItemInNs, Macro, ModuleDef, Name, Semantics};
use hir::{ItemInNs, ModuleDef, Name, Semantics};
use syntax::{
ast::{self, make},
AstToken, SyntaxKind, SyntaxToken, TokenAtOffset,
@ -13,9 +13,9 @@ use crate::{defs::Definition, generated, RootDatabase};
pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
match item {
ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
ItemInNs::Macros(macro_def_id) => Some(Macro::from(macro_def_id).name(db)),
ItemInNs::Types(module_def_id) => module_def_id.name(db),
ItemInNs::Values(module_def_id) => module_def_id.name(db),
ItemInNs::Macros(macro_def_id) => Some(macro_def_id.name(db)),
}
}

View file

@ -430,8 +430,8 @@ fn module_with_segment_name(
candidate: ItemInNs,
) -> Option<Module> {
let mut current_module = match candidate {
ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).module(db),
ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).module(db),
ItemInNs::Types(module_def_id) => module_def_id.module(db),
ItemInNs::Values(module_def_id) => module_def_id.module(db),
ItemInNs::Macros(macro_def_id) => ModuleDef::from(macro_def_id).module(db),
};
while let Some(module) = current_module {

View file

@ -75,7 +75,7 @@ fn try_merge_trees_mut(lhs: &ast::UseTree, rhs: &ast::UseTree, merge: MergeBehav
lhs.split_prefix(&lhs_prefix);
rhs.split_prefix(&rhs_prefix);
}
recursive_merge(&lhs, &rhs, merge)
recursive_merge(lhs, rhs, merge)
}
/// Recursively merges rhs to lhs
@ -157,7 +157,7 @@ fn recursive_merge(lhs: &ast::UseTree, rhs: &ast::UseTree, merge: MergeBehavior)
}
lhs_t.split_prefix(&lhs_prefix);
rhs_t.split_prefix(&rhs_prefix);
recursive_merge(&lhs_t, &rhs_t, merge)?;
recursive_merge(lhs_t, &rhs_t, merge)?;
}
Err(_)
if merge == MergeBehavior::Module

View file

@ -115,7 +115,7 @@ fn find_items<'a>(
});
// Query the local crate using the symbol index.
let local_results = symbol_index::crate_symbols(db, krate.into(), local_query)
let local_results = symbol_index::crate_symbols(db, krate, local_query)
.into_iter()
.filter_map(move |local_candidate| get_name_definition(sema, &local_candidate))
.filter_map(|name_definition_to_import| match name_definition_to_import {

View file

@ -120,8 +120,7 @@ fn library_symbols(db: &dyn SymbolsDatabase, source_root_id: SourceRootId) -> Ar
// we specifically avoid calling SymbolsDatabase::module_symbols here, even they do the same thing,
// as the index for a library is not going to really ever change, and we do not want to store each
// module's index in salsa.
.map(|module| SymbolCollector::collect(db.upcast(), module))
.flatten()
.flat_map(|module| SymbolCollector::collect(db.upcast(), module))
.collect();
Arc::new(SymbolIndex::new(symbols))

View file

@ -69,7 +69,7 @@ pub fn insert_ws_into(syn: SyntaxNode) -> SyntaxNode {
if indent > 0 {
mods.push(do_indent(after, tok, indent));
}
mods.push(do_nl(after, &tok));
mods.push(do_nl(after, tok));
}
R_CURLY if is_last(|it| it != L_CURLY, true) => {
indent = indent.saturating_sub(1);
@ -85,7 +85,7 @@ pub fn insert_ws_into(syn: SyntaxNode) -> SyntaxNode {
}
mods.push(do_nl(after, tok));
}
LIFETIME_IDENT if is_next(|it| is_text(it), true) => {
LIFETIME_IDENT if is_next(is_text, true) => {
mods.push(do_ws(after, tok));
}
AS_KW | DYN_KW | IMPL_KW => {

View file

@ -75,7 +75,7 @@ fn generate_lint_descriptor(buf: &mut String) {
format!("lint group for: {}", lints.trim()).into(),
lints
.split_ascii_whitespace()
.map(|s| s.trim().trim_matches(',').replace("-", "_"))
.map(|s| s.trim().trim_matches(',').replace('-', "_"))
.collect(),
)
});
@ -85,7 +85,7 @@ fn generate_lint_descriptor(buf: &mut String) {
.sorted_by(|(ident, ..), (ident2, ..)| ident.cmp(ident2))
.collect::<Vec<_>>();
for (name, description, ..) in &lints {
push_lint_completion(buf, &name.replace("-", "_"), &description);
push_lint_completion(buf, &name.replace('-', "_"), description);
}
buf.push_str("];\n");
buf.push_str(r#"pub const DEFAULT_LINT_GROUPS: &[LintGroup] = &["#);
@ -93,10 +93,10 @@ fn generate_lint_descriptor(buf: &mut String) {
if !children.is_empty() {
// HACK: warnings is emitted with a general description, not with its members
if name == &"warnings" {
push_lint_group(buf, &name, &description, &Vec::new());
push_lint_group(buf, name, description, &Vec::new());
continue;
}
push_lint_group(buf, &name.replace("-", "_"), &description, children);
push_lint_group(buf, &name.replace('-', "_"), description, children);
}
}
buf.push('\n');
@ -124,7 +124,7 @@ fn generate_lint_descriptor(buf: &mut String) {
format!("lint group for: {}", lints.trim()).into(),
lints
.split_ascii_whitespace()
.map(|s| s.trim().trim_matches(',').replace("-", "_"))
.map(|s| s.trim().trim_matches(',').replace('-', "_"))
.collect(),
)
},
@ -136,14 +136,14 @@ fn generate_lint_descriptor(buf: &mut String) {
.collect::<Vec<_>>();
for (name, description, ..) in &lints_rustdoc {
push_lint_completion(buf, &name.replace("-", "_"), &description)
push_lint_completion(buf, &name.replace('-', "_"), description)
}
buf.push_str("];\n");
buf.push_str(r#"pub const RUSTDOC_LINT_GROUPS: &[LintGroup] = &["#);
for (name, description, children) in &lints_rustdoc {
if !children.is_empty() {
push_lint_group(buf, &name.replace("-", "_"), &description, children);
push_lint_group(buf, &name.replace('-', "_"), description, children);
}
}
buf.push('\n');
@ -159,7 +159,7 @@ fn generate_feature_descriptor(buf: &mut String, src_dir: &Path) {
path.extension().unwrap_or_default().to_str().unwrap_or_default() == "md"
})
.map(|path| {
let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_");
let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace('-', "_");
let doc = fs::read_to_string(path).unwrap();
(feature_ident, doc)
})

View file

@ -117,12 +117,7 @@ fn make_fixes(
}
// If there are existing `mod m;` items, append after them (after the first group of them, rather).
match ast
.items()
.skip_while(|item| !is_outline_mod(item))
.take_while(|item| is_outline_mod(item))
.last()
{
match ast.items().skip_while(|item| !is_outline_mod(item)).take_while(is_outline_mod).last() {
Some(last) => {
cov_mark::hit!(unlinked_file_append_to_existing_mods);
let offset = last.syntax().text_range().end();

View file

@ -170,9 +170,9 @@ fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
Some(it) => it,
None => break,
};
let synth_id = token.synthetic_id(&conv);
let synth_id = token.synthetic_id(conv);
let kind = token.kind(&conv);
let kind = token.kind(conv);
if kind == COMMENT {
if let Some(tokens) = conv.convert_doc_comment(&token) {
// FIXME: There has to be a better way to do this
@ -227,7 +227,7 @@ fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
continue;
}
let spacing = match conv.peek().map(|next| next.kind(&conv)) {
let spacing = match conv.peek().map(|next| next.kind(conv)) {
Some(kind)
if !kind.is_trivia()
&& kind.is_punct()
@ -240,7 +240,7 @@ fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
}
_ => tt::Spacing::Alone,
};
let char = match token.to_char(&conv) {
let char = match token.to_char(conv) {
Some(c) => c,
None => {
panic!("Token from lexer must be single char: token = {:#?}", token);

View file

@ -74,14 +74,11 @@ pub trait Message: Serialize + DeserializeOwned {
impl Message for Request {}
impl Message for Response {}
fn read_json<'a>(
inp: &mut impl BufRead,
mut buf: &'a mut String,
) -> io::Result<Option<&'a String>> {
fn read_json<'a>(inp: &mut impl BufRead, buf: &'a mut String) -> io::Result<Option<&'a String>> {
loop {
buf.clear();
inp.read_line(&mut buf)?;
inp.read_line(buf)?;
buf.pop(); // Remove trailing '\n'
if buf.is_empty() {

View file

@ -121,7 +121,7 @@ impl ProcMacroLibraryLibloading {
let abs_file: &AbsPath = file.try_into().map_err(|_| {
invalid_data_err(format!("expected an absolute path, got {}", file.display()))
})?;
let version_info = read_dylib_info(&abs_file)?;
let version_info = read_dylib_info(abs_file)?;
let lib = load_library(file).map_err(invalid_data_err)?;
let abi = Abi::from_lib(&lib, symbol_name, version_info)?;

View file

@ -1238,7 +1238,7 @@ fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json:
let map = fields
.iter()
.map(|(field, ty, doc, default)| {
let name = field.replace("_", ".");
let name = field.replace('_', ".");
let name = format!("rust-analyzer.{}", name);
let props = field_props(field, ty, doc, default);
(name, props)
@ -1385,7 +1385,7 @@ fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
fields
.iter()
.map(|(field, _ty, doc, default)| {
let name = format!("rust-analyzer.{}", field.replace("_", "."));
let name = format!("rust-analyzer.{}", field.replace('_', "."));
let doc = doc_comment_to_string(*doc);
if default.contains('\n') {
format!(
@ -1428,7 +1428,7 @@ mod tests {
.trim_start_matches('{')
.trim_end_matches('}')
.replace(" ", " ")
.replace("\n", "\n ")
.replace('\n', "\n ")
.trim_start_matches('\n')
.trim_end()
.to_string();

View file

@ -24,7 +24,7 @@ fn diagnostic_severity(
// HACK: special case for `warnings` rustc lint.
Some(code)
if config.warnings_as_hint.iter().any(|lint| {
lint == "warnings" || ide_db::helpers::lint_eq_or_in_group(&code.code, &lint)
lint == "warnings" || ide_db::helpers::lint_eq_or_in_group(&code.code, lint)
}) =>
{
lsp_types::DiagnosticSeverity::HINT
@ -32,7 +32,7 @@ fn diagnostic_severity(
// HACK: special case for `warnings` rustc lint.
Some(code)
if config.warnings_as_info.iter().any(|lint| {
lint == "warnings" || ide_db::helpers::lint_eq_or_in_group(&code.code, &lint)
lint == "warnings" || ide_db::helpers::lint_eq_or_in_group(&code.code, lint)
}) =>
{
lsp_types::DiagnosticSeverity::INFORMATION

View file

@ -48,7 +48,7 @@ impl<'a> RequestDispatcher<'a> {
};
let _pctx = stdx::panic_context::enter(panic_context);
let result = f(&mut self.global_state, params);
let result = f(self.global_state, params);
let response = result_to_response::<R>(id, result);
self.global_state.respond(response);

View file

@ -532,7 +532,7 @@ pub(crate) fn handle_will_rename_files(
let mut source_change = source_changes.next().unwrap_or_default();
source_change.file_system_edits.clear();
// no collect here because we want to merge text edits on same file ids
source_change.extend(source_changes.map(|it| it.source_file_edits).flatten());
source_change.extend(source_changes.flat_map(|it| it.source_file_edits));
if source_change.source_file_edits.is_empty() {
Ok(None)
} else {

View file

@ -167,7 +167,7 @@ impl GlobalState {
self.handle_event(event)?
}
return Err("client exited without proper shutdown sequence".into());
Err("client exited without proper shutdown sequence".into())
}
fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {

View file

@ -533,7 +533,7 @@ mod bar;
fn main() {{}}
"#,
PROJECT = project.to_string(),
PROJECT = project,
);
let server =
@ -972,7 +972,7 @@ fn main() {}
"documentChanges": [
{
"textDocument": {
"uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace("\\", "/")),
"uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace('\\', "/")),
"version": null
},
"edits": [
@ -1029,7 +1029,7 @@ fn main() {}
"documentChanges": [
{
"textDocument": {
"uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace("\\", "/")),
"uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace('\\', "/")),
"version": null
},
"edits": [

View file

@ -374,8 +374,8 @@ fn lines_match(expected: &str, actual: &str) -> bool {
// Let's not deal with / vs \ (windows...)
// First replace backslash-escaped backslashes with forward slashes
// which can occur in, for example, JSON output
let expected = expected.replace(r"\\", "/").replace(r"\", "/");
let mut actual: &str = &actual.replace(r"\\", "/").replace(r"\", "/");
let expected = expected.replace(r"\\", "/").replace('\\', "/");
let mut actual: &str = &actual.replace(r"\\", "/").replace('\\', "/");
for (i, part) in expected.split("[..]").enumerate() {
match actual.find(part) {
Some(j) => {

View file

@ -392,10 +392,8 @@ impl AstNode for CallableExpr {
{
if let Some(it) = ast::CallExpr::cast(syntax.clone()) {
Some(Self::Call(it))
} else if let Some(it) = ast::MethodCallExpr::cast(syntax) {
Some(Self::MethodCall(it))
} else {
None
ast::MethodCallExpr::cast(syntax).map(Self::MethodCall)
}
}

View file

@ -49,7 +49,7 @@ pub mod ext {
) -> Option<ast::Expr> {
let mut iter = parts.into_iter();
let base = expr_path(ext::ident_path(iter.next()?));
let expr = iter.fold(base, |base, s| expr_field(base, s));
let expr = iter.fold(base, expr_field);
Some(expr)
}

View file

@ -307,7 +307,7 @@ impl ast::IntNumber {
pub fn value(&self) -> Option<u128> {
let (_, text, _) = self.split_into_parts();
let value = u128::from_str_radix(&text.replace("_", ""), self.radix() as u32).ok()?;
let value = u128::from_str_radix(&text.replace('_', ""), self.radix() as u32).ok()?;
Some(value)
}

View file

@ -94,14 +94,14 @@ impl TextEdit {
let text_size = TextSize::of(&*text);
let mut total_len = text_size;
let mut max_total_len = text_size.clone();
let mut max_total_len = text_size;
for indel in &self.indels {
total_len += TextSize::of(&indel.insert);
total_len -= indel.delete.len();
max_total_len = max(max_total_len, total_len);
}
if let Some(additional) = max_total_len.checked_sub(text_size.into()) {
if let Some(additional) = max_total_len.checked_sub(text_size) {
text.reserve(additional.into());
}