remove needless borrows

This commit is contained in:
Daniel Eades 2022-12-30 08:05:03 +00:00
parent 77051679d7
commit ed128872eb
53 changed files with 87 additions and 87 deletions

View File

@ -542,7 +542,7 @@ impl<'a> AssocItemCollector<'a> {
if !attrs.is_cfg_enabled(self.expander.cfg_options()) { if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
self.inactive_diagnostics.push(DefDiagnostic::unconfigured_code( self.inactive_diagnostics.push(DefDiagnostic::unconfigured_code(
self.module_id.local_id, self.module_id.local_id,
InFile::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast()), InFile::new(self.expander.current_file_id(), item.ast_id(item_tree).upcast()),
attrs.cfg().unwrap(), attrs.cfg().unwrap(),
self.expander.cfg_options().clone(), self.expander.cfg_options().clone(),
)); ));
@ -551,7 +551,7 @@ impl<'a> AssocItemCollector<'a> {
'attrs: for attr in &*attrs { 'attrs: for attr in &*attrs {
let ast_id = let ast_id =
AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast()); AstId::new(self.expander.current_file_id(), item.ast_id(item_tree).upcast());
let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id }; let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro( if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(

View File

@ -176,7 +176,7 @@ fn find_path_for_module(
// - if relative paths are fine, check if we are searching for a parent // - if relative paths are fine, check if we are searching for a parent
if prefixed.filter(PrefixKind::is_absolute).is_none() { if prefixed.filter(PrefixKind::is_absolute).is_none() {
if let modpath @ Some(_) = find_self_super(&def_map, module_id, from) { if let modpath @ Some(_) = find_self_super(def_map, module_id, from) {
return modpath; return modpath;
} }
} }

View File

@ -1094,7 +1094,7 @@ impl DefCollector<'_> {
ast_id, ast_id,
*expand_to, *expand_to,
self.def_map.krate, self.def_map.krate,
&resolver_def_id, resolver_def_id,
&mut |_err| (), &mut |_err| (),
); );
if let Ok(Ok(call_id)) = call_id { if let Ok(Ok(call_id)) = call_id {
@ -1110,7 +1110,7 @@ impl DefCollector<'_> {
*derive_attr, *derive_attr,
*derive_pos as u32, *derive_pos as u32,
self.def_map.krate, self.def_map.krate,
&resolver, resolver,
); );
if let Ok((macro_id, def_id, call_id)) = id { if let Ok((macro_id, def_id, call_id)) = id {

View File

@ -115,7 +115,8 @@ pub fn pseudo_derive_attr_expansion(
}; };
let mut token_trees = Vec::new(); let mut token_trees = Vec::new();
for tt in (&args.token_trees) for tt in args
.token_trees
.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', .. })))) .split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', .. }))))
{ {
token_trees.push(mk_leaf('#')); token_trees.push(mk_leaf('#'));

View File

@ -62,7 +62,7 @@ impl<'a> UnescapedName<'a> {
it.clone() it.clone()
} }
} }
Repr::TupleField(it) => SmolStr::new(&it.to_string()), Repr::TupleField(it) => SmolStr::new(it.to_string()),
} }
} }
} }
@ -139,7 +139,7 @@ impl Name {
pub fn to_smol_str(&self) -> SmolStr { pub fn to_smol_str(&self) -> SmolStr {
match &self.0 { match &self.0 {
Repr::Text(it) => it.clone(), Repr::Text(it) => it.clone(),
Repr::TupleField(it) => SmolStr::new(&it.to_string()), Repr::TupleField(it) => SmolStr::new(it.to_string()),
} }
} }

View File

@ -404,7 +404,7 @@ pub(crate) fn path_to_const(
args_lazy: impl FnOnce() -> Generics, args_lazy: impl FnOnce() -> Generics,
debruijn: DebruijnIndex, debruijn: DebruijnIndex,
) -> Option<Const> { ) -> Option<Const> {
match resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) { match resolver.resolve_path_in_value_ns_fully(db.upcast(), path) {
Some(ValueNs::GenericParam(p)) => { Some(ValueNs::GenericParam(p)) => {
let ty = db.const_param_ty(p); let ty = db.const_param_ty(p);
let args = args_lazy(); let args = args_lazy();

View File

@ -1335,7 +1335,7 @@ impl<'a> InferenceContext<'a> {
ty, ty,
c, c,
ParamLoweringMode::Placeholder, ParamLoweringMode::Placeholder,
|| generics(this.db.upcast(), (&this.resolver).generic_def().unwrap()), || generics(this.db.upcast(), this.resolver.generic_def().unwrap()),
DebruijnIndex::INNERMOST, DebruijnIndex::INNERMOST,
) )
}, },

View File

@ -153,7 +153,7 @@ impl<'a> InferenceContext<'a> {
) -> Ty { ) -> Ty {
let mut expected = self.resolve_ty_shallow(expected); let mut expected = self.resolve_ty_shallow(expected);
if is_non_ref_pat(&self.body, pat) { if is_non_ref_pat(self.body, pat) {
let mut pat_adjustments = Vec::new(); let mut pat_adjustments = Vec::new();
while let Some((inner, _lifetime, mutability)) = expected.as_reference() { while let Some((inner, _lifetime, mutability)) = expected.as_reference() {
pat_adjustments.push(expected.clone()); pat_adjustments.push(expected.clone());

View File

@ -241,7 +241,7 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty, krate: CrateId) -> Result<Lay
fn layout_of_unit(cx: &LayoutCx<'_>, dl: &TargetDataLayout) -> Result<Layout, LayoutError> { fn layout_of_unit(cx: &LayoutCx<'_>, dl: &TargetDataLayout) -> Result<Layout, LayoutError> {
cx.univariant::<RustcEnumVariantIdx, &&Layout>( cx.univariant::<RustcEnumVariantIdx, &&Layout>(
&dl, dl,
&[], &[],
&ReprOptions::default(), &ReprOptions::default(),
StructKind::AlwaysSized, StructKind::AlwaysSized,

View File

@ -12,8 +12,7 @@ use super::layout_of_ty;
fn eval_goal(ra_fixture: &str, minicore: &str) -> Result<Layout, LayoutError> { fn eval_goal(ra_fixture: &str, minicore: &str) -> Result<Layout, LayoutError> {
// using unstable cargo features failed, fall back to using plain rustc // using unstable cargo features failed, fall back to using plain rustc
let mut cmd = std::process::Command::new("rustc"); let mut cmd = std::process::Command::new("rustc");
cmd.args(&["-Z", "unstable-options", "--print", "target-spec-json"]) cmd.args(["-Z", "unstable-options", "--print", "target-spec-json"]).env("RUSTC_BOOTSTRAP", "1");
.env("RUSTC_BOOTSTRAP", "1");
let output = cmd.output().unwrap(); let output = cmd.output().unwrap();
assert!(output.status.success(), "{}", output.status); assert!(output.status.success(), "{}", output.status);
let stdout = String::from_utf8(output.stdout).unwrap(); let stdout = String::from_utf8(output.stdout).unwrap();

View File

@ -780,7 +780,7 @@ impl<'a> TyLoweringContext<'a> {
|_, c, ty| { |_, c, ty| {
const_or_path_to_chalk( const_or_path_to_chalk(
self.db, self.db,
&self.resolver, self.resolver,
ty, ty,
c, c,
self.type_param_mode, self.type_param_mode,
@ -1852,7 +1852,7 @@ pub(crate) fn return_type_impl_traits(
let ctx_ret = TyLoweringContext::new(db, &resolver) let ctx_ret = TyLoweringContext::new(db, &resolver)
.with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
.with_type_param_mode(ParamLoweringMode::Variable); .with_type_param_mode(ParamLoweringMode::Variable);
let _ret = (&ctx_ret).lower_ty(&data.ret_type); let _ret = ctx_ret.lower_ty(&data.ret_type);
let generics = generics(db.upcast(), def.into()); let generics = generics(db.upcast(), def.into());
let return_type_impl_traits = let return_type_impl_traits =
ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() }; ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };

View File

@ -926,7 +926,7 @@ fn iterate_method_candidates_by_receiver(
while let Some((self_ty, _)) = autoderef.next() { while let Some((self_ty, _)) = autoderef.next() {
iterate_inherent_methods( iterate_inherent_methods(
&self_ty, &self_ty,
&mut autoderef.table, autoderef.table,
name, name,
Some(&receiver_ty), Some(&receiver_ty),
Some(receiver_adjustments.clone()), Some(receiver_adjustments.clone()),
@ -941,7 +941,7 @@ fn iterate_method_candidates_by_receiver(
while let Some((self_ty, _)) = autoderef.next() { while let Some((self_ty, _)) = autoderef.next() {
iterate_trait_method_candidates( iterate_trait_method_candidates(
&self_ty, &self_ty,
&mut autoderef.table, autoderef.table,
traits_in_scope, traits_in_scope,
name, name,
Some(&receiver_ty), Some(&receiver_ty),
@ -1246,7 +1246,7 @@ fn is_valid_candidate(
let expected_self_ty = TyBuilder::impl_self_ty(db, impl_id) let expected_self_ty = TyBuilder::impl_self_ty(db, impl_id)
.fill_with_inference_vars(table) .fill_with_inference_vars(table)
.build(); .build();
table.unify(&expected_self_ty, &self_ty) table.unify(&expected_self_ty, self_ty)
}); });
if !self_ty_matches { if !self_ty_matches {
cov_mark::hit!(const_candidate_self_type_mismatch); cov_mark::hit!(const_candidate_self_type_mismatch);

View File

@ -1252,7 +1252,7 @@ impl<'db> SemanticsImpl<'db> {
fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> { fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
let src = self.find_file(src.syntax()).with_value(src).cloned(); let src = self.find_file(src.syntax()).with_value(src).cloned();
T::to_def(&self, src) T::to_def(self, src)
} }
fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> { fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {

View File

@ -228,7 +228,7 @@ impl SourceAnalyzer {
db: &dyn HirDatabase, db: &dyn HirDatabase,
pat: &ast::Pat, pat: &ast::Pat,
) -> Option<SmallVec<[Type; 1]>> { ) -> Option<SmallVec<[Type; 1]>> {
let pat_id = self.pat_id(&pat)?; let pat_id = self.pat_id(pat)?;
let infer = self.infer.as_ref()?; let infer = self.infer.as_ref()?;
Some( Some(
infer infer
@ -824,7 +824,7 @@ impl SourceAnalyzer {
} }
fn ty_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<&Ty> { fn ty_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<&Ty> {
self.infer.as_ref()?.type_of_expr.get(self.expr_id(db, &expr)?) self.infer.as_ref()?.type_of_expr.get(self.expr_id(db, expr)?)
} }
} }

View File

@ -35,16 +35,16 @@ pub(crate) fn add_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opt
match builder_edit_pos { match builder_edit_pos {
InsertOrReplace::Insert(insert_pos, needs_whitespace) => { InsertOrReplace::Insert(insert_pos, needs_whitespace) => {
let preceeding_whitespace = if needs_whitespace { " " } else { "" }; let preceeding_whitespace = if needs_whitespace { " " } else { "" };
builder.insert(insert_pos, &format!("{preceeding_whitespace}-> {ty} ")) builder.insert(insert_pos, format!("{preceeding_whitespace}-> {ty} "))
} }
InsertOrReplace::Replace(text_range) => { InsertOrReplace::Replace(text_range) => {
builder.replace(text_range, &format!("-> {ty}")) builder.replace(text_range, format!("-> {ty}"))
} }
} }
if let FnType::Closure { wrap_expr: true } = fn_type { if let FnType::Closure { wrap_expr: true } = fn_type {
cov_mark::hit!(wrap_closure_non_block_expr); cov_mark::hit!(wrap_closure_non_block_expr);
// `|x| x` becomes `|x| -> T x` which is invalid, so wrap it in a block // `|x| x` becomes `|x| -> T x` which is invalid, so wrap it in a block
builder.replace(tail_expr.syntax().text_range(), &format!("{{{tail_expr}}}")); builder.replace(tail_expr.syntax().text_range(), format!("{{{tail_expr}}}"));
} }
}, },
) )

View File

@ -203,7 +203,7 @@ fn relevance_score(
// get the distance between the imported path and the current module // get the distance between the imported path and the current module
// (prefer items that are more local) // (prefer items that are more local)
Some((item_module, current_module)) => { Some((item_module, current_module)) => {
score -= module_distance_hueristic(db, &current_module, &item_module) as i32; score -= module_distance_hueristic(db, current_module, &item_module) as i32;
} }
// could not find relevant modules, so just use the length of the path as an estimate // could not find relevant modules, so just use the length of the path as an estimate

View File

@ -180,7 +180,7 @@ fn make_tuple_field_list(
) -> Option<ast::FieldList> { ) -> Option<ast::FieldList> {
let args = call_expr.arg_list()?.args(); let args = call_expr.arg_list()?.args();
let tuple_fields = args.map(|arg| { let tuple_fields = args.map(|arg| {
let ty = expr_ty(ctx, arg, &scope).unwrap_or_else(make::ty_placeholder); let ty = expr_ty(ctx, arg, scope).unwrap_or_else(make::ty_placeholder);
make::tuple_field(None, ty) make::tuple_field(None, ty)
}); });
Some(make::tuple_field_list(tuple_fields).into()) Some(make::tuple_field_list(tuple_fields).into())

View File

@ -176,7 +176,7 @@ pub(crate) fn generate_getter_impl(
// for separating it from other assoc items, that needs // for separating it from other assoc items, that needs
// to be handled spearately // to be handled spearately
let mut getter_buf = let mut getter_buf =
generate_getter_from_info(ctx, &getter_info, &record_field_info); generate_getter_from_info(ctx, &getter_info, record_field_info);
// Insert `$0` only for last getter we generate // Insert `$0` only for last getter we generate
if i == record_fields_count - 1 { if i == record_fields_count - 1 {

View File

@ -70,7 +70,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
)?; )?;
let expr = use_trivial_constructor( let expr = use_trivial_constructor(
&ctx.sema.db, ctx.sema.db,
ide_db::helpers::mod_path_to_ast(&type_path), ide_db::helpers::mod_path_to_ast(&type_path),
&ty, &ty,
)?; )?;

View File

@ -138,7 +138,7 @@ pub(crate) fn inline_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
replacement = Replacement::Plain; replacement = Replacement::Plain;
} }
_ => { _ => {
let alias = get_type_alias(&ctx, &alias_instance)?; let alias = get_type_alias(ctx, &alias_instance)?;
concrete_type = alias.ty()?; concrete_type = alias.ty()?;
replacement = inline(&alias, &alias_instance)?; replacement = inline(&alias, &alias_instance)?;
} }
@ -158,7 +158,7 @@ impl Replacement {
fn to_text(&self, concrete_type: &ast::Type) -> String { fn to_text(&self, concrete_type: &ast::Type) -> String {
match self { match self {
Replacement::Generic { lifetime_map, const_and_type_map } => { Replacement::Generic { lifetime_map, const_and_type_map } => {
create_replacement(&lifetime_map, &const_and_type_map, &concrete_type) create_replacement(lifetime_map, const_and_type_map, concrete_type)
} }
Replacement::Plain => concrete_type.to_string(), Replacement::Plain => concrete_type.to_string(),
} }
@ -240,7 +240,7 @@ impl ConstAndTypeMap {
) -> Option<Self> { ) -> Option<Self> {
let mut inner = HashMap::new(); let mut inner = HashMap::new();
let instance_generics = generic_args_to_const_and_type_generics(instance_args); let instance_generics = generic_args_to_const_and_type_generics(instance_args);
let alias_generics = generic_param_list_to_const_and_type_generics(&alias_generics); let alias_generics = generic_param_list_to_const_and_type_generics(alias_generics);
if instance_generics.len() > alias_generics.len() { if instance_generics.len() > alias_generics.len() {
cov_mark::hit!(too_many_generic_args); cov_mark::hit!(too_many_generic_args);

View File

@ -107,7 +107,7 @@ fn find_all_references(
/// If no await expression is found, returns None. /// If no await expression is found, returns None.
fn find_await_expression(ctx: &AssistContext<'_>, nameref: &NameRef) -> Option<ast::AwaitExpr> { fn find_await_expression(ctx: &AssistContext<'_>, nameref: &NameRef) -> Option<ast::AwaitExpr> {
// From the nameref, walk up the tree to the await expression. // From the nameref, walk up the tree to the await expression.
let await_expr = if let Some(path) = full_path_of_name_ref(&nameref) { let await_expr = if let Some(path) = full_path_of_name_ref(nameref) {
// Function calls. // Function calls.
path.syntax() path.syntax()
.parent() .parent()

View File

@ -32,12 +32,12 @@ pub(crate) fn complete_dot(
complete_fields( complete_fields(
acc, acc,
ctx, ctx,
&receiver_ty, receiver_ty,
|acc, field, ty| acc.add_field(ctx, dot_access, None, field, &ty), |acc, field, ty| acc.add_field(ctx, dot_access, None, field, &ty),
|acc, field, ty| acc.add_tuple_field(ctx, None, field, &ty), |acc, field, ty| acc.add_tuple_field(ctx, None, field, &ty),
); );
} }
complete_methods(ctx, &receiver_ty, |func| acc.add_method(ctx, dot_access, func, None, None)); complete_methods(ctx, receiver_ty, |func| acc.add_method(ctx, dot_access, func, None, None));
} }
pub(crate) fn complete_undotted_self( pub(crate) fn complete_undotted_self(

View File

@ -64,7 +64,7 @@ pub(crate) fn complete_expr_path(
acc.add_enum_variants(ctx, path_ctx, e); acc.add_enum_variants(ctx, path_ctx, e);
} }
ctx.iterate_path_candidates(&ty, |item| { ctx.iterate_path_candidates(ty, |item| {
add_assoc_item(acc, item); add_assoc_item(acc, item);
}); });

View File

@ -13,7 +13,7 @@ pub(crate) fn format_string(
original: &ast::String, original: &ast::String,
expanded: &ast::String, expanded: &ast::String,
) { ) {
if !is_format_string(&expanded) { if !is_format_string(expanded) {
return; return;
} }
let cursor = ctx.position.offset; let cursor = ctx.position.offset;

View File

@ -58,7 +58,7 @@ pub(crate) fn complete_type_path(
trait_.items(ctx.sema.db).into_iter().for_each(|item| add_assoc_item(acc, item)) trait_.items(ctx.sema.db).into_iter().for_each(|item| add_assoc_item(acc, item))
} }
Qualified::TypeAnchor { ty: Some(ty), trait_: None } => { Qualified::TypeAnchor { ty: Some(ty), trait_: None } => {
ctx.iterate_path_candidates(&ty, |item| { ctx.iterate_path_candidates(ty, |item| {
add_assoc_item(acc, item); add_assoc_item(acc, item);
}); });

View File

@ -226,7 +226,7 @@ fn analyze(
find_node_at_offset(&file_with_fake_ident, offset) find_node_at_offset(&file_with_fake_ident, offset)
{ {
let parent = name_ref.syntax().parent()?; let parent = name_ref.syntax().parent()?;
let (mut nameref_ctx, _) = classify_name_ref(&sema, &original_file, name_ref, parent)?; let (mut nameref_ctx, _) = classify_name_ref(sema, &original_file, name_ref, parent)?;
if let NameRefKind::Path(path_ctx) = &mut nameref_ctx.kind { if let NameRefKind::Path(path_ctx) = &mut nameref_ctx.kind {
path_ctx.kind = PathKind::Derive { path_ctx.kind = PathKind::Derive {
existing_derives: sema existing_derives: sema
@ -277,7 +277,7 @@ fn analyze(
return Some((analysis, (None, None), QualifierCtx::default())); return Some((analysis, (None, None), QualifierCtx::default()));
} }
}; };
let expected = expected_type_and_name(sema, &self_token, &name_like); let expected = expected_type_and_name(sema, self_token, &name_like);
let mut qual_ctx = QualifierCtx::default(); let mut qual_ctx = QualifierCtx::default();
let analysis = match name_like { let analysis = match name_like {
ast::NameLike::Lifetime(lifetime) => { ast::NameLike::Lifetime(lifetime) => {
@ -374,7 +374,7 @@ fn expected_type_and_name(
ast::ArgList(_) => { ast::ArgList(_) => {
cov_mark::hit!(expected_type_fn_param); cov_mark::hit!(expected_type_fn_param);
ActiveParameter::at_token( ActiveParameter::at_token(
&sema, sema,
token.clone(), token.clone(),
).map(|ap| { ).map(|ap| {
let name = ap.ident().map(NameOrNameRef::Name); let name = ap.ident().map(NameOrNameRef::Name);
@ -507,7 +507,7 @@ fn classify_lifetime(
_ => LifetimeKind::Lifetime, _ => LifetimeKind::Lifetime,
} }
}; };
let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start()); let lifetime = find_node_at_offset(original_file, lifetime.syntax().text_range().start());
Some(LifetimeContext { lifetime, kind }) Some(LifetimeContext { lifetime, kind })
} }
@ -548,7 +548,7 @@ fn classify_name(
_ => return None, _ => return None,
} }
}; };
let name = find_node_at_offset(&original_file, name.syntax().text_range().start()); let name = find_node_at_offset(original_file, name.syntax().text_range().start());
Some(NameContext { name, kind }) Some(NameContext { name, kind })
} }
@ -558,7 +558,7 @@ fn classify_name_ref(
name_ref: ast::NameRef, name_ref: ast::NameRef,
parent: SyntaxNode, parent: SyntaxNode,
) -> Option<(NameRefContext, QualifierCtx)> { ) -> Option<(NameRefContext, QualifierCtx)> {
let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start()); let nameref = find_node_at_offset(original_file, name_ref.syntax().text_range().start());
let make_res = |kind| (NameRefContext { nameref: nameref.clone(), kind }, Default::default()); let make_res = |kind| (NameRefContext { nameref: nameref.clone(), kind }, Default::default());

View File

@ -68,7 +68,7 @@ pub(crate) fn render_union_literal(
item.set_documentation(ctx.docs(un)) item.set_documentation(ctx.docs(un))
.set_deprecated(ctx.is_deprecated(un)) .set_deprecated(ctx.is_deprecated(un))
.detail(&detail) .detail(detail)
.set_relevance(ctx.completion_relevance()); .set_relevance(ctx.completion_relevance());
match ctx.snippet_cap() { match ctx.snippet_cap() {

View File

@ -128,9 +128,9 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
)?; )?;
use_trivial_constructor( use_trivial_constructor(
&ctx.sema.db, ctx.sema.db,
ide_db::helpers::mod_path_to_ast(&type_path), ide_db::helpers::mod_path_to_ast(&type_path),
&ty, ty,
) )
})(); })();

View File

@ -68,7 +68,7 @@ fn missing_record_expr_field_fixes(
} }
let new_field = make::record_field( let new_field = make::record_field(
None, None,
make::name(&record_expr_field.field_name()?.ident_token()?.text()), make::name(record_expr_field.field_name()?.ident_token()?.text()),
make::ty(&new_field_type.display_source_code(sema.db, module.into()).ok()?), make::ty(&new_field_type.display_source_code(sema.db, module.into()).ok()?),
); );

View File

@ -229,7 +229,7 @@ pub fn diagnostics(
for node in parse.syntax().descendants() { for node in parse.syntax().descendants() {
handlers::useless_braces::useless_braces(&mut res, file_id, &node); handlers::useless_braces::useless_braces(&mut res, file_id, &node);
handlers::field_shorthand::field_shorthand(&mut res, file_id, &node); handlers::field_shorthand::field_shorthand(&mut res, file_id, &node);
handlers::json_is_not_rust::json_in_items(&sema, &mut res, file_id, &node, &config); handlers::json_is_not_rust::json_in_items(&sema, &mut res, file_id, &node, config);
} }
let module = sema.to_module_def(file_id); let module = sema.to_module_def(file_id);

View File

@ -11,7 +11,7 @@ fn sourcegen_diagnostic_docs() {
diagnostics.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n"); diagnostics.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n");
let contents = sourcegen::add_preamble("sourcegen_diagnostic_docs", contents); let contents = sourcegen::add_preamble("sourcegen_diagnostic_docs", contents);
let dst = project_root().join("docs/user/generated_diagnostic.adoc"); let dst = project_root().join("docs/user/generated_diagnostic.adoc");
fs::write(&dst, &contents).unwrap(); fs::write(dst, contents).unwrap();
} }
#[derive(Debug)] #[derive(Debug)]

View File

@ -163,7 +163,7 @@ fn _format(
) -> Option<String> { ) -> Option<String> {
use ide_db::base_db::{FileLoader, SourceDatabase}; use ide_db::base_db::{FileLoader, SourceDatabase};
// hack until we get hygiene working (same character amount to preserve formatting as much as possible) // hack until we get hygiene working (same character amount to preserve formatting as much as possible)
const DOLLAR_CRATE_REPLACE: &str = &"__r_a_"; const DOLLAR_CRATE_REPLACE: &str = "__r_a_";
let expansion = expansion.replace("$crate", DOLLAR_CRATE_REPLACE); let expansion = expansion.replace("$crate", DOLLAR_CRATE_REPLACE);
let (prefix, suffix) = match kind { let (prefix, suffix) = match kind {
SyntaxKind::MACRO_PAT => ("fn __(", ": u32);"), SyntaxKind::MACRO_PAT => ("fn __(", ": u32);"),

View File

@ -195,7 +195,7 @@ pub(crate) fn hover(
// fallback to type hover if there aren't any other suggestions // fallback to type hover if there aren't any other suggestions
// this finds its own range instead of using the closest token's range // this finds its own range instead of using the closest token's range
.or_else(|| { .or_else(|| {
descended.iter().find_map(|token| hover_type_fallback(sema, config, token, &token)) descended.iter().find_map(|token| hover_type_fallback(sema, config, token, token))
}) })
} }

View File

@ -276,7 +276,7 @@ pub(super) fn struct_rest_pat(
} }
}; };
for (_, t) in &missing_fields { for (_, t) in &missing_fields {
walk_and_push_ty(sema.db, &t, &mut push_new_def); walk_and_push_ty(sema.db, t, &mut push_new_def);
} }
res.markup = { res.markup = {

View File

@ -253,7 +253,7 @@ fn label_of_ty(
ty: hir::Type, ty: hir::Type,
label_builder: &mut InlayHintLabelBuilder<'_>, label_builder: &mut InlayHintLabelBuilder<'_>,
) { ) {
let iter_item_type = hint_iterator(sema, &famous_defs, &ty); let iter_item_type = hint_iterator(sema, famous_defs, &ty);
match iter_item_type { match iter_item_type {
Some(ty) => { Some(ty) => {
const LABEL_START: &str = "impl Iterator<Item = "; const LABEL_START: &str = "impl Iterator<Item = ";
@ -279,7 +279,7 @@ fn label_of_ty(
location_link_enabled: config.location_links, location_link_enabled: config.location_links,
result: InlayHintLabel::default(), result: InlayHintLabel::default(),
}; };
rec(sema, &famous_defs, config.max_length, ty, &mut label_builder); rec(sema, famous_defs, config.max_length, ty, &mut label_builder);
let r = label_builder.finish(); let r = label_builder.finish();
Some(r) Some(r)
} }
@ -315,7 +315,7 @@ pub(crate) fn inlay_hints(
let mut acc = Vec::new(); let mut acc = Vec::new();
if let Some(scope) = sema.scope(&file) { if let Some(scope) = sema.scope(file) {
let famous_defs = FamousDefs(&sema, scope.krate()); let famous_defs = FamousDefs(&sema, scope.krate());
let hints = |node| hints(&mut acc, &famous_defs, config, file_id, node); let hints = |node| hints(&mut acc, &famous_defs, config, file_id, node);

View File

@ -31,7 +31,7 @@ pub(super) fn hints(
.last(); .last();
let range = let range =
outer_paren_pat.as_ref().map_or_else(|| pat.syntax(), |it| it.syntax()).text_range(); outer_paren_pat.as_ref().map_or_else(|| pat.syntax(), |it| it.syntax()).text_range();
let pattern_adjustments = sema.pattern_adjustments(&pat); let pattern_adjustments = sema.pattern_adjustments(pat);
pattern_adjustments.iter().for_each(|ty| { pattern_adjustments.iter().for_each(|ty| {
let reference = ty.is_reference(); let reference = ty.is_reference();
let mut_reference = ty.is_mutable_reference(); let mut_reference = ty.is_mutable_reference();

View File

@ -30,7 +30,7 @@ fn check_punct_spacing(fixture: &str) {
while !cursor.eof() { while !cursor.eof() {
while let Some(token_tree) = cursor.token_tree() { while let Some(token_tree) = cursor.token_tree() {
if let TokenTreeRef::Leaf(Leaf::Punct(Punct { spacing, id, .. }), _) = token_tree { if let TokenTreeRef::Leaf(Leaf::Punct(Punct { spacing, id, .. }), _) = token_tree {
if let Some(expected) = annotations.remove(&id) { if let Some(expected) = annotations.remove(id) {
assert_eq!(expected, *spacing); assert_eq!(expected, *spacing);
} }
} }

View File

@ -182,7 +182,7 @@ impl server::TokenStream for RustAnalyzer {
.map(|tree| match tree { .map(|tree| match tree {
tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => { tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
bridge::TokenTree::Ident(bridge::Ident { bridge::TokenTree::Ident(bridge::Ident {
sym: Symbol::intern(&ident.text.trim_start_matches("r#")), sym: Symbol::intern(ident.text.trim_start_matches("r#")),
is_raw: ident.text.starts_with("r#"), is_raw: ident.text.starts_with("r#"),
span: ident.id, span: ident.id,
}) })

View File

@ -114,7 +114,7 @@ impl Drop for CpuSpan {
match out { match out {
Ok(out) if out.status.success() => { Ok(out) if out.status.success() => {
let svg = profile_data.with_extension("svg"); let svg = profile_data.with_extension("svg");
std::fs::write(&svg, &out.stdout).unwrap(); std::fs::write(&svg, out.stdout).unwrap();
eprintln!("Profile rendered to:\n\n {}\n", svg.display()); eprintln!("Profile rendered to:\n\n {}\n", svg.display());
} }
_ => { _ => {

View File

@ -66,7 +66,7 @@ impl WorkspaceBuildScripts {
_ => { _ => {
let mut cmd = Command::new(toolchain::cargo()); let mut cmd = Command::new(toolchain::cargo());
cmd.args(&["check", "--quiet", "--workspace", "--message-format=json"]); cmd.args(["check", "--quiet", "--workspace", "--message-format=json"]);
// --all-targets includes tests, benches and examples in addition to the // --all-targets includes tests, benches and examples in addition to the
// default lib and bins. This is an independent concept from the --target // default lib and bins. This is an independent concept from the --target
@ -74,7 +74,7 @@ impl WorkspaceBuildScripts {
cmd.arg("--all-targets"); cmd.arg("--all-targets");
if let Some(target) = &config.target { if let Some(target) = &config.target {
cmd.args(&["--target", target]); cmd.args(["--target", target]);
} }
match &config.features { match &config.features {
@ -122,7 +122,7 @@ impl WorkspaceBuildScripts {
InvocationLocation::Root(root) if config.run_build_script_command.is_some() => { InvocationLocation::Root(root) if config.run_build_script_command.is_some() => {
root.as_path() root.as_path()
} }
_ => &workspace.workspace_root(), _ => workspace.workspace_root(),
} }
.as_ref(); .as_ref();
@ -133,7 +133,7 @@ impl WorkspaceBuildScripts {
// building build scripts failed, attempt to build with --keep-going so // building build scripts failed, attempt to build with --keep-going so
// that we potentially get more build data // that we potentially get more build data
let mut cmd = Self::build_command(config)?; let mut cmd = Self::build_command(config)?;
cmd.args(&["-Z", "unstable-options", "--keep-going"]).env("RUSTC_BOOTSTRAP", "1"); cmd.args(["-Z", "unstable-options", "--keep-going"]).env("RUSTC_BOOTSTRAP", "1");
let mut res = Self::run_per_ws(cmd, workspace, current_dir, progress)?; let mut res = Self::run_per_ws(cmd, workspace, current_dir, progress)?;
res.error = Some(error); res.error = Some(error);
Ok(res) Ok(res)

View File

@ -517,7 +517,7 @@ fn cargo_config_build_target(
cargo_config.envs(extra_env); cargo_config.envs(extra_env);
cargo_config cargo_config
.current_dir(cargo_toml.parent()) .current_dir(cargo_toml.parent())
.args(&["-Z", "unstable-options", "config", "get", "build.target"]) .args(["-Z", "unstable-options", "config", "get", "build.target"])
.env("RUSTC_BOOTSTRAP", "1"); .env("RUSTC_BOOTSTRAP", "1");
// if successful we receive `build.target = "target-triple"` // if successful we receive `build.target = "target-triple"`
// or `build.target = ["<target 1>", ..]` // or `build.target = ["<target 1>", ..]`

View File

@ -50,10 +50,10 @@ fn get_rust_cfgs(
cargo_config.envs(extra_env); cargo_config.envs(extra_env);
cargo_config cargo_config
.current_dir(cargo_toml.parent()) .current_dir(cargo_toml.parent())
.args(&["rustc", "-Z", "unstable-options", "--print", "cfg"]) .args(["rustc", "-Z", "unstable-options", "--print", "cfg"])
.env("RUSTC_BOOTSTRAP", "1"); .env("RUSTC_BOOTSTRAP", "1");
if let Some(target) = target { if let Some(target) = target {
cargo_config.args(&["--target", target]); cargo_config.args(["--target", target]);
} }
match utf8_stdout(cargo_config) { match utf8_stdout(cargo_config) {
Ok(it) => return Ok(it), Ok(it) => return Ok(it),
@ -63,9 +63,9 @@ fn get_rust_cfgs(
// using unstable cargo features failed, fall back to using plain rustc // using unstable cargo features failed, fall back to using plain rustc
let mut cmd = Command::new(toolchain::rustc()); let mut cmd = Command::new(toolchain::rustc());
cmd.envs(extra_env); cmd.envs(extra_env);
cmd.args(&["--print", "cfg", "-O"]); cmd.args(["--print", "cfg", "-O"]);
if let Some(target) = target { if let Some(target) = target {
cmd.args(&["--target", target]); cmd.args(["--target", target]);
} }
utf8_stdout(cmd) utf8_stdout(cmd)
} }

View File

@ -171,7 +171,7 @@ fn discover_sysroot_dir(
) -> Result<AbsPathBuf> { ) -> Result<AbsPathBuf> {
let mut rustc = Command::new(toolchain::rustc()); let mut rustc = Command::new(toolchain::rustc());
rustc.envs(extra_env); rustc.envs(extra_env);
rustc.current_dir(current_dir).args(&["--print", "sysroot"]); rustc.current_dir(current_dir).args(["--print", "sysroot"]);
tracing::debug!("Discovering sysroot by {:?}", rustc); tracing::debug!("Discovering sysroot by {:?}", rustc);
let stdout = utf8_stdout(rustc)?; let stdout = utf8_stdout(rustc)?;
Ok(AbsPathBuf::assert(PathBuf::from(stdout))) Ok(AbsPathBuf::assert(PathBuf::from(stdout)))
@ -203,7 +203,7 @@ fn discover_sysroot_src_dir_or_add_component(
.or_else(|| { .or_else(|| {
let mut rustup = Command::new(toolchain::rustup()); let mut rustup = Command::new(toolchain::rustup());
rustup.envs(extra_env); rustup.envs(extra_env);
rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]); rustup.current_dir(current_dir).args(["component", "add", "rust-src"]);
tracing::info!("adding rust-src component by {:?}", rustup); tracing::info!("adding rust-src component by {:?}", rustup);
utf8_stdout(rustup).ok()?; utf8_stdout(rustup).ok()?;
get_rust_src(sysroot_path) get_rust_src(sysroot_path)

View File

@ -15,10 +15,10 @@ pub(super) fn get(
let mut cmd = Command::new(toolchain::rustc()); let mut cmd = Command::new(toolchain::rustc());
cmd.envs(extra_env); cmd.envs(extra_env);
cmd.current_dir(cargo_toml.parent()) cmd.current_dir(cargo_toml.parent())
.args(&["-Z", "unstable-options", "rustc", "--print", "target-spec-json"]) .args(["-Z", "unstable-options", "rustc", "--print", "target-spec-json"])
.env("RUSTC_BOOTSTRAP", "1"); .env("RUSTC_BOOTSTRAP", "1");
if let Some(target) = target { if let Some(target) = target {
cmd.args(&["--target", target]); cmd.args(["--target", target]);
} }
match utf8_stdout(cmd) { match utf8_stdout(cmd) {
Ok(it) => return Ok(it), Ok(it) => return Ok(it),
@ -28,10 +28,10 @@ pub(super) fn get(
// using unstable cargo features failed, fall back to using plain rustc // using unstable cargo features failed, fall back to using plain rustc
let mut cmd = Command::new(toolchain::rustc()); let mut cmd = Command::new(toolchain::rustc());
cmd.envs(extra_env) cmd.envs(extra_env)
.args(&["-Z", "unstable-options", "rustc", "--print", "target-spec-json"]) .args(["-Z", "unstable-options", "rustc", "--print", "target-spec-json"])
.env("RUSTC_BOOTSTRAP", "1"); .env("RUSTC_BOOTSTRAP", "1");
if let Some(target) = target { if let Some(target) = target {
cmd.args(&["--target", target]); cmd.args(["--target", target]);
} }
utf8_stdout(cmd) utf8_stdout(cmd)
})() })()

View File

@ -407,7 +407,7 @@ impl ProjectWorkspace {
["libexec", "lib"] ["libexec", "lib"]
.into_iter() .into_iter()
.map(|segment| sysroot.root().join(segment).join(&standalone_server_name)) .map(|segment| sysroot.root().join(segment).join(&standalone_server_name))
.find(|server_path| std::fs::metadata(&server_path).is_ok()) .find(|server_path| std::fs::metadata(server_path).is_ok())
} }
_ => None, _ => None,
} }

View File

@ -42,7 +42,7 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities {
"(".to_string(), "(".to_string(),
]), ]),
all_commit_characters: None, all_commit_characters: None,
completion_item: completion_item(&config), completion_item: completion_item(config),
work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
}), }),
signature_help_provider: Some(SignatureHelpOptions { signature_help_provider: Some(SignatureHelpOptions {
@ -67,7 +67,7 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities {
}, },
document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions { document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
first_trigger_character: "=".to_string(), first_trigger_character: "=".to_string(),
more_trigger_character: Some(more_trigger_character(&config)), more_trigger_character: Some(more_trigger_character(config)),
}), }),
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)), selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)), folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),

View File

@ -102,7 +102,7 @@ impl flags::Scip {
let symbol = tokens_to_symbol let symbol = tokens_to_symbol
.entry(id) .entry(id)
.or_insert_with(|| { .or_insert_with(|| {
let symbol = token_to_symbol(&token).unwrap_or_else(&mut new_local_symbol); let symbol = token_to_symbol(token).unwrap_or_else(&mut new_local_symbol);
scip::symbol::format_symbol(symbol) scip::symbol::format_symbol(symbol)
}) })
.clone(); .clone();
@ -176,7 +176,7 @@ fn get_relative_filepath(
rootpath: &vfs::AbsPathBuf, rootpath: &vfs::AbsPathBuf,
file_id: ide::FileId, file_id: ide::FileId,
) -> Option<String> { ) -> Option<String> {
Some(vfs.file_path(file_id).as_path()?.strip_prefix(&rootpath)?.as_ref().to_str()?.to_string()) Some(vfs.file_path(file_id).as_path()?.strip_prefix(rootpath)?.as_ref().to_str()?.to_string())
} }
// SCIP Ranges have a (very large) optimization that ranges if they are on the same line // SCIP Ranges have a (very large) optimization that ranges if they are on the same line

View File

@ -877,7 +877,7 @@ impl GlobalState {
if let Ok(vfs_path) = from_proto::vfs_path(&params.text_document.uri) { if let Ok(vfs_path) = from_proto::vfs_path(&params.text_document.uri) {
// Re-fetch workspaces if a workspace related file has changed // Re-fetch workspaces if a workspace related file has changed
if let Some(abs_path) = vfs_path.as_path() { if let Some(abs_path) = vfs_path.as_path() {
if reload::should_refresh_for_change(&abs_path, ChangeKind::Modify) { if reload::should_refresh_for_change(abs_path, ChangeKind::Modify) {
this.fetch_workspaces_queue this.fetch_workspaces_queue
.request_op(format!("DidSaveTextDocument {}", abs_path.display())); .request_op(format!("DidSaveTextDocument {}", abs_path.display()));
} }

View File

@ -14,7 +14,7 @@ fn sourcegen_feature_docs() {
contents.trim() contents.trim()
); );
let dst = sourcegen::project_root().join("docs/user/generated_features.adoc"); let dst = sourcegen::project_root().join("docs/user/generated_features.adoc");
fs::write(&dst, &contents).unwrap(); fs::write(dst, contents).unwrap();
} }
#[derive(Debug)] #[derive(Debug)]

View File

@ -119,7 +119,7 @@ pub struct Location {
impl fmt::Display for Location { impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let path = self.file.strip_prefix(&project_root()).unwrap().display().to_string(); let path = self.file.strip_prefix(project_root()).unwrap().display().to_string();
let path = path.replace('\\', "/"); let path = path.replace('\\', "/");
let name = self.file.file_name().unwrap(); let name = self.file.file_name().unwrap();
write!( write!(
@ -175,7 +175,7 @@ pub fn ensure_file_contents(file: &Path, contents: &str) {
} }
} }
let display_path = file.strip_prefix(&project_root()).unwrap_or(file); let display_path = file.strip_prefix(project_root()).unwrap_or(file);
eprintln!( eprintln!(
"\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n", "\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n",
display_path.display() display_path.display()

View File

@ -888,6 +888,6 @@ enum Foo {
let enum_ = ast_mut_from_text::<ast::Enum>(before); let enum_ = ast_mut_from_text::<ast::Enum>(before);
enum_.variant_list().map(|it| it.add_variant(variant)); enum_.variant_list().map(|it| it.add_variant(variant));
let after = enum_.to_string(); let after = enum_.to_string();
assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(&after.trim())); assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(after.trim()));
} }
} }

View File

@ -157,7 +157,7 @@ fn collect_rust_files(root_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)>
/// Collects paths to all `.rs` files from `dir` in a sorted `Vec<PathBuf>`. /// Collects paths to all `.rs` files from `dir` in a sorted `Vec<PathBuf>`.
fn rust_files_in_dir(dir: &Path) -> Vec<PathBuf> { fn rust_files_in_dir(dir: &Path) -> Vec<PathBuf> {
let mut acc = Vec::new(); let mut acc = Vec::new();
for file in fs::read_dir(&dir).unwrap() { for file in fs::read_dir(dir).unwrap() {
let file = file.unwrap(); let file = file.unwrap();
let path = file.path(); let path = file.path();
if path.extension().unwrap_or_default() == "rs" { if path.extension().unwrap_or_default() == "rs" {

View File

@ -479,7 +479,7 @@ pub fn try_ensure_file_contents(file: &Path, contents: &str) -> Result<(), ()> {
} }
_ => (), _ => (),
} }
let display_path = file.strip_prefix(&project_root()).unwrap_or(file); let display_path = file.strip_prefix(project_root()).unwrap_or(file);
eprintln!( eprintln!(
"\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n", "\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n",
display_path.display() display_path.display()