From 0725319df551c0e7547de8abba50d9745dd0677b Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Tue, 17 Dec 2019 23:45:19 +0700 Subject: [PATCH 1/8] use Self and match --- src/config/config_type.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 618de16bc15..7e0d7751bed 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -139,7 +139,7 @@ macro_rules! create_config { ConfigWasSet(self) } - fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config { + fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Self { let deprecate_skip_children = || { let msg = "Option skip_children is deprecated since it is now the default to \ not format submodules of given files (#3587)"; @@ -322,19 +322,19 @@ macro_rules! create_config { #[allow(unreachable_pub)] /// Returns `true` if the config key was explicitly set and is the default value. pub fn is_default(&self, key: &str) -> bool { - $( - if let stringify!($i) = key { - return self.$i.1 && self.$i.2 == $def; - } - )+ - false + match key { + $( + stringify!($i) => self.$i.1 && self.$i.2 == $def, + )+ + _ => false, + } } } // Template for the default configuration impl Default for Config { - fn default() -> Config { - Config { + fn default() -> Self { + Self { license_template: None, $( $i: (Cell::new(false), false, $def, $stb), From 517b11292d81012d204cf4c411fda0a848e01e5d Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 17:36:47 +0700 Subject: [PATCH 2/8] fix some clippy lints --- config_proc_macro/src/item_enum.rs | 4 ++-- src/bin/main.rs | 4 ++-- src/cargo-fmt/main.rs | 24 ++++++++++++-------- src/config/config_type.rs | 2 +- src/emitter/json.rs | 6 ++--- src/expr.rs | 4 ++-- src/formatting.rs | 2 +- src/formatting/newline_style.rs | 2 +- src/items.rs | 4 ++-- src/lists.rs | 2 +- src/macros.rs | 19 ++++++++-------- src/modules.rs | 2 +- src/skip.rs | 12 +++++----- src/syntux/parser.rs | 4 ++-- src/syntux/session.rs | 14 +++++------- src/test/mod.rs | 36 +++++++++++++++--------------- 16 files changed, 72 insertions(+), 69 deletions(-) diff --git a/config_proc_macro/src/item_enum.rs b/config_proc_macro/src/item_enum.rs index dcee77a8549..6101e65d6e9 100644 --- a/config_proc_macro/src/item_enum.rs +++ b/config_proc_macro/src/item_enum.rs @@ -123,11 +123,11 @@ fn impl_from_str(ident: &syn::Ident, variants: &Variants) -> TokenStream { } fn doc_hint_of_variant(variant: &syn::Variant) -> String { - find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()) + find_doc_hint(&variant.attrs).unwrap_or_else(|| variant.ident.to_string()) } fn config_value_of_variant(variant: &syn::Variant) -> String { - find_config_value(&variant.attrs).unwrap_or(variant.ident.to_string()) + find_config_value(&variant.attrs).unwrap_or_else(|| variant.ident.to_string()) } fn impl_serde(ident: &syn::Ident, variants: &Variants) -> TokenStream { diff --git a/src/bin/main.rs b/src/bin/main.rs index 0335dc99116..b277b9323f1 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -235,7 +235,7 @@ fn execute(opts: &Options) -> Result { let file = PathBuf::from(path); let file = file.canonicalize().unwrap_or(file); - let (config, _) = load_config(Some(file.parent().unwrap()), Some(options.clone()))?; + let (config, _) = load_config(Some(file.parent().unwrap()), Some(options))?; let toml = config.all_options().to_toml()?; io::stdout().write_all(toml.as_bytes())?; @@ -590,7 +590,7 @@ impl GetOptsOptions { options.inline_config = matches .opt_strs("config") .iter() - .flat_map(|config| config.split(",")) + .flat_map(|config| config.split(',')) .map( |key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') { Some((middle, _)) => { diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 7c7e600b7d8..f2a345a9610 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -102,11 +102,11 @@ fn execute() -> i32 { if opts.version { return handle_command_status(get_rustfmt_info(&[String::from("--version")])); } - if opts.rustfmt_options.iter().any(|s| { - ["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str()) - || s.starts_with("--help=") - || s.starts_with("--print-config=") - }) { + if opts + .rustfmt_options + .iter() + .any(|s| is_status_options(s.as_str())) + { return handle_command_status(get_rustfmt_info(&opts.rustfmt_options)); } @@ -142,6 +142,12 @@ fn execute() -> i32 { } } +fn is_status_options(s: &str) -> bool { + ["--print-config", "-h", "--help", "-V", "--version"].contains(&s) + || s.starts_with("--help=") + || s.starts_with("--print-config=") +} + fn build_rustfmt_args(opts: &Opts, rustfmt_args: &mut Vec) -> Result<(), String> { let mut contains_check = false; let mut contains_emit_mode = false; @@ -285,9 +291,9 @@ impl Target { ) -> Self { let path = PathBuf::from(&target.src_path); let canonicalized = fs::canonicalize(&path).unwrap_or(path); - let test_files = nested_int_test_files.unwrap_or(vec![]); + let test_files = nested_int_test_files.unwrap_or_else(Vec::new); - Target { + Self { path: canonicalized, kind: target.kind[0].clone(), edition: target.edition.clone(), @@ -417,7 +423,7 @@ fn get_targets_root_only( .map(|p| p.targets) .flatten() .collect(), - PathBuf::from(current_dir_manifest), + current_dir_manifest, ), }; @@ -660,7 +666,7 @@ fn get_cargo_metadata( match cmd.exec() { Ok(metadata) => Ok(metadata), Err(_) => { - cmd.other_options(vec![]); + cmd.other_options(&[]); match cmd.exec() { Ok(metadata) => Ok(metadata), Err(error) => Err(io::Error::new(io::ErrorKind::Other, error.to_string())), diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 7e0d7751bed..432e9429242 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -271,7 +271,7 @@ macro_rules! create_config { } name_out.push_str(name_raw); name_out.push(' '); - let mut default_str = format!("{}", $def); + let mut default_str = $def.to_string(); if default_str.is_empty() { default_str = String::from("\"\""); } diff --git a/src/emitter/json.rs b/src/emitter/json.rs index 7c0f862cbc6..9cf37bf1289 100644 --- a/src/emitter/json.rs +++ b/src/emitter/json.rs @@ -136,7 +136,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); @@ -181,7 +181,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); @@ -206,7 +206,7 @@ mod tests { .unwrap(); let _ = emitter.emit_footer(&mut writer); assert_eq!(result.has_diff, false); - assert_eq!(&writer[..], "[]\n".as_bytes()); + assert_eq!(&writer[..], b"[]\n"); } #[test] diff --git a/src/expr.rs b/src/expr.rs index 181a1a61552..4f74372d521 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -600,7 +600,7 @@ pub(crate) fn rewrite_cond( String::from("\n") + &shape.indent.block_only().to_string(context.config); control_flow .rewrite_cond(context, shape, &alt_block_sep) - .and_then(|rw| Some(rw.0)) + .map(|rw| rw.0) }), } } @@ -835,7 +835,7 @@ impl<'a> ControlFlow<'a> { rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context) { if !self.connector.is_empty() && !comment.is_empty() { - if comment_style(&comment, false).is_line_comment() || comment.contains("\n") { + if comment_style(&comment, false).is_line_comment() || comment.contains('\n') { let newline = &pat_shape .indent .block_indent(context.config) diff --git a/src/formatting.rs b/src/formatting.rs index eb4f37d1ab2..da92992559e 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -91,7 +91,7 @@ fn format_project( let files = modules::ModResolver::new( &context.parse_session, directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaMod(true)), - !(input_is_stdin || !config.recursive()), + !input_is_stdin && config.recursive(), ) .visit_crate(&krate) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; diff --git a/src/formatting/newline_style.rs b/src/formatting/newline_style.rs index ac620094900..97c4fc16d6f 100644 --- a/src/formatting/newline_style.rs +++ b/src/formatting/newline_style.rs @@ -77,7 +77,7 @@ fn convert_to_windows_newlines(formatted_text: &String) -> String { transformed } -fn convert_to_unix_newlines(formatted_text: &String) -> String { +fn convert_to_unix_newlines(formatted_text: &str) -> String { formatted_text.replace(WINDOWS_NEWLINE, UNIX_NEWLINE) } diff --git a/src/items.rs b/src/items.rs index 1ecbdbceb9e..161997f969c 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1210,7 +1210,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> { let fits_single_line = !generic_bounds_str.contains('\n') && !where_str.contains('\n') - && generic_bounds_str.len() + where_str.len() + 1 <= shape.width; + && generic_bounds_str.len() + where_str.len() < shape.width; let space = if generic_bounds_str.is_empty() || where_str.is_empty() { Cow::from("") } else if fits_single_line { @@ -1998,7 +1998,7 @@ impl Rewrite for ast::Param { let num_attrs = self.attrs.len(); ( mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()), - param_attrs_result.contains("\n"), + param_attrs_result.contains('\n'), ) } else { (mk_sp(self.span.lo(), self.span.lo()), false) diff --git a/src/lists.rs b/src/lists.rs index 77c076540f1..8f98ab0747f 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -823,7 +823,7 @@ where pub(crate) fn total_item_width(item: &ListItem) -> usize { comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) - + &item.item.as_ref().map_or(0, |s| unicode_str_width(&s)) + + item.item.as_ref().map_or(0, |s| unicode_str_width(&s)) } fn comment_len(comment: Option<&str>) -> usize { diff --git a/src/macros.rs b/src/macros.rs index 5d27b485e1d..37016d2d76f 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -225,18 +225,17 @@ pub(crate) fn rewrite_macro( } fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { + let is_delim = |kind| match kind { + TokenKind::Eof | TokenKind::Comma | TokenKind::CloseDelim(DelimToken::NoDelim) => true, + _ => false, + }; for &keyword in RUST_KW.iter() { - if parser.token.is_keyword(keyword) - && parser.look_ahead(1, |t| { - t.kind == TokenKind::Eof - || t.kind == TokenKind::Comma - || t.kind == TokenKind::CloseDelim(DelimToken::NoDelim) - }) - { + if parser.token.is_keyword(keyword) && parser.look_ahead(1, |t| is_delim(t.kind.clone())) { parser.bump(); - let macro_arg = - MacroArg::Keyword(ast::Ident::with_dummy_span(keyword), parser.prev_span); - return Some(macro_arg); + return Some(MacroArg::Keyword( + ast::Ident::with_dummy_span(keyword), + parser.prev_span + )); } } None diff --git a/src/modules.rs b/src/modules.rs index 0c35cc2d073..bef70cde80e 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -67,7 +67,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { ) -> Result, String> { let root_filename = self.parse_sess.span_to_filename(krate.span); self.directory.path = match root_filename { - FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(), + FileName::Real(ref p) => p.parent().unwrap_or_else(|| Path::new("")).to_path_buf(), _ => PathBuf::new(), }; diff --git a/src/skip.rs b/src/skip.rs index 6b4e04a7173..7ebdc3d8b29 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -31,21 +31,21 @@ impl SkipContext { } } -static RUSTFMT: &'static str = "rustfmt"; -static SKIP: &'static str = "skip"; +static RUSTFMT: &str = "rustfmt"; +static SKIP: &str = "skip"; /// Say if you're playing with `rustfmt`'s skip attribute pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool { - if segments.len() < 2 || segments[0].ident.to_string() != RUSTFMT { + if segments.len() < 2 || segments[0].ident.as_str() != RUSTFMT { return false; } match segments.len() { - 2 => segments[1].ident.to_string() == SKIP, + 2 => segments[1].ident.as_str() == SKIP, 3 => { - segments[1].ident.to_string() == SKIP + segments[1].ident.as_str() == SKIP && ["macros", "attributes"] .iter() - .any(|&n| n == &segments[2].ident.name.as_str()) + .any(|&n| n == segments[2].ident.name.as_str()) } _ => false, } diff --git a/src/syntux/parser.rs b/src/syntux/parser.rs index b4da22f23ae..2253b54d817 100644 --- a/src/syntux/parser.rs +++ b/src/syntux/parser.rs @@ -26,7 +26,7 @@ impl<'a> Directory { fn to_syntax_directory(&'a self) -> syntax::parse::Directory<'a> { syntax::parse::Directory { path: Cow::Borrowed(&self.path), - ownership: self.ownership.clone(), + ownership: self.ownership, } } } @@ -209,7 +209,7 @@ impl<'a> Parser<'a> { } match Parser::parse_mod_items(&mut parser, lo) { - Ok(m) => Some(m.clone()), + Ok(m) => Some(m), Err(mut db) => { db.cancel(); sess.reset_errors(); diff --git a/src/syntux/session.rs b/src/syntux/session.rs index b1ae5e04871..e66d4b76f24 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -173,15 +173,13 @@ impl ParseSess { pub(crate) fn span_to_first_line_string(&self, span: Span) -> String { let file_lines = self.parse_sess.source_map().span_to_lines(span).ok(); - let first_line_str = match file_lines { + match file_lines { Some(fl) => fl .file .get_line(fl.lines[0].line_index) - .map(|s| s.into_owned()), - None => return String::new(), - }; - - first_line_str.unwrap_or(String::new()) + .map_or_else(String::new, |s| s.to_string()), + None => String::new(), + } } pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize { @@ -292,7 +290,7 @@ mod tests { message: vec![], children: vec![], suggestions: vec![], - span: span.unwrap_or_else(|| MultiSpan::new()), + span: span.unwrap_or_else(MultiSpan::new), } } @@ -307,7 +305,7 @@ mod tests { source_map.unwrap_or_else(|| Rc::new(SourceMap::new(FilePathMapping::empty()))); let ignore_path_set = Rc::new( IgnorePathSet::from_ignore_list( - &ignore_list.unwrap_or_else(|| IgnoreList::default()), + &ignore_list.unwrap_or_default(), ) .unwrap(), ); diff --git a/src/test/mod.rs b/src/test/mod.rs index a208b1d75b6..bb0d72ebff9 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -101,9 +101,9 @@ fn is_file_skip(path: &Path) -> bool { fn get_test_files(path: &Path, recursive: bool) -> Vec { let mut files = vec![]; if path.is_dir() { - for entry in fs::read_dir(path).expect(&format!( + for entry in fs::read_dir(path).unwrap_or_else(|_| panic!( "couldn't read directory {}", - path.to_str().unwrap() + path.display() )) { let entry = entry.expect("couldn't get `DirEntry`"); let path = entry.path(); @@ -118,9 +118,9 @@ fn get_test_files(path: &Path, recursive: bool) -> Vec { } fn verify_config_used(path: &Path, config_name: &str) { - for entry in fs::read_dir(path).expect(&format!( + for entry in fs::read_dir(path).unwrap_or_else(|_| panic!( "couldn't read {} directory", - path.to_str().unwrap() + path.display() )) { let entry = entry.expect("couldn't get directory entry"); let path = entry.path(); @@ -435,9 +435,9 @@ fn stdin_formatting_smoke_test() { } #[cfg(not(windows))] - assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes()); + assert_eq!(buf, b"stdin:\n\nfn main() {}\n"); #[cfg(windows)] - assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes()); + assert_eq!(buf, b"stdin:\n\nfn main() {}\r\n"); } #[test] @@ -459,7 +459,7 @@ fn stdin_parser_panic_caught() { fn stdin_works_with_modified_lines() { init_log(); let input = "\nfn\n some( )\n{\n}\nfn main () {}\n"; - let output = "1 6 2\nfn some() {}\nfn main() {}\n"; + let output = b"1 6 2\nfn some() {}\nfn main() {}\n"; let input = Input::Text(input.to_owned()); let mut config = Config::default(); @@ -475,7 +475,7 @@ fn stdin_works_with_modified_lines() { }; assert_eq!(session.errors, errors); } - assert_eq!(buf, output.as_bytes()); + assert_eq!(buf, output); } /// Ensures that `EmitMode::Json` works with input from `stdin`. @@ -510,8 +510,8 @@ fn stdin_disable_all_formatting_test() { // These tests require nightly. _ => return, } - let input = String::from("fn main() { println!(\"This should not be formatted.\"); }"); - let mut child = Command::new(rustfmt().to_str().unwrap()) + let input = "fn main() { println!(\"This should not be formatted.\"); }"; + let mut child = Command::new(rustfmt()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .arg("--config-path=./tests/config/disable_all_formatting.toml") @@ -890,8 +890,8 @@ fn make_temp_file(file_name: &'static str) -> TempFile { let path = Path::new(&target_dir).join(file_name); let mut file = File::create(&path).expect("couldn't create temp file"); - let content = "fn main() {}\n"; - file.write_all(content.as_bytes()) + let content = b"fn main() {}\n"; + file.write_all(content) .expect("couldn't write temp file"); TempFile { path } } @@ -933,9 +933,9 @@ fn verify_check_works() { init_log(); let temp_file = make_temp_file("temp_check.rs"); - Command::new(rustfmt().to_str().unwrap()) + Command::new(rustfmt()) .arg("--check") - .arg(temp_file.path.to_str().unwrap()) + .arg(&temp_file.path) .status() .expect("run with check option failed"); } @@ -944,7 +944,7 @@ fn verify_check_works() { fn verify_check_works_with_stdin() { init_log(); - let mut child = Command::new(rustfmt().to_str().unwrap()) + let mut child = Command::new(rustfmt()) .arg("--check") .stdin(Stdio::piped()) .stderr(Stdio::piped()) @@ -954,7 +954,7 @@ fn verify_check_works_with_stdin() { { let stdin = child.stdin.as_mut().expect("Failed to open stdin"); stdin - .write_all("fn main() {}\n".as_bytes()) + .write_all(b"fn main() {}\n") .expect("Failed to write to rustfmt --check"); } let output = child @@ -967,7 +967,7 @@ fn verify_check_works_with_stdin() { fn verify_check_l_works_with_stdin() { init_log(); - let mut child = Command::new(rustfmt().to_str().unwrap()) + let mut child = Command::new(rustfmt()) .arg("--check") .arg("-l") .stdin(Stdio::piped()) @@ -979,7 +979,7 @@ fn verify_check_l_works_with_stdin() { { let stdin = child.stdin.as_mut().expect("Failed to open stdin"); stdin - .write_all("fn main()\n{}\n".as_bytes()) + .write_all(b"fn main()\n{}\n") .expect("Failed to write to rustfmt --check"); } let output = child From 8822b25a9cdbe8464d6a36194959496d46892d96 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 17:37:10 +0700 Subject: [PATCH 3/8] use lazy_static to cache rustfmt's binary path --- src/test/mod.rs | 51 +++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/src/test/mod.rs b/src/test/mod.rs index bb0d72ebff9..5aa2c713301 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -903,29 +903,34 @@ impl Drop for TempFile { } } -fn rustfmt() -> PathBuf { - let mut me = env::current_exe().expect("failed to get current executable"); - // Chop of the test name. - me.pop(); - // Chop off `deps`. - me.pop(); - - // If we run `cargo test --release`, we might only have a release build. - if cfg!(release) { - // `../release/` - me.pop(); - me.push("release"); - } - me.push("rustfmt"); - assert!( - me.is_file() || me.with_extension("exe").is_file(), - if cfg!(release) { - "no rustfmt bin, try running `cargo build --release` before testing" - } else { - "no rustfmt bin, try running `cargo build` before testing" - } - ); - me +fn rustfmt() -> &'static Path { + lazy_static! { + static ref RUSTFMT_PATH: PathBuf = { + let mut me = env::current_exe().expect("failed to get current executable"); + // Chop of the test name. + me.pop(); + // Chop off `deps`. + me.pop(); + + // If we run `cargo test --release`, we might only have a release build. + if cfg!(release) { + // `../release/` + me.pop(); + me.push("release"); + } + me.push("rustfmt"); + assert!( + me.is_file() || me.with_extension("exe").is_file(), + if cfg!(release) { + "no rustfmt bin, try running `cargo build --release` before testing" + } else { + "no rustfmt bin, try running `cargo build` before testing" + } + ); + me + }; + } + &RUSTFMT_PATH } #[test] From 8a2141e8360f1b9b686c8fba782ac02c1a19ecae Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 06:55:58 +0700 Subject: [PATCH 4/8] update env_logger to 0.7 --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 769e019faf1..a0fa4a0c036 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -263,7 +263,7 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.6.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", @@ -803,7 +803,7 @@ dependencies = [ "cargo_metadata 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", "diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "dirs 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "getopts 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "ignore 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1138,7 +1138,7 @@ dependencies = [ "checksum dirs-sys 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "afa0b23de8fd801745c471deffa6e12d248f962c9fd4b4c33787b055599bde7b" "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" "checksum ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8944dc8fa28ce4a38f778bd46bf7d923fe73eed5a439398507246c8e017e6f36" -"checksum env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" +"checksum env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" "checksum failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" "checksum failure_derive 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0bc225b78e0391e4b8683440bf2e63c2deeeb2ce5189eab46e2b68c6d3725d08" "checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" diff --git a/Cargo.toml b/Cargo.toml index c654ebf36c6..831462032e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,7 @@ regex = "1.0" term = "0.6" diff = "0.1" log = "0.4" -env_logger = "0.6" +env_logger = "0.7" getopts = "0.2" cargo_metadata = "0.8" bytecount = "0.6" From 720ee50df42110b6f6a76e3c3ea9f6787129b3b1 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 06:58:02 +0700 Subject: [PATCH 5/8] update cargo_metadata to 0.9 --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a0fa4a0c036..bb765584d8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -130,7 +130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cargo_metadata" -version = "0.8.2" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -800,7 +800,7 @@ dependencies = [ "ansi_term 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", "anyhow 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", "bytecount 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cargo_metadata 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cargo_metadata 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", "diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "dirs 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1122,7 +1122,7 @@ dependencies = [ "checksum bstr 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8d6c2c5b58ab920a4f5aeaaca34b4488074e8cc7596af94e6f8c6ff247c60245" "checksum bytecount 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b0017894339f586ccb943b01b9555de56770c11cda818e7e3d8bd93f4ed7f46e" "checksum byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" -"checksum cargo_metadata 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "700b3731fd7d357223d0000f4dbf1808401b694609035c3c411fbc0cd375c426" +"checksum cargo_metadata 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "46e3374c604fb39d1a2f35ed5e4a4e30e60d01fab49446e08f1b3e9a90aef202" "checksum cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)" = "0213d356d3c4ea2c18c40b037c3be23cd639825c18f25ee670ac7813beeef99c" "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" diff --git a/Cargo.toml b/Cargo.toml index 831462032e6..a914f956cfe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ diff = "0.1" log = "0.4" env_logger = "0.7" getopts = "0.2" -cargo_metadata = "0.8" +cargo_metadata = "0.9" bytecount = "0.6" unicode-width = "0.1.5" unicode_categories = "0.1.1" From fc39046cfb33d472bf2c9e3f954c98ad4bff1aab Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 07:03:24 +0700 Subject: [PATCH 6/8] split long lines which cause formatting errors --- src/config/config_type.rs | 6 ++++-- src/config/mod.rs | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 432e9429242..a3d31610bc7 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -248,8 +248,10 @@ macro_rules! create_config { #[allow(unreachable_pub)] pub fn is_hidden_option(name: &str) -> bool { - const HIDE_OPTIONS: [&str; 6] = - ["verbose", "verbose_diff", "file_lines", "width_heuristics", "recursive", "print_misformatted_file_names"]; + const HIDE_OPTIONS: [&str; 6] = [ + "verbose", "verbose_diff", "file_lines", "width_heuristics", + "recursive", "print_misformatted_file_names", + ]; HIDE_OPTIONS.contains(&name) } diff --git a/src/config/mod.rs b/src/config/mod.rs index 621caa72aee..b0c99c049e3 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -513,7 +513,9 @@ mod test { Ok(_) => panic!("Expected configuration error"), Err(msg) => assert_eq!( msg, - "Error: Conflicting config options `skip_children` and `recursive` are both enabled. `skip_children` has been deprecated and should be removed from your config.", + "Error: Conflicting config options `skip_children` and `recursive` \ + are both enabled. `skip_children` has been deprecated and should be \ + removed from your config.", ), } } From 3f4f42ed6c939f1b3242916a15c520d84046d4ac Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 14:27:59 +0700 Subject: [PATCH 7/8] use Symbol comparison in SkipContext --- src/skip.rs | 73 +++++++++++++++++++++++++---------------------------- 1 file changed, 34 insertions(+), 39 deletions(-) diff --git a/src/skip.rs b/src/skip.rs index 7ebdc3d8b29..e21d407720d 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -1,6 +1,13 @@ //! Module that contains skip related stuffs. -use syntax::ast; +use syntax::ast::{Attribute, PathSegment}; +use syntax::symbol::{sym, Symbol}; + +macro_rules! sym { + ($tt:tt) => { + Symbol::intern(stringify!($tt)) + }; +} /// Take care of skip name stack. You can update it by attributes slice or /// by other context. Query this context to know if you need skip a block. @@ -11,13 +18,26 @@ pub(crate) struct SkipContext { } impl SkipContext { - pub(crate) fn update_with_attrs(&mut self, attrs: &[ast::Attribute]) { - self.macros.append(&mut get_skip_names("macros", attrs)); - self.attributes - .append(&mut get_skip_names("attributes", attrs)); + pub(crate) fn update_with_attrs(&mut self, attrs: &[Attribute]) { + fn get_skip_names(vs: &mut Vec, attr: &Attribute) { + if let Some(list) = attr.meta_item_list() { + for nested_meta_item in list { + if let Some(name) = nested_meta_item.ident() { + vs.push(name.to_string()); + } + } + } + } + for attr in attrs { + if is_skip_attr_with(&attr.item.path.segments, |s| s == sym!(macros)) { + get_skip_names(&mut self.macros, attr) + } else if is_skip_attr_with(&attr.item.path.segments, |s| s == sym::attributes) { + get_skip_names(&mut self.attributes, attr) + } + } } - pub(crate) fn update(&mut self, mut other: SkipContext) { + pub(crate) fn update(&mut self, mut other: Self) { self.macros.append(&mut other.macros); self.attributes.append(&mut other.attributes); } @@ -31,43 +51,18 @@ impl SkipContext { } } -static RUSTFMT: &str = "rustfmt"; -static SKIP: &str = "skip"; - /// Say if you're playing with `rustfmt`'s skip attribute -pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool { - if segments.len() < 2 || segments[0].ident.as_str() != RUSTFMT { +pub(crate) fn is_skip_attr(segments: &[PathSegment]) -> bool { + is_skip_attr_with(segments, |s| s == sym!(macros) || s == sym::attributes) +} + +fn is_skip_attr_with(segments: &[PathSegment], pred: impl FnOnce(Symbol) -> bool) -> bool { + if segments.len() < 2 || segments[0].ident.name != sym::rustfmt { return false; } match segments.len() { - 2 => segments[1].ident.as_str() == SKIP, - 3 => { - segments[1].ident.as_str() == SKIP - && ["macros", "attributes"] - .iter() - .any(|&n| n == segments[2].ident.name.as_str()) - } + 2 => segments[1].ident.name == sym!(skip), + 3 => segments[1].ident.name == sym!(skip) && pred(segments[2].ident.name), _ => false, } } - -fn get_skip_names(kind: &str, attrs: &[ast::Attribute]) -> Vec { - let mut skip_names = vec![]; - let path = format!("{}::{}::{}", RUSTFMT, SKIP, kind); - for attr in attrs { - // syntax::ast::Path is implemented partialEq - // but it is designed for segments.len() == 1 - if format!("{}", attr.path) != path { - continue; - } - - if let Some(list) = attr.meta_item_list() { - for nested_meta_item in list { - if let Some(name) = nested_meta_item.ident() { - skip_names.push(name.to_string()); - } - } - } - } - skip_names -} From 51e89ea8e1b1d67ecadd28d0777e25c70b3a8828 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Wed, 18 Dec 2019 07:32:04 +0000 Subject: [PATCH 8/8] run rustfmt on workspace --- src/macros.rs | 2 +- src/syntux/parser.rs | 1 - src/syntux/session.rs | 8 ++------ src/test/mod.rs | 17 +++++++---------- 4 files changed, 10 insertions(+), 18 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index 37016d2d76f..4fa62982e9f 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -234,7 +234,7 @@ fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { parser.bump(); return Some(MacroArg::Keyword( ast::Ident::with_dummy_span(keyword), - parser.prev_span + parser.prev_span, )); } } diff --git a/src/syntux/parser.rs b/src/syntux/parser.rs index 2253b54d817..ad38537d8d1 100644 --- a/src/syntux/parser.rs +++ b/src/syntux/parser.rs @@ -86,7 +86,6 @@ impl<'a> ParserBuilder<'a> { parser.cfg_mods = false; parser.recurse_into_file_modules = config.recursive(); - Ok(Parser { parser, sess }) } diff --git a/src/syntux/session.rs b/src/syntux/session.rs index e66d4b76f24..5d96d516783 100644 --- a/src/syntux/session.rs +++ b/src/syntux/session.rs @@ -303,12 +303,8 @@ mod tests { let emitter_writer = TestEmitter { num_emitted_errors }; let source_map = source_map.unwrap_or_else(|| Rc::new(SourceMap::new(FilePathMapping::empty()))); - let ignore_path_set = Rc::new( - IgnorePathSet::from_ignore_list( - &ignore_list.unwrap_or_default(), - ) - .unwrap(), - ); + let ignore_path_set = + Rc::new(IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap()); SilentOnIgnoredFilesEmitter { has_non_ignorable_parser_errors: false, source_map, diff --git a/src/test/mod.rs b/src/test/mod.rs index 5aa2c713301..ab156e39175 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -101,10 +101,9 @@ fn is_file_skip(path: &Path) -> bool { fn get_test_files(path: &Path, recursive: bool) -> Vec { let mut files = vec![]; if path.is_dir() { - for entry in fs::read_dir(path).unwrap_or_else(|_| panic!( - "couldn't read directory {}", - path.display() - )) { + for entry in fs::read_dir(path) + .unwrap_or_else(|_| panic!("couldn't read directory {}", path.display())) + { let entry = entry.expect("couldn't get `DirEntry`"); let path = entry.path(); if path.is_dir() && recursive { @@ -118,10 +117,9 @@ fn get_test_files(path: &Path, recursive: bool) -> Vec { } fn verify_config_used(path: &Path, config_name: &str) { - for entry in fs::read_dir(path).unwrap_or_else(|_| panic!( - "couldn't read {} directory", - path.display() - )) { + for entry in + fs::read_dir(path).unwrap_or_else(|_| panic!("couldn't read {} directory", path.display())) + { let entry = entry.expect("couldn't get directory entry"); let path = entry.path(); if path.extension().map_or(false, |f| f == "rs") { @@ -891,8 +889,7 @@ fn make_temp_file(file_name: &'static str) -> TempFile { let mut file = File::create(&path).expect("couldn't create temp file"); let content = b"fn main() {}\n"; - file.write_all(content) - .expect("couldn't write temp file"); + file.write_all(content).expect("couldn't write temp file"); TempFile { path } }