Skip to content

Implement cargo lint and fix some clippy errors #1374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 25 commits into from
Jun 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .cargo/config
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ install-code = "run --package tools --bin tools -- install-code"
# Formats the full repository or installs the git hook to do it automatically.
format = "run --package tools --bin tools -- format"
format-hook = "run --package tools --bin tools -- format-hook"
# Run clippy
lint = "run --package tools --bin tools -- lint"

# Runs the fuzzing test suite (currently only parser)
fuzz-tests = "run --package tools --bin tools -- fuzz-tests"

Expand Down
26 changes: 11 additions & 15 deletions crates/ra_assists/src/ast_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,21 +212,17 @@ impl AstEditor<ast::FnDef> {
}

pub fn strip_attrs_and_docs(&mut self) {
loop {
if let Some(start) = self
.ast()
.syntax()
.children_with_tokens()
.find(|it| it.kind() == ATTR || it.kind() == COMMENT)
{
let end = match start.next_sibling_or_token() {
Some(el) if el.kind() == WHITESPACE => el,
Some(_) | None => start,
};
self.ast = self.replace_children(RangeInclusive::new(start, end), iter::empty());
} else {
break;
}
while let Some(start) = self
.ast()
.syntax()
.children_with_tokens()
.find(|it| it.kind() == ATTR || it.kind() == COMMENT)
{
let end = match start.next_sibling_or_token() {
Some(el) if el.kind() == WHITESPACE => el,
Some(_) | None => start,
};
self.ast = self.replace_children(RangeInclusive::new(start, end), iter::empty());
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ra_assists/src/auto_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ fn best_action_for_target<'b, 'a: 'b>(
.filter_map(ast::UseItem::use_tree)
.map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
.fold(None, |best, a| {
best.and_then(|best| Some(*ImportAction::better(&best, &a))).or(Some(a))
best.and_then(|best| Some(*ImportAction::better(&best, &a))).or_else(|| Some(a))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel conflicted about this, it seems like closure creates noise for little benefit here. But I guess it's ok?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think the fact that clippy interprets these constructors as "function calls" is pretty unfortunate, It looks like a bug (rust-lang/rust-clippy#1609), but for now I figured that it'd be better to make the changes just so we can get all the lint errors out of the way.

});

match best_action {
Expand All @@ -347,7 +347,7 @@ fn best_action_for_target<'b, 'a: 'b>(
let anchor = container
.children()
.find(|n| n.range().start() < anchor.range().start())
.or(Some(anchor));
.or_else(|| Some(anchor));

return ImportAction::add_new_use(anchor, false);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_assists/src/change_visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ fn vis_offset(node: &SyntaxNode) -> TextUnit {
})
.next()
.map(|it| it.range().start())
.unwrap_or(node.range().start())
.unwrap_or_else(|| node.range().start())
}

fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: &ast::Visibility) -> Option<Assist> {
Expand Down
4 changes: 2 additions & 2 deletions crates/ra_assists/src/introduce_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
if text.starts_with("\r\n") {
buf.push_str("\r\n");
buf.push_str(text.trim_start_matches("\r\n"));
} else if text.starts_with("\n") {
} else if text.starts_with('\n') {
buf.push_str("\n");
buf.push_str(text.trim_start_matches("\n"));
buf.push_str(text.trim_start_matches('\n'));
} else {
buf.push_str(text);
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ra_batch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ impl salsa::Database for BatchDatabase {
}

fn vfs_file_to_id(f: ra_vfs::VfsFile) -> FileId {
FileId(f.0.into())
FileId(f.0)
}
fn vfs_root_to_id(r: ra_vfs::VfsRoot) -> SourceRootId {
SourceRootId(r.0.into())
SourceRootId(r.0)
}

impl BatchDatabase {
Expand Down
10 changes: 4 additions & 6 deletions crates/ra_cli/src/analysis_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,16 @@ pub fn run(verbose: bool, path: &str, only: Option<&str>) -> Result<()> {

for decl in module.declarations(&db) {
num_decls += 1;
match decl {
ModuleDef::Function(f) => funcs.push(f),
_ => {}
if let ModuleDef::Function(f) = decl {
funcs.push(f);
}
}

for impl_block in module.impl_blocks(&db) {
for item in impl_block.items(&db) {
num_decls += 1;
match item {
ImplItem::Method(f) => funcs.push(f),
_ => {}
if let ImplItem::Method(f) = item {
funcs.push(f);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_hir/src/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl AdtDef {

impl Struct {
pub(crate) fn variant_data(&self, db: &impl DefDatabase) -> Arc<VariantData> {
db.struct_data((*self).into()).variant_data.clone()
db.struct_data(*self).variant_data.clone()
}
}

Expand Down
5 changes: 2 additions & 3 deletions crates/ra_hir/src/code_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,8 @@ impl Module {

for impl_block in self.impl_blocks(db) {
for item in impl_block.items(db) {
match item {
crate::ImplItem::Method(f) => f.diagnostics(db, sink),
_ => (),
if let crate::ImplItem::Method(f) = item {
f.diagnostics(db, sink);
}
}
}
Expand Down
11 changes: 4 additions & 7 deletions crates/ra_hir/src/expr/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,8 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
pub(crate) fn validate_body(&mut self, db: &impl HirDatabase) {
let body = self.func.body(db);
for e in body.exprs() {
match e {
(id, Expr::StructLit { path, fields, spread }) => {
self.validate_struct_literal(id, path, fields, spread, db)
}
_ => (),
if let (id, Expr::StructLit { path, fields, spread }) = e {
self.validate_struct_literal(id, path, fields, spread, db);
}
}
}
Expand All @@ -44,7 +41,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
&mut self,
id: ExprId,
_path: &Option<Path>,
fields: &Vec<StructLitField>,
fields: &[StructLitField],
spread: &Option<ExprId>,
db: &impl HirDatabase,
) {
Expand All @@ -57,7 +54,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
_ => return,
};

let lit_fields: FxHashSet<_> = fields.into_iter().map(|f| &f.name).collect();
let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
let missed_fields: Vec<Name> = struct_def
.fields(db)
.iter()
Expand Down
1 change: 0 additions & 1 deletion crates/ra_hir/src/impl_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ impl ModuleImplBlocks {
};

let (file_id, module_source) = m.module.definition_source(db);
let file_id: HirFileId = file_id.into();
let node = match &module_source {
ModuleSource::SourceFile(node) => node.syntax(),
ModuleSource::Module(node) => {
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_hir/src/lang_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl LangItems {
.nth(0);
if let Some(lang_item_name) = lang_item_name {
let imp = ImplBlock::from_id(*module, impl_id);
self.items.entry(lang_item_name).or_insert(LangItemTarget::ImplBlock(imp));
self.items.entry(lang_item_name).or_insert_with(|| LangItemTarget::ImplBlock(imp));
}
}

Expand Down
27 changes: 15 additions & 12 deletions crates/ra_hir/src/nameres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,8 @@ impl CrateDefMap {
let name = path.expand_macro_expr()?;
// search local first
// FIXME: Remove public_macros check when we have a correct local_macors implementation
let local = self.public_macros.get(&name).or(self.local_macros.get(&name)).map(|it| *it);
let local =
self.public_macros.get(&name).or_else(|| self.local_macros.get(&name)).map(|it| *it);
if local.is_some() {
return local;
}
Expand Down Expand Up @@ -405,7 +406,7 @@ impl CrateDefMap {
};

for (i, segment) in segments {
let curr = match curr_per_ns.as_ref().left().map_or(None, |m| m.as_ref().take_types()) {
let curr = match curr_per_ns.as_ref().left().and_then(|m| m.as_ref().take_types()) {
Some(r) => r,
None => {
// we still have path segments left, but the path so far
Expand All @@ -421,10 +422,8 @@ impl CrateDefMap {
curr_per_ns = match curr {
ModuleDef::Module(module) => {
if module.krate != self.krate {
let path = Path {
segments: path.segments[i..].iter().cloned().collect(),
kind: PathKind::Self_,
};
let path =
Path { segments: path.segments[i..].to_vec(), kind: PathKind::Self_ };
log::debug!("resolving {:?} in other crate", path);
let defp_map = db.crate_def_map(module.krate);
let (def, s) =
Expand Down Expand Up @@ -468,7 +467,7 @@ impl CrateDefMap {
);

return ResolvePathResult::with(
Either::Left(PerNs::types((*s).into())),
Either::Left(PerNs::types(*s)),
ReachedFixedPoint::Yes,
Some(i),
);
Expand All @@ -479,8 +478,10 @@ impl CrateDefMap {
}

fn resolve_name_in_crate_root_or_extern_prelude(&self, name: &Name) -> ItemOrMacro {
let from_crate_root =
self[self.root].scope.get_item_or_macro(name).unwrap_or(Either::Left(PerNs::none()));
let from_crate_root = self[self.root]
.scope
.get_item_or_macro(name)
.unwrap_or_else(|| Either::Left(PerNs::none()));
let from_extern_prelude = self.resolve_name_in_extern_prelude(name);

or(from_crate_root, Either::Left(from_extern_prelude))
Expand All @@ -505,8 +506,10 @@ impl CrateDefMap {
// - current module / scope
// - extern prelude
// - std prelude
let from_scope =
self[module].scope.get_item_or_macro(name).unwrap_or(Either::Left(PerNs::none()));;
let from_scope = self[module]
.scope
.get_item_or_macro(name)
.unwrap_or_else(|| Either::Left(PerNs::none()));;
let from_extern_prelude =
self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it));
let from_prelude = self.resolve_in_prelude(db, name);
Expand All @@ -525,7 +528,7 @@ impl CrateDefMap {
} else {
db.crate_def_map(prelude.krate)[prelude.module_id].scope.get_item_or_macro(name)
};
resolution.unwrap_or(Either::Left(PerNs::none()))
resolution.unwrap_or_else(|| Either::Left(PerNs::none()))
} else {
Either::Left(PerNs::none())
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_hir/src/nameres/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ where

fn define_def(&mut self, def: &raw::DefData) {
let module = Module { krate: self.def_collector.def_map.krate, module_id: self.module_id };
let ctx = LocationCtx::new(self.def_collector.db, module, self.file_id.into());
let ctx = LocationCtx::new(self.def_collector.db, module, self.file_id);

macro_rules! def {
($kind:ident, $ast_id:ident) => {
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_hir/src/nameres/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl RawItems {
) -> (Arc<RawItems>, Arc<ImportSourceMap>) {
let mut collector = RawItemsCollector {
raw_items: RawItems::default(),
source_ast_id_map: db.ast_id_map(file_id.into()),
source_ast_id_map: db.ast_id_map(file_id),
source_map: ImportSourceMap::default(),
};
if let Some(node) = db.parse_or_expand(file_id) {
Expand Down
4 changes: 2 additions & 2 deletions crates/ra_hir/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl Path {

/// `true` if this path is just a standalone `self`
pub fn is_self(&self) -> bool {
self.kind == PathKind::Self_ && self.segments.len() == 0
self.kind == PathKind::Self_ && self.segments.is_empty()
}

/// If this path is a single identifier, like `foo`, return its name.
Expand All @@ -140,7 +140,7 @@ impl GenericArgs {
args.push(GenericArg::Type(type_ref));
}
// lifetimes and assoc type args ignored for now
if args.len() > 0 {
if !args.is_empty() {
Some(GenericArgs { args })
} else {
None
Expand Down
11 changes: 4 additions & 7 deletions crates/ra_hir/src/source_binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ pub fn module_from_declaration(
pub fn module_from_position(db: &impl HirDatabase, position: FilePosition) -> Option<Module> {
let file = db.parse(position.file_id).tree;
match find_node_at_offset::<ast::Module>(file.syntax(), position.offset) {
Some(m) if !m.has_semi() => module_from_inline(db, position.file_id.into(), m),
_ => module_from_file_id(db, position.file_id.into()),
Some(m) if !m.has_semi() => module_from_inline(db, position.file_id, m),
_ => module_from_file_id(db, position.file_id),
}
}

Expand All @@ -72,9 +72,9 @@ pub fn module_from_child_node(
child: &SyntaxNode,
) -> Option<Module> {
if let Some(m) = child.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi()) {
module_from_inline(db, file_id.into(), m)
module_from_inline(db, file_id, m)
} else {
module_from_file_id(db, file_id.into())
module_from_file_id(db, file_id)
}
}

Expand All @@ -99,14 +99,12 @@ pub fn struct_from_module(
struct_def: &ast::StructDef,
) -> Struct {
let (file_id, _) = module.definition_source(db);
let file_id = file_id.into();
let ctx = LocationCtx::new(db, module, file_id);
Struct { id: ctx.to_def(struct_def) }
}

pub fn enum_from_module(db: &impl HirDatabase, module: Module, enum_def: &ast::EnumDef) -> Enum {
let (file_id, _) = module.definition_source(db);
let file_id = file_id.into();
let ctx = LocationCtx::new(db, module, file_id);
Enum { id: ctx.to_def(enum_def) }
}
Expand All @@ -117,7 +115,6 @@ pub fn trait_from_module(
trait_def: &ast::TraitDef,
) -> Trait {
let (file_id, _) = module.definition_source(db);
let file_id = file_id.into();
let ctx = LocationCtx::new(db, module, file_id);
Trait { id: ctx.to_def(trait_def) }
}
Expand Down
9 changes: 3 additions & 6 deletions crates/ra_hir/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,10 @@ impl TraitItemsIndex {
pub(crate) fn trait_items_index(db: &impl DefDatabase, module: Module) -> TraitItemsIndex {
let mut index = TraitItemsIndex { traits_by_def: FxHashMap::default() };
for decl in module.declarations(db) {
match decl {
crate::ModuleDef::Trait(tr) => {
for item in tr.trait_data(db).items() {
index.traits_by_def.insert(*item, tr);
}
if let crate::ModuleDef::Trait(tr) = decl {
for item in tr.trait_data(db).items() {
index.traits_by_def.insert(*item, tr);
}
_ => {}
}
}
index
Expand Down
2 changes: 1 addition & 1 deletion crates/ra_hir/src/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ impl Ty {
/// Substitutes `Ty::Bound` vars (as opposed to type parameters).
pub fn subst_bound_vars(self, substs: &Substs) -> Ty {
self.fold(&mut |ty| match ty {
Ty::Bound(idx) => substs.get(idx as usize).cloned().unwrap_or(Ty::Bound(idx)),
Ty::Bound(idx) => substs.get(idx as usize).cloned().unwrap_or_else(|| Ty::Bound(idx)),
ty => ty,
})
}
Expand Down
Loading