10440: Fix Clippy warnings and replace some `if let`s with `match` r=Veykril a=arzg

I decided to try fixing a bunch of Clippy warnings. I am aware of this project’s opinion of Clippy (I have read both [rust-lang/clippy#5537](https://github.com/rust-lang/rust-clippy/issues/5537) and [rust-analyzer/rowan#57 (comment)](https://github.com/rust-analyzer/rowan/pull/57#discussion_r415676159)), so I totally understand if part of or the entirety of this PR is rejected. In particular, I can see how the semicolons and `if let` vs `match` commits provide comparatively little benefit when compared to the ensuing churn.

I tried to separate each kind of change into its own commit to make it easier to discard certain changes. I also only applied Clippy suggestions where I thought they provided a definite improvement to the code (apart from semicolons, which is IMO more of a formatting/consistency question than a linting question). In the end I accumulated a list of 28 Clippy lints I ignored entirely.

Sidenote: I should really have asked about this on Zulip before going through all 1,555 `if let`s in the codebase to decide which ones definitely look better as `match` :P

Co-authored-by: Aramis Razzaghipour <aramisnoah@gmail.com>
This commit is contained in:
bors[bot] 2021-10-05 08:58:40 +00:00 committed by GitHub
commit 86c534f244
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
95 changed files with 399 additions and 478 deletions

View file

@ -112,15 +112,15 @@ impl TreeDiff {
pub fn into_text_edit(&self, builder: &mut TextEditBuilder) {
let _p = profile::span("into_text_edit");
for (anchor, to) in self.insertions.iter() {
for (anchor, to) in &self.insertions {
let offset = match anchor {
TreeDiffInsertPos::After(it) => it.text_range().end(),
TreeDiffInsertPos::AsFirstChild(it) => it.text_range().start(),
};
to.iter().for_each(|to| builder.insert(offset, to.to_string()));
}
for (from, to) in self.replacements.iter() {
builder.replace(from.text_range(), to.to_string())
for (from, to) in &self.replacements {
builder.replace(from.text_range(), to.to_string());
}
for text_range in self.deletions.iter().map(SyntaxElement::text_range) {
builder.delete(text_range);
@ -217,9 +217,8 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
cov_mark::hit!(diff_insertions);
insert = true;
break;
} else {
look_ahead_scratch.push(rhs_child);
}
look_ahead_scratch.push(rhs_child);
}
let drain = look_ahead_scratch.drain(..);
if insert {
@ -233,7 +232,7 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
diff.insertions.entry(insert_pos).or_insert_with(Vec::new).extend(drain);
rhs_children = rhs_children_clone;
} else {
go(diff, lhs_ele, rhs_ele)
go(diff, lhs_ele, rhs_ele);
}
}
}

View file

@ -126,7 +126,7 @@ impl IndentLevel {
if let Some(ws) = ast::Whitespace::cast(token) {
if ws.text().contains('\n') {
let new_ws = make::tokens::whitespace(&format!("{}{}", ws.syntax(), self));
ted::replace(ws.syntax(), &new_ws)
ted::replace(ws.syntax(), &new_ws);
}
}
}
@ -143,7 +143,7 @@ impl IndentLevel {
let new_ws = make::tokens::whitespace(
&ws.syntax().text().replace(&format!("\n{}", self), "\n"),
);
ted::replace(ws.syntax(), &new_ws)
ted::replace(ws.syntax(), &new_ws);
}
}
}

View file

@ -49,7 +49,7 @@ impl GenericParamsOwnerEdit for ast::Fn {
} else {
Position::last_child_of(self.syntax())
};
create_where_clause(position)
create_where_clause(position);
}
self.where_clause().unwrap()
}
@ -60,10 +60,9 @@ impl GenericParamsOwnerEdit for ast::Impl {
match self.generic_param_list() {
Some(it) => it,
None => {
let position = if let Some(imp_token) = self.impl_token() {
Position::after(imp_token)
} else {
Position::last_child_of(self.syntax())
let position = match self.impl_token() {
Some(imp_token) => Position::after(imp_token),
None => Position::last_child_of(self.syntax()),
};
create_generic_param_list(position)
}
@ -72,12 +71,11 @@ impl GenericParamsOwnerEdit for ast::Impl {
fn get_or_create_where_clause(&self) -> ast::WhereClause {
if self.where_clause().is_none() {
let position = if let Some(items) = self.assoc_item_list() {
Position::before(items.syntax())
} else {
Position::last_child_of(self.syntax())
let position = match self.assoc_item_list() {
Some(items) => Position::before(items.syntax()),
None => Position::last_child_of(self.syntax()),
};
create_where_clause(position)
create_where_clause(position);
}
self.where_clause().unwrap()
}
@ -102,12 +100,11 @@ impl GenericParamsOwnerEdit for ast::Trait {
fn get_or_create_where_clause(&self) -> ast::WhereClause {
if self.where_clause().is_none() {
let position = if let Some(items) = self.assoc_item_list() {
Position::before(items.syntax())
} else {
Position::last_child_of(self.syntax())
let position = match self.assoc_item_list() {
Some(items) => Position::before(items.syntax()),
None => Position::last_child_of(self.syntax()),
};
create_where_clause(position)
create_where_clause(position);
}
self.where_clause().unwrap()
}
@ -145,7 +142,7 @@ impl GenericParamsOwnerEdit for ast::Struct {
} else {
Position::last_child_of(self.syntax())
};
create_where_clause(position)
create_where_clause(position);
}
self.where_clause().unwrap()
}
@ -177,7 +174,7 @@ impl GenericParamsOwnerEdit for ast::Enum {
} else {
Position::last_child_of(self.syntax())
};
create_where_clause(position)
create_where_clause(position);
}
self.where_clause().unwrap()
}
@ -234,7 +231,7 @@ impl ast::GenericParamList {
}
None => {
let after_l_angle = Position::after(self.l_angle_token().unwrap());
ted::insert(after_l_angle, generic_param.syntax())
ted::insert(after_l_angle, generic_param.syntax());
}
}
}
@ -247,18 +244,15 @@ impl ast::WhereClause {
ted::append_child_raw(self.syntax(), make::token(T![,]));
}
}
ted::append_child(self.syntax(), predicate.syntax())
ted::append_child(self.syntax(), predicate.syntax());
}
}
impl ast::TypeBoundList {
pub fn remove(&self) {
if let Some(colon) =
self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:])
{
ted::remove_all(colon..=self.syntax().clone().into())
} else {
ted::remove(self.syntax())
match self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:]) {
Some(colon) => ted::remove_all(colon..=self.syntax().clone().into()),
None => ted::remove(self.syntax()),
}
}
}
@ -267,7 +261,7 @@ impl ast::PathSegment {
pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList {
if self.generic_arg_list().is_none() {
let arg_list = make::generic_arg_list().clone_for_update();
ted::append_child(self.syntax(), arg_list.syntax())
ted::append_child(self.syntax(), arg_list.syntax());
}
self.generic_arg_list().unwrap()
}
@ -275,7 +269,7 @@ impl ast::PathSegment {
impl ast::UseTree {
pub fn remove(&self) {
for &dir in [Direction::Next, Direction::Prev].iter() {
for dir in [Direction::Next, Direction::Prev] {
if let Some(next_use_tree) = neighbor(self, dir) {
let separators = self
.syntax()
@ -286,7 +280,7 @@ impl ast::UseTree {
break;
}
}
ted::remove(self.syntax())
ted::remove(self.syntax());
}
}
@ -301,13 +295,13 @@ impl ast::Use {
let ws_text = next_ws.syntax().text();
if let Some(rest) = ws_text.strip_prefix('\n') {
if rest.is_empty() {
ted::remove(next_ws.syntax())
ted::remove(next_ws.syntax());
} else {
ted::replace(next_ws.syntax(), make::tokens::whitespace(rest))
ted::replace(next_ws.syntax(), make::tokens::whitespace(rest));
}
}
}
ted::remove(self.syntax())
ted::remove(self.syntax());
}
}
@ -455,7 +449,7 @@ impl ast::RecordExprField {
/// This will either replace the initializer, or in the case that this is a shorthand convert
/// the initializer into the name ref and insert the expr as the new initializer.
pub fn replace_expr(&self, expr: ast::Expr) {
if let Some(_) = self.name_ref() {
if self.name_ref().is_some() {
match self.expr() {
Some(prev) => ted::replace(prev.syntax(), expr.syntax()),
None => ted::append_child(self.syntax(), expr.syntax()),
@ -525,7 +519,7 @@ pub trait Indent: AstNode + Clone + Sized {
fn reindent_to(&self, target_level: IndentLevel) {
let current_level = IndentLevel::from_node(self.syntax());
self.dedent(current_level);
self.indent(target_level)
self.indent(target_level);
}
}

View file

@ -257,7 +257,7 @@ pub fn block_expr(
format_to!(buf, " {}\n", stmt);
}
if let Some(tail_expr) = tail_expr {
format_to!(buf, " {}\n", tail_expr)
format_to!(buf, " {}\n", tail_expr);
}
buf += "}";
ast_from_text(&format!("fn f() {}", buf))
@ -644,9 +644,14 @@ pub fn fn_(
ret_type: Option<ast::RetType>,
is_async: bool,
) -> ast::Fn {
let type_params =
if let Some(type_params) = type_params { format!("<{}>", type_params) } else { "".into() };
let ret_type = if let Some(ret_type) = ret_type { format!("{} ", ret_type) } else { "".into() };
let type_params = match type_params {
Some(type_params) => format!("<{}>", type_params),
None => "".into(),
};
let ret_type = match ret_type {
Some(ret_type) => format!("{} ", ret_type),
None => "".into(),
};
let visibility = match visibility {
None => String::new(),
Some(it) => format!("{} ", it),

View file

@ -276,9 +276,9 @@ impl ast::Path {
impl ast::Use {
pub fn is_simple_glob(&self) -> bool {
self.use_tree()
.map(|use_tree| use_tree.use_tree_list().is_none() && use_tree.star_token().is_some())
.unwrap_or(false)
self.use_tree().map_or(false, |use_tree| {
use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()
})
}
}
@ -549,10 +549,9 @@ impl ast::FieldExpr {
}
pub fn field_access(&self) -> Option<FieldKind> {
if let Some(nr) = self.name_ref() {
Some(FieldKind::Name(nr))
} else {
self.index_token().map(FieldKind::Index)
match self.name_ref() {
Some(nr) => Some(FieldKind::Name(nr)),
None => self.index_token().map(FieldKind::Index),
}
}
}

View file

@ -283,10 +283,9 @@ pub trait HasFormatSpecifier: AstToken {
where
F: FnMut(TextRange, FormatSpecifier),
{
let char_ranges = if let Some(char_ranges) = self.char_ranges() {
char_ranges
} else {
return;
let char_ranges = match self.char_ranges() {
Some(char_ranges) => char_ranges,
None => return,
};
let mut chars = char_ranges.iter().peekable();
@ -528,10 +527,11 @@ pub trait HasFormatSpecifier: AstToken {
}
}
if let Some((_, Ok('}'))) = chars.peek() {
skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
} else {
continue;
match chars.peek() {
Some((_, Ok('}'))) => {
skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
}
Some((_, _)) | None => continue,
}
}
_ => {
@ -609,7 +609,7 @@ impl HasFormatSpecifier for ast::String {
TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap())
+ offset,
unescaped_char,
))
));
});
Some(res)
@ -631,7 +631,7 @@ impl ast::IntNumber {
let mut text = token.text();
if let Some(suffix) = self.suffix() {
text = &text[..text.len() - suffix.len()]
text = &text[..text.len() - suffix.len()];
}
let radix = self.radix();
@ -688,7 +688,7 @@ impl Radix {
pub const ALL: &'static [Radix] =
&[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
const fn prefix_len(&self) -> usize {
const fn prefix_len(self) -> usize {
match self {
Self::Decimal => 0,
_ => 2,

View file

@ -28,7 +28,7 @@ pub fn function_declaration(node: &ast::Fn) -> String {
format_to!(buf, "{} ", abi);
}
if let Some(name) = node.name() {
format_to!(buf, "fn {}", name)
format_to!(buf, "fn {}", name);
}
if let Some(type_params) = node.generic_param_list() {
format_to!(buf, "{}", type_params);

View file

@ -44,8 +44,7 @@ impl<'t> TokenSource for TextTokenSource<'t> {
fn is_keyword(&self, kw: &str) -> bool {
self.token_offset_pairs
.get(self.curr.1)
.map(|(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw)
.unwrap_or(false)
.map_or(false, |(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw)
}
}
@ -55,8 +54,7 @@ fn mk_token(pos: usize, token_offset_pairs: &[(Token, TextSize)]) -> parser::Tok
token.kind,
token_offset_pairs
.get(pos + 1)
.map(|(_, next_offset)| offset + token.len == *next_offset)
.unwrap_or(false),
.map_or(false, |(_, next_offset)| offset + token.len == *next_offset),
),
None => (EOF, false),
};

View file

@ -88,7 +88,7 @@ impl<'a> TreeSink for TextTreeSink<'a> {
}
fn error(&mut self, error: ParseError) {
self.inner.error(error, self.text_pos)
self.inner.error(error, self.text_pos);
}
}
@ -108,7 +108,7 @@ impl<'a> TextTreeSink<'a> {
match mem::replace(&mut self.state, State::Normal) {
State::PendingFinish => {
self.eat_trivias();
self.inner.finish_node()
self.inner.finish_node();
}
State::PendingStart | State::Normal => unreachable!(),
}

View file

@ -81,7 +81,7 @@ impl<N: AstNode> PartialEq for AstPtr<N> {
impl<N: AstNode> Hash for AstPtr<N> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state)
self.raw.hash(state);
}
}

View file

@ -56,19 +56,19 @@ impl SyntaxTreeBuilder {
pub fn token(&mut self, kind: SyntaxKind, text: &str) {
let kind = RustLanguage::kind_to_raw(kind);
self.inner.token(kind, text)
self.inner.token(kind, text);
}
pub fn start_node(&mut self, kind: SyntaxKind) {
let kind = RustLanguage::kind_to_raw(kind);
self.inner.start_node(kind)
self.inner.start_node(kind);
}
pub fn finish_node(&mut self) {
self.inner.finish_node()
self.inner.finish_node();
}
pub fn error(&mut self, error: parser::ParseError, text_pos: TextSize) {
self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos))
self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos));
}
}

View file

@ -77,23 +77,23 @@ impl Position {
}
pub fn insert(position: Position, elem: impl Element) {
insert_all(position, vec![elem.syntax_element()])
insert_all(position, vec![elem.syntax_element()]);
}
pub fn insert_raw(position: Position, elem: impl Element) {
insert_all_raw(position, vec![elem.syntax_element()])
insert_all_raw(position, vec![elem.syntax_element()]);
}
pub fn insert_all(position: Position, mut elements: Vec<SyntaxElement>) {
if let Some(first) = elements.first() {
if let Some(ws) = ws_before(&position, first) {
elements.insert(0, ws.into())
elements.insert(0, ws.into());
}
}
if let Some(last) = elements.last() {
if let Some(ws) = ws_after(&position, last) {
elements.push(ws.into())
elements.push(ws.into());
}
}
insert_all_raw(position, elements)
insert_all_raw(position, elements);
}
pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) {
let (parent, index) = match position.repr {
@ -104,10 +104,10 @@ pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) {
}
pub fn remove(elem: impl Element) {
elem.syntax_element().detach()
elem.syntax_element().detach();
}
pub fn remove_all(range: RangeInclusive<SyntaxElement>) {
replace_all(range, Vec::new())
replace_all(range, Vec::new());
}
pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
let mut it = range.into_iter();
@ -115,9 +115,9 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
match it.last() {
Some(mut last) => {
if first.index() > last.index() {
mem::swap(&mut first, &mut last)
mem::swap(&mut first, &mut last);
}
remove_all(first..=last)
remove_all(first..=last);
}
None => remove(first),
}
@ -125,26 +125,26 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
}
pub fn replace(old: impl Element, new: impl Element) {
replace_with_many(old, vec![new.syntax_element()])
replace_with_many(old, vec![new.syntax_element()]);
}
pub fn replace_with_many(old: impl Element, new: Vec<SyntaxElement>) {
let old = old.syntax_element();
replace_all(old.clone()..=old, new)
replace_all(old.clone()..=old, new);
}
pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
let start = range.start().index();
let end = range.end().index();
let parent = range.start().parent().unwrap();
parent.splice_children(start..end + 1, new)
parent.splice_children(start..end + 1, new);
}
pub fn append_child(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
let position = Position::last_child_of(node);
insert(position, child)
insert(position, child);
}
pub fn append_child_raw(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
let position = Position::last_child_of(node);
insert_raw(position, child)
insert_raw(position, child);
}
fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {

View file

@ -227,12 +227,9 @@ where
T: crate::AstNode,
F: Fn(&str) -> Result<T, ()>,
{
dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| {
if let Ok(node) = f(text) {
format!("{:#?}", crate::ast::AstNode::syntax(&node))
} else {
panic!("Failed to parse '{:?}'", path);
}
dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| match f(text) {
Ok(node) => format!("{:#?}", crate::ast::AstNode::syntax(&node)),
Err(_) => panic!("Failed to parse '{:?}'", path),
});
dir_tests(&test_data_dir(), err_paths, "rast", |text, path| {
if f(text).is_ok() {

View file

@ -215,7 +215,7 @@ fn generate_nodes(kinds: KindsSrc<'_>, grammar: &AstSrc) -> String {
.flat_map(|node| node.traits.iter().map(move |t| (t, node)))
.into_group_map()
.into_iter()
.sorted_by_key(|(k, _)| k.clone())
.sorted_by_key(|(k, _)| *k)
.map(|(trait_name, nodes)| {
let name = format_ident!("Any{}", trait_name);
let trait_name = format_ident!("{}", trait_name);
@ -558,12 +558,13 @@ impl Field {
}
fn lower(grammar: &Grammar) -> AstSrc {
let mut res = AstSrc::default();
res.tokens = "Whitespace Comment String ByteString IntNumber FloatNumber"
.split_ascii_whitespace()
.map(|it| it.to_string())
.collect::<Vec<_>>();
let mut res = AstSrc {
tokens: "Whitespace Comment String ByteString IntNumber FloatNumber"
.split_ascii_whitespace()
.map(|it| it.to_string())
.collect::<Vec<_>>(),
..Default::default()
};
let nodes = grammar.iter().collect::<Vec<_>>();

View file

@ -137,7 +137,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Err(err) = char {
push_err(1, (range.start, err));
}
})
});
}
}
}
@ -148,7 +148,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Err(err) = char {
push_err(2, (range.start, err));
}
})
});
}
}
}

View file

@ -19,6 +19,6 @@ pub(crate) fn validate_block_expr(block: ast::BlockExpr, errors: &mut Vec<Syntax
"A block in this position cannot accept inner attributes",
attr.syntax().text_range(),
)
}))
}));
}
}