Skip to content

Commit

Permalink
fix other clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
kadiwa4 committed Jan 9, 2024
1 parent 220bb45 commit 24cc6da
Show file tree
Hide file tree
Showing 21 changed files with 68 additions and 81 deletions.
18 changes: 10 additions & 8 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,15 +439,15 @@ fn print_version() {

fn determine_operation(matches: &Matches) -> Result<Operation, OperationError> {
if matches.opt_present("h") {
let topic = matches.opt_str("h");
if topic.is_none() {
let Some(topic) = matches.opt_str("h") else {
return Ok(Operation::Help(HelpOp::None));
} else if topic == Some("config".to_owned()) {
};
if topic == "config" {
return Ok(Operation::Help(HelpOp::Config));
} else if topic == Some("file-lines".to_owned()) && is_nightly() {
} else if topic == "file-lines" && is_nightly() {
return Ok(Operation::Help(HelpOp::FileLines));
} else {
return Err(OperationError::UnknownHelpTopic(topic.unwrap()));
return Err(OperationError::UnknownHelpTopic(topic));
}
}
let mut free_matches = matches.free.iter();
Expand Down Expand Up @@ -523,9 +523,11 @@ struct GetOptsOptions {

impl GetOptsOptions {
pub fn from_matches(matches: &Matches) -> Result<GetOptsOptions> {
let mut options = GetOptsOptions::default();
options.verbose = matches.opt_present("verbose");
options.quiet = matches.opt_present("quiet");
let mut options = Self {
verbose: matches.opt_present("verbose"),
quiet: matches.opt_present("quiet"),
..Self::default()
};
if options.verbose && options.quiet {
return Err(format_err!("Can't use both `--verbose` and `--quiet`"));
}
Expand Down
2 changes: 1 addition & 1 deletion src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ impl ChainItemKind {
fn is_tup_field_access(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::Field(_, ref field) => {
field.name.to_string().chars().all(|c| c.is_digit(10))
field.name.to_string().bytes().all(|c| c.is_ascii_digit())
}
_ => false,
}
Expand Down
7 changes: 4 additions & 3 deletions src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl<'a> CommentStyle<'a> {
}
}

pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
pub(crate) fn to_str_tuplet(self) -> (&'a str, &'a str, &'a str) {
(self.opener(), self.closer(), self.line_start())
}
}
Expand Down Expand Up @@ -990,11 +990,12 @@ fn is_table_item(mut s: &str) -> bool {
// This function may return false positive, but should get its job done in most cases (i.e.
// markdown tables with two column delimiters).
s = s.trim_start();
return s.starts_with('|')

s.starts_with('|')
&& match s.rfind('|') {
Some(0) | None => false,
_ => true,
};
}
}

/// Given the span, rewrite the missing comment inside it if available.
Expand Down
2 changes: 1 addition & 1 deletion src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ macro_rules! create_config {
}
}

#[allow(unreachable_pub)]
#[allow(unreachable_pub, clippy::cmp_owned)]
/// Returns `true` if the config key was explicitly set and is the default value.
pub fn is_default(&self, key: &str) -> bool {
$(
Expand Down
2 changes: 1 addition & 1 deletion src/config/file_lines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl fmt::Display for FileLines {
Some(map) => {
for (file_name, ranges) in map.iter() {
write!(f, "{file_name}: ")?;
write!(f, "{}\n", ranges.iter().format(", "))?;
writeln!(f, "{}", ranges.iter().format(", "))?;
}
}
};
Expand Down
17 changes: 5 additions & 12 deletions src/config/options.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![allow(unused_imports)]
#![allow(clippy::enum_variant_names)]

use std::collections::{hash_set, HashSet};
use std::fmt;
Expand Down Expand Up @@ -153,9 +154,11 @@ pub enum ReportTactic {

/// What Rustfmt should emit. Mostly corresponds to the `--emit` command line
/// option.
#[derive(Default)]
#[config_type]
pub enum EmitMode {
/// Emits to files.
#[default]
Files,
/// Writes the output to stdout.
Stdout,
Expand Down Expand Up @@ -308,12 +311,6 @@ impl ::std::str::FromStr for WidthHeuristics {
}
}

impl Default for EmitMode {
fn default() -> EmitMode {
EmitMode::Files
}
}

/// A set of directories, files and modules that rustfmt should ignore.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct IgnoreList {
Expand Down Expand Up @@ -417,10 +414,12 @@ pub trait CliOptions {
}

/// The edition of the syntax and semntics of code (RFC 2052).
#[derive(Default)]
#[config_type]
pub enum Edition {
#[value = "2015"]
#[doc_hint = "2015"]
#[default]
/// Edition 2015.
Edition2015,
#[value = "2018"]
Expand All @@ -437,12 +436,6 @@ pub enum Edition {
Edition2024,
}

impl Default for Edition {
fn default() -> Edition {
Edition::Edition2015
}
}

impl From<Edition> for rustc_span::edition::Edition {
fn from(edition: Edition) -> Self {
match edition {
Expand Down
4 changes: 2 additions & 2 deletions src/emitter/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ mod tests {
],
};

let _ = emitter
emitter
.add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch])
.unwrap();

Expand Down Expand Up @@ -181,7 +181,7 @@ mod tests {
],
};

let _ = emitter
emitter
.add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch])
.unwrap();

Expand Down
20 changes: 10 additions & 10 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,10 @@ pub(crate) fn format_expr(
ast::RangeLimits::Closed => "..=",
};

fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
fn needs_space_before_range(lhs: &ast::Expr) -> bool {
match lhs.kind {
ast::ExprKind::Lit(token_lit) => lit_ends_in_dot(&token_lit),
ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(expr),
_ => false,
}
}
Expand All @@ -296,7 +296,7 @@ pub(crate) fn format_expr(

format!(
"{}{}{}",
lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
lhs.map_or("", |lhs| space_if(needs_space_before_range(lhs))),
delim,
rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
)
Expand Down Expand Up @@ -1573,11 +1573,11 @@ fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool
!has_base && fields.iter().all(|field| !field.is_shorthand)
}

fn rewrite_struct_lit<'a>(
fn rewrite_struct_lit(
context: &RewriteContext<'_>,
path: &ast::Path,
qself: &Option<ptr::P<ast::QSelf>>,
fields: &'a [ast::ExprField],
fields: &[ast::ExprField],
struct_rest: &ast::StructRest,
attrs: &[ast::Attribute],
span: Span,
Expand Down Expand Up @@ -1620,14 +1620,14 @@ fn rewrite_struct_lit<'a>(
one_line_width,
)?
} else {
let field_iter = fields.iter().map(StructLitField::Regular).chain(
match struct_rest {
let field_iter = fields
.iter()
.map(StructLitField::Regular)
.chain(match struct_rest {
ast::StructRest::Base(expr) => Some(StructLitField::Base(expr)),
ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
ast::StructRest::None => None,
}
.into_iter(),
);
});

let span_lo = |item: &StructLitField<'_>| match *item {
StructLitField::Regular(field) => field.span().lo(),
Expand Down
2 changes: 1 addition & 1 deletion src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ impl<'a> FormatLines<'a> {
}

// Iterate over the chars in the file map.
fn iterate(&mut self, text: &mut String) {
fn iterate(&mut self, text: &mut str) {
for (kind, c) in CharClasses::new(text.chars()) {
if c == '\r' {
continue;
Expand Down
8 changes: 4 additions & 4 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1224,7 +1224,7 @@ pub(crate) fn format_trait(
let item_snippet = context.snippet(item.span);
if let Some(lo) = item_snippet.find('/') {
// 1 = `{`
let comment_hi = if generics.params.len() > 0 {
let comment_hi = if !generics.params.is_empty() {
generics.span.lo() - BytePos(1)
} else {
body_lo - BytePos(1)
Expand Down Expand Up @@ -1663,11 +1663,11 @@ struct TyAliasRewriteInfo<'c, 'g>(
Span,
);

pub(crate) fn rewrite_type_alias<'a, 'b>(
pub(crate) fn rewrite_type_alias(
ty_alias_kind: &ast::TyAlias,
context: &RewriteContext<'a>,
context: &RewriteContext<'_>,
indent: Indent,
visitor_kind: &ItemVisitorKind<'b>,
visitor_kind: &ItemVisitorKind<'_>,
span: Span,
) -> Option<String> {
use ItemVisitorKind::*;
Expand Down
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,17 +516,17 @@ impl<'b, T: Write + 'b> Session<'b, T> {
pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
match config.emit_mode() {
EmitMode::Files if config.make_backup() => {
Box::new(emitter::FilesWithBackupEmitter::default())
<Box<emitter::FilesWithBackupEmitter>>::default()
}
EmitMode::Files => Box::new(emitter::FilesEmitter::new(
config.print_misformatted_file_names(),
)),
EmitMode::Stdout | EmitMode::Coverage => {
Box::new(emitter::StdoutEmitter::new(config.verbose()))
}
EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
EmitMode::Json => <Box<emitter::JsonEmitter>>::default(),
EmitMode::ModifiedLines => <Box<emitter::ModifiedLinesEmitter>>::default(),
EmitMode::Checkstyle => <Box<emitter::CheckstyleEmitter>>::default(),
EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ pub(crate) fn rewrite_macro_def(
shape
};

if parsed_def.branches.len() == 0 {
if parsed_def.branches.is_empty() {
let lo = context.snippet_provider.span_before(span, "{");
result += " ";
result += &rewrite_empty_macro_def_body(context, span.with_lo(lo), shape)?;
Expand Down
2 changes: 1 addition & 1 deletion src/matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ fn rewrite_match_arms(
context.snippet_provider,
arms.iter()
.zip(is_last_iter)
.zip(beginning_verts.into_iter())
.zip(beginning_verts)
.map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
"}",
"|",
Expand Down
8 changes: 4 additions & 4 deletions src/overflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,8 @@ impl<'a> Context<'a> {
};

if let Some(rewrite) = rewrite {
// splitn(2, *).next().unwrap() is always safe.
let rewrite_first_line = Some(rewrite.splitn(2, '\n').next().unwrap().to_owned());
// split(*).next().unwrap() never panics.
let rewrite_first_line = Some(rewrite.split('\n').next().unwrap().to_owned());
last_list_item.item = rewrite_first_line;
Some(rewrite)
} else {
Expand Down Expand Up @@ -735,7 +735,7 @@ fn last_item_shape(
shape: Shape,
args_max_width: usize,
) -> Option<Shape> {
if items.len() == 1 && !lists.get(0)?.is_nested_call() {
if items.len() == 1 && !lists.first()?.is_nested_call() {
return Some(shape);
}
let offset = items
Expand Down Expand Up @@ -786,7 +786,7 @@ pub(crate) fn maybe_get_args_offset(
config: &Config,
) -> Option<(bool, usize)> {
if let Some(&(_, num_args_before)) = args
.get(0)?
.first()?
.special_cases(config)
.find(|&&(s, _)| s == callee_str)
{
Expand Down
4 changes: 3 additions & 1 deletion src/parse/macros/lazy_static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ use rustc_span::symbol::{self, kw};

use crate::rewrite::RewriteContext;

type LazyStaticItem = (ast::Visibility, symbol::Ident, P<ast::Ty>, P<ast::Expr>);

pub(crate) fn parse_lazy_static(
context: &RewriteContext<'_>,
ts: TokenStream,
) -> Option<Vec<(ast::Visibility, symbol::Ident, P<ast::Ty>, P<ast::Expr>)>> {
) -> Option<Vec<LazyStaticItem>> {
let mut result = vec![];
let mut parser = super::build_parser(context, ts);
macro_rules! parse_or {
Expand Down
8 changes: 4 additions & 4 deletions src/parse/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub(crate) mod asm;
pub(crate) mod cfg_if;
pub(crate) mod lazy_static;

fn build_stream_parser<'a>(sess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> {
fn build_stream_parser(sess: &ParseSess, tokens: TokenStream) -> Parser<'_> {
stream_to_parser(sess, tokens, MACRO_ARGUMENTS)
}

Expand Down Expand Up @@ -47,17 +47,17 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
parse_macro_arg!(
Expr,
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(),
|x: ptr::P<ast::Expr>| Some(x)
Some
);
parse_macro_arg!(
Ty,
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(),
|x: ptr::P<ast::Ty>| Some(x)
Some
);
parse_macro_arg!(
Pat,
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat_no_top_alt(None, None),
|x: ptr::P<ast::Pat>| Some(x)
Some
);
// `parse_item` returns `Option<ptr::P<ast::Item>>`.
parse_macro_arg!(
Expand Down
8 changes: 4 additions & 4 deletions src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ impl Indent {
self.block_indent + self.alignment
}

pub(crate) fn to_string(&self, config: &Config) -> Cow<'static, str> {
pub(crate) fn to_string(self, config: &Config) -> Cow<'static, str> {
self.to_string_inner(config, 1)
}

pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> {
pub(crate) fn to_string_with_newline(self, config: &Config) -> Cow<'static, str> {
self.to_string_inner(config, 0)
}

fn to_string_inner(&self, config: &Config, offset: usize) -> Cow<'static, str> {
fn to_string_inner(self, config: &Config, offset: usize) -> Cow<'static, str> {
let (num_tabs, num_spaces) = if config.hard_tabs() {
(self.block_indent / config.tab_spaces(), self.alignment)
} else {
Expand Down Expand Up @@ -272,7 +272,7 @@ impl Shape {
Shape { width, ..*self }
}

pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> {
pub(crate) fn to_string_with_newline(self, config: &Config) -> Cow<'static, str> {
let mut offset_indent = self.indent;
offset_indent.alignment = self.offset;
offset_indent.to_string_inner(config, 0)
Expand Down
Loading

0 comments on commit 24cc6da

Please sign in to comment.