Skip to content

Some minor cleanup #3970

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 8 commits into from
Dec 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ 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"
cargo_metadata = "0.9"
bytecount = "0.6"
unicode-width = "0.1.5"
unicode_categories = "0.1.1"
Expand Down
4 changes: 2 additions & 2 deletions config_proc_macro/src/item_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ fn execute(opts: &Options) -> Result<i32> {
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())?;

Expand Down Expand Up @@ -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, _)) => {
Expand Down
24 changes: 15 additions & 9 deletions src/cargo-fmt/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down Expand Up @@ -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<String>) -> Result<(), String> {
let mut contains_check = false;
let mut contains_emit_mode = false;
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -417,7 +423,7 @@ fn get_targets_root_only(
.map(|p| p.targets)
.flatten()
.collect(),
PathBuf::from(current_dir_manifest),
current_dir_manifest,
),
};

Expand Down Expand Up @@ -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())),
Expand Down
26 changes: 14 additions & 12 deletions src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)";
Expand Down Expand Up @@ -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)
}

Expand All @@ -271,7 +273,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("\"\"");
}
Expand Down Expand Up @@ -322,19 +324,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),
Expand Down
4 changes: 3 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
),
}
}
Expand Down
6 changes: 3 additions & 3 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 All @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}),
}
}
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ fn format_project<T: FormatHandler>(
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))?;
Expand Down
2 changes: 1 addition & 1 deletion src/formatting/newline_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
4 changes: 2 additions & 2 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
19 changes: 9 additions & 10 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,18 +225,17 @@ pub(crate) fn rewrite_macro(
}

fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
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
Expand Down
2 changes: 1 addition & 1 deletion src/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
) -> Result<FileModMap<'ast>, 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(),
};

Expand Down
Loading