Merge pull request #142 from cassiersg/rewrite-imports

Move 'use' to Rewrite
This commit is contained in:
Nick Cameron 2015-07-26 09:03:56 +12:00
commit 0f3848471d
7 changed files with 167 additions and 152 deletions

View File

@ -608,7 +608,7 @@ fn rewrite_binary_op(context: &RewriteContext,
result.push_str(&operator_str);
// 1 = space between operator and rhs
let used_width = result.len() + operator_str.len() + 1;
let used_width = result.len() + 1;
let remaining_width = match result.rfind('\n') {
Some(idx) => (offset + width + idx).checked_sub(used_width).unwrap_or(0),
None => width.checked_sub(used_width).unwrap_or(0)

View File

@ -8,54 +8,76 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use visitor::FmtVisitor;
use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
use utils::{span_after, format_visibility};
use utils::span_after;
use rewrite::{Rewrite, RewriteContext};
use config::Config;
use syntax::ast;
use syntax::parse::token;
use syntax::print::pprust;
use syntax::codemap::Span;
use syntax::codemap::{CodeMap, Span};
// 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 {
if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
let name_str = token::get_ident(name).to_string();
if path_str.len() == 0 {
format!("{}use {};", vis, name_str)
} else {
format!("{}use {}::{};", vis, path_str, name_str)
impl Rewrite for ast::ViewPath {
// Returns an empty string when the ViewPath is empty (like foo::bar::{})
fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
match self.node {
ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
Some(rewrite_use_list(width,
offset,
path,
path_list,
self.span,
context.codemap,
context.config).unwrap_or("".to_owned()))
}
ast::ViewPath_::ViewPathGlob(_) => {
// FIXME convert to list?
None
}
ast::ViewPath_::ViewPathSimple(_,_) => {
None
}
} else {
if path_str.len() != 0 {
format!("{}use {};", vis, path_str)
} else {
// This catches the import: use {self}, which is a compiler error, so we just
// leave it alone.
format!("{}use {{self}};", vis)
}
}
}
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(&self,
block_indent: usize,
one_line_budget: usize, // excluding indentation
multi_line_budget: usize,
fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem) -> String {
if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
let name_str = token::get_ident(name).to_string();
if path_str.len() == 0 {
name_str
} else {
format!("{}::{}", path_str, name_str)
}
} else {
if path_str.len() != 0 {
path_str
} else {
// This catches the import: use {self}, which is a compiler error, so we just
// leave it alone.
"{self}".to_owned()
}
}
}
// Basically just pretty prints a multi-item import.
// Returns None when the import can be removed.
pub fn rewrite_use_list(width: usize,
offset: usize,
path: &ast::Path,
path_list: &[ast::PathListItem],
visibility: ast::Visibility,
span: Span)
span: Span,
codemap: &CodeMap,
config: &Config)
-> Option<String> {
let path_str = pprust::path_to_string(path);
let vis = format_visibility(visibility);
match path_list.len() {
0 => return None,
1 => return Some(rewrite_single_use_list(path_str, path_list[0], vis)),
1 => return Some(rewrite_single_use_list(path_str, path_list[0])),
_ => ()
}
@ -65,27 +87,25 @@ pub fn rewrite_use_list(&self,
} else {
0
};
// 5 = "use " + {
let indent = path_str.len() + 5 + path_separation_w + vis.len();
// 2 = } + ;
let used_width = indent + 2;
// Break as early as possible when we've blown our budget.
let remaining_line_budget = one_line_budget.checked_sub(used_width).unwrap_or(0);
let remaining_multi_budget = multi_line_budget.checked_sub(used_width).unwrap_or(0);
// 1 = {
let supp_indent = path_str.len() + path_separation_w + 1;
// 1 = }
let remaining_width = width.checked_sub(supp_indent + 1).unwrap_or(0);
let fmt = ListFormatting {
tactic: ListTactic::Mixed,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: block_indent + indent,
h_width: remaining_line_budget,
v_width: remaining_multi_budget,
indent: offset + supp_indent,
h_width: remaining_width,
// FIXME This is too conservative, and will not use all width
// available
// (loose 1 column (";"))
v_width: remaining_width,
ends_with_newline: true,
};
let mut items = itemize_list(self.codemap,
let mut items = itemize_list(codemap,
vec![ListItem::from_str("")], /* Dummy value, explanation
* below */
path_list.iter(),
@ -101,7 +121,7 @@ pub fn rewrite_use_list(&self,
"self".to_owned()
}
},
span_after(span, "{", self.codemap),
span_after(span, "{", codemap),
span.hi);
// We prefixed the item list with a dummy value so that we can
@ -116,18 +136,17 @@ pub fn rewrite_use_list(&self,
1
};
if self.config.reorder_imports {
if config.reorder_imports {
items[1..].sort_by(|a, b| a.item.cmp(&b.item));
}
let list = write_list(&items[first_index..], &fmt);
Some(if path_str.len() == 0 {
format!("{}use {{{}}};", vis, list)
format!("{{{}}}", list)
} else {
format!("{}use {}::{{{}}};", vis, path_str, list)
format!("{}::{{{}}}", path_str, list)
})
}
}
// Returns true when self item was found.

View File

@ -164,43 +164,7 @@ fn visit_item(&mut self, item: &'v ast::Item) {
match item.node {
ast::Item_::ItemUse(ref vp) => {
match vp.node {
ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
let block_indent = self.block_indent;
let one_line_budget = self.config.max_width - block_indent;
let multi_line_budget = self.config.ideal_width - block_indent;
let formatted = self.rewrite_use_list(block_indent,
one_line_budget,
multi_line_budget,
path,
path_list,
item.vis,
item.span);
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(_) => {
self.format_missing_with_indent(item.span.lo);
// FIXME convert to list?
}
ast::ViewPath_::ViewPathSimple(_,_) => {
self.format_missing_with_indent(item.span.lo);
}
}
visit::walk_item(self, item);
self.format_import(item.vis, vp, item.span);
}
ast::Item_::ItemImpl(..) |
ast::Item_::ItemTrait(..) => {
@ -221,7 +185,6 @@ fn visit_item(&mut self, item: &'v ast::Item) {
def,
generics,
item.span);
self.last_pos = item.span.hi;
}
ast::Item_::ItemEnum(ref def, ref generics) => {
self.format_missing_with_indent(item.span.lo);
@ -418,4 +381,37 @@ fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
self.last_pos = last_pos;
self.block_indent = block_indent;
}
fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
let vis = utils::format_visibility(vis);
let offset = self.block_indent + vis.len() + "use ".len();
let context = RewriteContext {
codemap: self.codemap,
config: self.config,
block_indent: self.block_indent,
};
// 1 = ";"
match vp.rewrite(&context, self.config.max_width - offset - 1, offset) {
Some(ref s) if s.len() == 0 => {
// Format up to last newline
let prev_span = codemap::mk_sp(self.last_pos, span.lo);
let span_end = match self.snippet(prev_span).rfind('\n') {
Some(offset) => self.last_pos + BytePos(offset as u32),
None => span.lo
};
self.format_missing(span_end);
self.last_pos = span.hi;
}
Some(ref s) => {
let s = format!("{}use {};", vis, s);
self.format_missing_with_indent(span.lo);
self.changes.push_str_span(span, &s);
self.last_pos = span.hi;
}
None => {
self.format_missing_with_indent(span.lo);
self.format_missing(span.hi);
}
}
}
}

View File

@ -7,6 +7,7 @@ fn foo() -> bool {
let very_long_variable_name = ( a + first + simple + test );
let very_long_variable_name = (a + first + simple + test + AAAAAAAAAAAAA + BBBBBBBBBBBBBBBBB + b + c);
//FIXME this exceeds width limit. Needs assignments reformatting
let is_internalxxxx = self.codemap.span_to_filename(s) == self.codemap.span_to_filename(m.inner);
let some_val = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * bbbb / (bbbbbb -

View File

@ -8,8 +8,8 @@ fn foo() -> bool {
let very_long_variable_name = (a + first + simple + test + AAAAAAAAAAAAA + BBBBBBBBBBBBBBBBB +
b + c);
let is_internalxxxx = self.codemap.span_to_filename(s) ==
self.codemap.span_to_filename(m.inner);
//FIXME this exceeds width limit. Needs assignments reformatting
let is_internalxxxx = self.codemap.span_to_filename(s) == self.codemap.span_to_filename(m.inner);
let some_val = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * bbbb /
(bbbbbb - function_call(x, *very_long_pointer, y)) + 1000;

View File

@ -23,8 +23,8 @@ mod Foo {
pub use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
mod Foo2 {
pub use syntax::ast::{self, ItemForeignMod, ItemImpl, ItemMac, ItemMod,
ItemStatic, ItemDefaultImpl};
pub use syntax::ast::{self, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic,
ItemDefaultImpl};
}
}

View File

@ -14,10 +14,9 @@
extern crate foo;
use std::cell::*;
use std::{self, any, ascii, borrow, boxed, char, borrow, boxed, char, borrow,
borrow, boxed, char, borrow, boxed, char, borrow, boxed, char,
borrow, boxed, char, borrow, boxed, char, borrow, boxed, char,
borrow, boxed, char, borrow, boxed, char};
use std::{self, any, ascii, borrow, boxed, char, borrow, boxed, char, borrow, borrow, boxed, char,
borrow, boxed, char, borrow, boxed, char, borrow, boxed, char, borrow, boxed, char,
borrow, boxed, char, borrow, boxed, char, borrow, boxed, char};
mod doc;
mod other;