More manual clippy fixes

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

View file

@ -43,7 +43,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
.clone();
let trait_token =
ctx.token_at_offset().filter(|t| t.kind() == IDENT && *t.text() != attr_name).next()?;
ctx.token_at_offset().find(|t| t.kind() == IDENT && *t.text() != attr_name)?;
let annotated = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?;
let annotated_name = annotated.syntax().text().to_string();
@ -86,7 +86,7 @@ pub(crate) fn add_custom_impl(ctx: AssistCtx) -> Option<Assist> {
.next_sibling_or_token()
.filter(|t| t.kind() == WHITESPACE)
.map(|t| t.text_range())
.unwrap_or(TextRange::from_to(TextUnit::from(0), TextUnit::from(0)));
.unwrap_or_else(|| TextRange::from_to(TextUnit::from(0), TextUnit::from(0)));
edit.delete(line_break_range);
attr_range.len() + line_break_range.len()

View file

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

View file

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

View file

@ -157,7 +157,7 @@ impl ItemScope {
}
pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Name, PerNs)> + 'a {
self.visible.iter().map(|(name, res)| (name.clone(), res.clone()))
self.visible.iter().map(|(name, res)| (name.clone(), *res))
}
pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {

View file

@ -460,7 +460,7 @@ impl AsMacroCall for AstIdWithPath<ast::MacroCall> {
resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
) -> Option<MacroCallId> {
let def = resolver(self.path.clone())?;
Some(def.as_call_id(db, MacroCallKind::FnLike(self.ast_id.clone())))
Some(def.as_call_id(db, MacroCallKind::FnLike(self.ast_id)))
}
}
@ -471,6 +471,6 @@ impl AsMacroCall for AstIdWithPath<ast::ModuleItem> {
resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
) -> Option<MacroCallId> {
let def = resolver(self.path.clone())?;
Some(def.as_call_id(db, MacroCallKind::Attr(self.ast_id.clone())))
Some(def.as_call_id(db, MacroCallKind::Attr(self.ast_id)))
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -128,7 +128,7 @@ impl FnCallNode {
}),
FnCallNode::MethodCallExpr(call_expr) => {
call_expr.syntax().children().filter_map(ast::NameRef::cast).nth(0)
call_expr.syntax().children().filter_map(ast::NameRef::cast).next()
}
FnCallNode::MacroCallExpr(call_expr) => call_expr.path()?.segment()?.name_ref(),

View file

@ -59,7 +59,7 @@ pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext
.as_ref()
.and_then(|node| node.parent())
.and_then(|node| node.parent())
.and_then(|node| ast::ImplBlock::cast(node));
.and_then(ast::ImplBlock::cast);
if let (Some(trigger), Some(impl_block)) = (trigger, impl_block) {
match trigger.kind() {
@ -110,17 +110,17 @@ fn add_function_impl(
ctx: &CompletionContext,
func: &hir::Function,
) {
let display = FunctionSignature::from_hir(ctx.db, func.clone());
let display = FunctionSignature::from_hir(ctx.db, *func);
let fn_name = func.name(ctx.db).to_string();
let label = if func.params(ctx.db).len() > 0 {
let label = if !func.params(ctx.db).is_empty() {
format!("fn {}(..)", fn_name)
} else {
format!("fn {}()", fn_name)
};
let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label.clone())
let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
.lookup_by(fn_name)
.set_documentation(func.docs(ctx.db));

View file

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

View file

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

View file

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

View file

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

View file

@ -85,8 +85,11 @@ impl FromStr for SsrQuery {
fn from_str(query: &str) -> Result<SsrQuery, SsrError> {
let mut it = query.split("==>>");
let pattern = it.next().expect("at least empty string").trim();
let mut template =
it.next().ok_or(SsrError("Cannot find delemiter `==>>`".into()))?.trim().to_string();
let mut template = it
.next()
.ok_or_else(|| SsrError("Cannot find delemiter `==>>`".into()))?
.trim()
.to_string();
if it.next().is_some() {
return Err(SsrError("More than one delimiter found".into()));
}
@ -131,11 +134,12 @@ fn traverse(node: &SyntaxNode, go: &mut impl FnMut(&SyntaxNode) -> bool) {
}
fn split_by_var(s: &str) -> Result<(&str, &str, &str), SsrError> {
let end_of_name = s.find(":").ok_or(SsrError("Use $<name>:expr".into()))?;
let end_of_name = s.find(':').ok_or_else(|| SsrError("Use $<name>:expr".into()))?;
let name = &s[0..end_of_name];
is_name(name)?;
let type_begin = end_of_name + 1;
let type_length = s[type_begin..].find(|c| !char::is_ascii_alphanumeric(&c)).unwrap_or(s.len());
let type_length =
s[type_begin..].find(|c| !char::is_ascii_alphanumeric(&c)).unwrap_or_else(|| s.len());
let type_name = &s[type_begin..type_begin + type_length];
Ok((name, type_name, &s[type_begin + type_length..]))
}
@ -182,7 +186,7 @@ fn find(pattern: &SsrPattern, code: &SyntaxNode) -> SsrMatches {
pattern.text() == code.text()
}
(SyntaxElement::Node(ref pattern), SyntaxElement::Node(ref code)) => {
if placeholders.iter().find(|&n| n.0.as_str() == pattern.text()).is_some() {
if placeholders.iter().any(|n| n.0.as_str() == pattern.text()) {
match_.binding.insert(Var(pattern.text().to_string()), code.clone());
true
} else {

View file

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

View file

@ -21,7 +21,7 @@ use super::*;
// struct S;
pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) {
attributes::inner_attributes(p);
while !p.at(EOF) && !(stop_on_r_curly && p.at(T!['}'])) {
while !(stop_on_r_curly && p.at(T!['}']) || p.at(EOF)) {
item_or_macro(p, stop_on_r_curly, ItemFlavor::Mod)
}
}

View file

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

View file

@ -197,7 +197,7 @@ impl CargoWorkspace {
let pkg_data = &mut packages[pkg];
pkg_by_id.insert(id, pkg);
for meta_tgt in meta_pkg.targets {
let is_proc_macro = meta_tgt.kind.as_slice() == &["proc-macro"];
let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
let tgt = targets.alloc(TargetData {
pkg,
name: meta_tgt.name,

View file

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

View file

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