Remove empty list imports

This commit is contained in:
Marcus Klaas 2015-06-02 18:44:33 +02:00
parent b601ea2bc7
commit 27d6558964
2 changed files with 27 additions and 15 deletions

View file

@ -15,8 +15,6 @@ use syntax::ast;
use syntax::parse::token;
use syntax::print::pprust;
// TODO remove empty lists (if they're even possible)
// TODO (some day) remove unused imports, expand globs, compress many single imports into a list import
fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem, vis: &str) -> String {
@ -40,13 +38,14 @@ fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem, vis: &str)
impl<'a> FmtVisitor<'a> {
// Basically just pretty prints a multi-item import.
// Returns None when the import can be removed.
pub fn rewrite_use_list(&mut self,
block_indent: usize,
one_line_budget: usize, // excluding indentation
multi_line_budget: usize,
path: &ast::Path,
path_list: &[ast::PathListItem],
visibility: ast::Visibility) -> String {
visibility: ast::Visibility) -> Option<String> {
let path_str = pprust::path_to_string(path);
let vis = match visibility {
@ -54,8 +53,10 @@ impl<'a> FmtVisitor<'a> {
_ => ""
};
if path_list.len() == 1 {
return rewrite_single_use_list(path_str, path_list[0], vis);
match path_list.len() {
0 => return None,
1 => return Some(rewrite_single_use_list(path_str, path_list[0], vis)),
_ => ()
}
// 2 = ::
@ -110,10 +111,10 @@ impl<'a> FmtVisitor<'a> {
ast::PathListItem_::PathListMod{ .. } => None,
}
})).collect();
if path_str.len() == 0 {
Some(if path_str.len() == 0 {
format!("{}use {{{}}};", vis, write_list(&items, &fmt))
} else {
format!("{}use {}::{{{}}};", vis, path_str, write_list(&items, &fmt))
}
})
}
}

View file

@ -152,19 +152,30 @@ impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
match item.node {
ast::Item_::ItemUse(ref vp) => {
self.format_missing_with_indent(item.span.lo);
match vp.node {
ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
let block_indent = self.block_indent;
let one_line_budget = config!(max_width) - block_indent;
let multi_line_budget = config!(ideal_width) - block_indent;
let new_str = self.rewrite_use_list(block_indent,
one_line_budget,
multi_line_budget,
path,
path_list,
item.vis);
self.changes.push_str_span(item.span, &new_str);
let formatted = self.rewrite_use_list(block_indent,
one_line_budget,
multi_line_budget,
path,
path_list,
item.vis);
if let Some(new_str) = formatted {
self.format_missing_with_indent(item.span.lo);
self.changes.push_str_span(item.span, &new_str);
} else {
// Format up to last newline
let span = codemap::mk_sp(self.last_pos, item.span.lo);
let span_end = match self.snippet(span).rfind('\n') {
Some(offset) => self.last_pos + BytePos(offset as u32),
None => item.span.lo
};
self.format_missing(span_end);
}
self.last_pos = item.span.hi;
}
ast::ViewPath_::ViewPathGlob(_) => {