Skip to content

Commit a035b2c

Browse files
tesujitopecongiro
authored andcommitted
Some minor cleanup (#3970)
1 parent 64be324 commit a035b2c

File tree

19 files changed

+153
-154
lines changed

19 files changed

+153
-154
lines changed

Cargo.lock

Lines changed: 6 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,9 @@ regex = "1.0"
4343
term = "0.6"
4444
diff = "0.1"
4545
log = "0.4"
46-
env_logger = "0.6"
46+
env_logger = "0.7"
4747
getopts = "0.2"
48-
cargo_metadata = "0.8"
48+
cargo_metadata = "0.9"
4949
bytecount = "0.6"
5050
unicode-width = "0.1.5"
5151
unicode_categories = "0.1.1"

config_proc_macro/src/item_enum.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,11 @@ fn impl_from_str(ident: &syn::Ident, variants: &Variants) -> TokenStream {
123123
}
124124

125125
fn doc_hint_of_variant(variant: &syn::Variant) -> String {
126-
find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string())
126+
find_doc_hint(&variant.attrs).unwrap_or_else(|| variant.ident.to_string())
127127
}
128128

129129
fn config_value_of_variant(variant: &syn::Variant) -> String {
130-
find_config_value(&variant.attrs).unwrap_or(variant.ident.to_string())
130+
find_config_value(&variant.attrs).unwrap_or_else(|| variant.ident.to_string())
131131
}
132132

133133
fn impl_serde(ident: &syn::Ident, variants: &Variants) -> TokenStream {

src/bin/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ fn execute(opts: &Options) -> Result<i32> {
235235
let file = PathBuf::from(path);
236236
let file = file.canonicalize().unwrap_or(file);
237237

238-
let (config, _) = load_config(Some(file.parent().unwrap()), Some(options.clone()))?;
238+
let (config, _) = load_config(Some(file.parent().unwrap()), Some(options))?;
239239
let toml = config.all_options().to_toml()?;
240240
io::stdout().write_all(toml.as_bytes())?;
241241

@@ -590,7 +590,7 @@ impl GetOptsOptions {
590590
options.inline_config = matches
591591
.opt_strs("config")
592592
.iter()
593-
.flat_map(|config| config.split(","))
593+
.flat_map(|config| config.split(','))
594594
.map(
595595
|key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') {
596596
Some((middle, _)) => {

src/cargo-fmt/main.rs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,11 @@ fn execute() -> i32 {
102102
if opts.version {
103103
return handle_command_status(get_rustfmt_info(&[String::from("--version")]));
104104
}
105-
if opts.rustfmt_options.iter().any(|s| {
106-
["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str())
107-
|| s.starts_with("--help=")
108-
|| s.starts_with("--print-config=")
109-
}) {
105+
if opts
106+
.rustfmt_options
107+
.iter()
108+
.any(|s| is_status_options(s.as_str()))
109+
{
110110
return handle_command_status(get_rustfmt_info(&opts.rustfmt_options));
111111
}
112112

@@ -142,6 +142,12 @@ fn execute() -> i32 {
142142
}
143143
}
144144

145+
fn is_status_options(s: &str) -> bool {
146+
["--print-config", "-h", "--help", "-V", "--version"].contains(&s)
147+
|| s.starts_with("--help=")
148+
|| s.starts_with("--print-config=")
149+
}
150+
145151
fn build_rustfmt_args(opts: &Opts, rustfmt_args: &mut Vec<String>) -> Result<(), String> {
146152
let mut contains_check = false;
147153
let mut contains_emit_mode = false;
@@ -285,9 +291,9 @@ impl Target {
285291
) -> Self {
286292
let path = PathBuf::from(&target.src_path);
287293
let canonicalized = fs::canonicalize(&path).unwrap_or(path);
288-
let test_files = nested_int_test_files.unwrap_or(vec![]);
294+
let test_files = nested_int_test_files.unwrap_or_else(Vec::new);
289295

290-
Target {
296+
Self {
291297
path: canonicalized,
292298
kind: target.kind[0].clone(),
293299
edition: target.edition.clone(),
@@ -417,7 +423,7 @@ fn get_targets_root_only(
417423
.map(|p| p.targets)
418424
.flatten()
419425
.collect(),
420-
PathBuf::from(current_dir_manifest),
426+
current_dir_manifest,
421427
),
422428
};
423429

@@ -660,7 +666,7 @@ fn get_cargo_metadata(
660666
match cmd.exec() {
661667
Ok(metadata) => Ok(metadata),
662668
Err(_) => {
663-
cmd.other_options(vec![]);
669+
cmd.other_options(&[]);
664670
match cmd.exec() {
665671
Ok(metadata) => Ok(metadata),
666672
Err(error) => Err(io::Error::new(io::ErrorKind::Other, error.to_string())),

src/config/config_type.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ macro_rules! create_config {
139139
ConfigWasSet(self)
140140
}
141141

142-
fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config {
142+
fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Self {
143143
let deprecate_skip_children = || {
144144
let msg = "Option skip_children is deprecated since it is now the default to \
145145
not format submodules of given files (#3587)";
@@ -248,8 +248,10 @@ macro_rules! create_config {
248248

249249
#[allow(unreachable_pub)]
250250
pub fn is_hidden_option(name: &str) -> bool {
251-
const HIDE_OPTIONS: [&str; 6] =
252-
["verbose", "verbose_diff", "file_lines", "width_heuristics", "recursive", "print_misformatted_file_names"];
251+
const HIDE_OPTIONS: [&str; 6] = [
252+
"verbose", "verbose_diff", "file_lines", "width_heuristics",
253+
"recursive", "print_misformatted_file_names",
254+
];
253255
HIDE_OPTIONS.contains(&name)
254256
}
255257

@@ -271,7 +273,7 @@ macro_rules! create_config {
271273
}
272274
name_out.push_str(name_raw);
273275
name_out.push(' ');
274-
let mut default_str = format!("{}", $def);
276+
let mut default_str = $def.to_string();
275277
if default_str.is_empty() {
276278
default_str = String::from("\"\"");
277279
}
@@ -322,19 +324,19 @@ macro_rules! create_config {
322324
#[allow(unreachable_pub)]
323325
/// Returns `true` if the config key was explicitly set and is the default value.
324326
pub fn is_default(&self, key: &str) -> bool {
325-
$(
326-
if let stringify!($i) = key {
327-
return self.$i.1 && self.$i.2 == $def;
328-
}
329-
)+
330-
false
327+
match key {
328+
$(
329+
stringify!($i) => self.$i.1 && self.$i.2 == $def,
330+
)+
331+
_ => false,
332+
}
331333
}
332334
}
333335

334336
// Template for the default configuration
335337
impl Default for Config {
336-
fn default() -> Config {
337-
Config {
338+
fn default() -> Self {
339+
Self {
338340
license_template: None,
339341
$(
340342
$i: (Cell::new(false), false, $def, $stb),

src/config/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,9 @@ mod test {
513513
Ok(_) => panic!("Expected configuration error"),
514514
Err(msg) => assert_eq!(
515515
msg,
516-
"Error: Conflicting config options `skip_children` and `recursive` are both enabled. `skip_children` has been deprecated and should be removed from your config.",
516+
"Error: Conflicting config options `skip_children` and `recursive` \
517+
are both enabled. `skip_children` has been deprecated and should be \
518+
removed from your config.",
517519
),
518520
}
519521
}

src/emitter/json.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ mod tests {
136136
],
137137
};
138138

139-
let _ = emitter
139+
emitter
140140
.add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch])
141141
.unwrap();
142142

@@ -181,7 +181,7 @@ mod tests {
181181
],
182182
};
183183

184-
let _ = emitter
184+
emitter
185185
.add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch])
186186
.unwrap();
187187

@@ -206,7 +206,7 @@ mod tests {
206206
.unwrap();
207207
let _ = emitter.emit_footer(&mut writer);
208208
assert_eq!(result.has_diff, false);
209-
assert_eq!(&writer[..], "[]\n".as_bytes());
209+
assert_eq!(&writer[..], b"[]\n");
210210
}
211211

212212
#[test]

src/expr.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ pub(crate) fn rewrite_cond(
600600
String::from("\n") + &shape.indent.block_only().to_string(context.config);
601601
control_flow
602602
.rewrite_cond(context, shape, &alt_block_sep)
603-
.and_then(|rw| Some(rw.0))
603+
.map(|rw| rw.0)
604604
}),
605605
}
606606
}
@@ -835,7 +835,7 @@ impl<'a> ControlFlow<'a> {
835835
rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
836836
{
837837
if !self.connector.is_empty() && !comment.is_empty() {
838-
if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
838+
if comment_style(&comment, false).is_line_comment() || comment.contains('\n') {
839839
let newline = &pat_shape
840840
.indent
841841
.block_indent(context.config)

src/formatting.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ fn format_project<T: FormatHandler>(
9494
let files = modules::ModResolver::new(
9595
&context.parse_session,
9696
directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaMod(true)),
97-
!(input_is_stdin || !config.recursive()),
97+
!input_is_stdin && config.recursive(),
9898
)
9999
.visit_crate(&krate)
100100
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

src/formatting/newline_style.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ fn convert_to_windows_newlines(formatted_text: &String) -> String {
7777
transformed
7878
}
7979

80-
fn convert_to_unix_newlines(formatted_text: &String) -> String {
80+
fn convert_to_unix_newlines(formatted_text: &str) -> String {
8181
formatted_text.replace(WINDOWS_NEWLINE, UNIX_NEWLINE)
8282
}
8383

src/items.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,7 +1210,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> {
12101210

12111211
let fits_single_line = !generic_bounds_str.contains('\n')
12121212
&& !where_str.contains('\n')
1213-
&& generic_bounds_str.len() + where_str.len() + 1 <= shape.width;
1213+
&& generic_bounds_str.len() + where_str.len() < shape.width;
12141214
let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
12151215
Cow::from("")
12161216
} else if fits_single_line {
@@ -1998,7 +1998,7 @@ impl Rewrite for ast::Param {
19981998
let num_attrs = self.attrs.len();
19991999
(
20002000
mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
2001-
param_attrs_result.contains("\n"),
2001+
param_attrs_result.contains('\n'),
20022002
)
20032003
} else {
20042004
(mk_sp(self.span.lo(), self.span.lo()), false)

src/lists.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ where
823823
pub(crate) fn total_item_width(item: &ListItem) -> usize {
824824
comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
825825
+ comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
826-
+ &item.item.as_ref().map_or(0, |s| unicode_str_width(&s))
826+
+ item.item.as_ref().map_or(0, |s| unicode_str_width(&s))
827827
}
828828

829829
fn comment_len(comment: Option<&str>) -> usize {

src/macros.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -225,18 +225,17 @@ pub(crate) fn rewrite_macro(
225225
}
226226

227227
fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
228+
let is_delim = |kind| match kind {
229+
TokenKind::Eof | TokenKind::Comma | TokenKind::CloseDelim(DelimToken::NoDelim) => true,
230+
_ => false,
231+
};
228232
for &keyword in RUST_KW.iter() {
229-
if parser.token.is_keyword(keyword)
230-
&& parser.look_ahead(1, |t| {
231-
t.kind == TokenKind::Eof
232-
|| t.kind == TokenKind::Comma
233-
|| t.kind == TokenKind::CloseDelim(DelimToken::NoDelim)
234-
})
235-
{
233+
if parser.token.is_keyword(keyword) && parser.look_ahead(1, |t| is_delim(t.kind.clone())) {
236234
parser.bump();
237-
let macro_arg =
238-
MacroArg::Keyword(ast::Ident::with_dummy_span(keyword), parser.prev_span);
239-
return Some(macro_arg);
235+
return Some(MacroArg::Keyword(
236+
ast::Ident::with_dummy_span(keyword),
237+
parser.prev_span,
238+
));
240239
}
241240
}
242241
None

src/modules.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
6767
) -> Result<FileModMap<'ast>, String> {
6868
let root_filename = self.parse_sess.span_to_filename(krate.span);
6969
self.directory.path = match root_filename {
70-
FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
70+
FileName::Real(ref p) => p.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
7171
_ => PathBuf::new(),
7272
};
7373

0 commit comments

Comments
 (0)