// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::cmp::{self, Ordering};
+use std::cmp::Ordering;
-use syntax::{ast, ptr};
+use config::lists::*;
+use syntax::ast;
use syntax::codemap::{BytePos, Span};
-use Shape;
use codemap::SpanUtils;
use config::IndentStyle;
-use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
- ListItem, Separator, SeparatorPlace, SeparatorTactic};
+use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
use rewrite::{Rewrite, RewriteContext};
+use shape::Shape;
use types::{rewrite_path, PathContext};
-use utils;
+use utils::{format_visibility, mk_sp};
use visitor::FmtVisitor;
-fn path_of(a: &ast::ViewPath_) -> &ast::Path {
- match *a {
- ast::ViewPath_::ViewPathSimple(_, ref p) => p,
- ast::ViewPath_::ViewPathGlob(ref p) => p,
- ast::ViewPath_::ViewPathList(ref p, _) => p,
- }
+/// Returns a name imported by a `use` declaration. e.g. returns `Ordering`
+/// for `std::cmp::Ordering` and `self` for `std::cmp::self`.
+pub fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
+ path.segments.last().unwrap().identifier
}
-fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
- a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
+pub fn same_rename(opt_ident: &Option<ast::Ident>, path: &ast::Path) -> bool {
+ opt_ident.map_or(true, |ident| path_to_imported_ident(path) == ident)
}
-fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
- for segment in a.segments.iter().zip(b.segments.iter()) {
- let ord = compare_path_segments(segment.0, segment.1);
- if ord != Ordering::Equal {
- return ord;
- }
- }
- a.segments.len().cmp(&b.segments.len())
-}
-
-fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
- let a_name_str = &*a.node.name.name.as_str();
- let b_name_str = &*b.node.name.name.as_str();
- let name_ordering = if a_name_str == "self" {
- if b_name_str == "self" {
- Ordering::Equal
- } else {
- Ordering::Less
- }
- } else {
- if b_name_str == "self" {
- Ordering::Greater
- } else {
- a_name_str.cmp(&b_name_str)
- }
- };
- if name_ordering == Ordering::Equal {
- match a.node.rename {
- Some(a_rename) => match b.node.rename {
- Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
- None => Ordering::Greater,
- },
- None => Ordering::Less,
- }
+fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
+ if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
+ let path = &ast::Path {
+ span: path.span,
+ segments: path.segments[..path.segments.len() - 1].to_owned(),
+ };
+ rewrite_path(context, PathContext::Import, None, path, shape)
} else {
- name_ordering
+ rewrite_path(context, PathContext::Import, None, path, shape)
}
}
-fn compare_path_list_item_lists(
- a_items: &Vec<ast::PathListItem>,
- b_items: &Vec<ast::PathListItem>,
-) -> Ordering {
- let mut a = a_items.clone();
- let mut b = b_items.clone();
- a.sort_by(|a, b| compare_path_list_items(a, b));
- b.sort_by(|a, b| compare_path_list_items(a, b));
- for comparison_pair in a.iter().zip(b.iter()) {
- let ord = compare_path_list_items(comparison_pair.0, comparison_pair.1);
- if ord != Ordering::Equal {
- return ord;
- }
- }
- a.len().cmp(&b.len())
-}
+impl Rewrite for ast::UseTree {
+ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+ match self.kind {
+ ast::UseTreeKind::Nested(ref items) => {
+ rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
+ }
+ ast::UseTreeKind::Glob => {
+ let prefix_shape = shape.sub_width(3)?;
-fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
- use syntax::ast::ViewPath_::*;
- match (a, b) {
- (&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
- (&ViewPathSimple(..), _) => Ordering::Less,
- (&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
- (&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
- (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
- (&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
- compare_path_list_item_lists(a_items, b_items)
+ if !self.prefix.segments.is_empty() {
+ let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
+ Some(format!("{}::*", path_str))
+ } else {
+ Some("*".to_owned())
+ }
+ }
+ ast::UseTreeKind::Simple(opt_ident) => {
+ if same_rename(&opt_ident, &self.prefix) {
+ rewrite_prefix(&self.prefix, context, shape)
+ .or_else(|| Some(context.snippet(self.prefix.span).to_owned()))
+ } else {
+ let ident_str = opt_ident?.to_string();
+ // 4 = " as ".len()
+ let prefix_shape = shape.sub_width(ident_str.len() + 4)?;
+ let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)
+ .unwrap_or_else(|| context.snippet(self.prefix.span).to_owned());
+ Some(format!("{} as {}", path_str, ident_str))
+ }
+ }
}
- (&ViewPathList(..), _) => Ordering::Greater,
}
}
-fn compare_view_paths(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
- match compare_paths(path_of(a), path_of(b)) {
- Ordering::Equal => compare_view_path_types(a, b),
- cmp => cmp,
- }
+fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
+ attrs.is_empty() && is_unused_import_inner(tree)
}
-fn compare_use_items(context: &RewriteContext, a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
- match (&a.node, &b.node) {
- (&ast::ItemKind::Use(ref a_vp), &ast::ItemKind::Use(ref b_vp)) => {
- Some(compare_view_paths(&a_vp.node, &b_vp.node))
- }
- (&ast::ItemKind::ExternCrate(..), &ast::ItemKind::ExternCrate(..)) => {
- Some(context.snippet(a.span).cmp(&context.snippet(b.span)))
- }
- _ => None,
+fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
+ match tree.kind {
+ ast::UseTreeKind::Nested(ref items) => match items.len() {
+ 0 => true,
+ 1 => is_unused_import_inner(&items[0].0),
+ _ => false,
+ },
+ _ => false,
}
}
-// TODO (some day) remove unused imports, expand globs, compress many single
-// imports into a list import.
-
-fn rewrite_view_path_prefix(
- path: &ast::Path,
+// Rewrite `use foo;` WITHOUT attributes.
+pub fn rewrite_import(
context: &RewriteContext,
+ vis: &ast::Visibility,
+ tree: &ast::UseTree,
+ attrs: &[ast::Attribute],
shape: Shape,
) -> Option<String> {
- let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
- path.segments.len() > 1
- {
- let path = &ast::Path {
- span: path.span.clone(),
- segments: path.segments[..path.segments.len() - 1].to_owned(),
- };
- try_opt!(rewrite_path(
- context,
- PathContext::Import,
- None,
- path,
- shape,
- ))
- } else {
- try_opt!(rewrite_path(
- context,
- PathContext::Import,
- None,
- path,
- shape,
- ))
- };
- Some(path_str)
-}
-
-impl Rewrite for ast::ViewPath {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- match self.node {
- ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
- rewrite_use_list(shape, path, path_list, self.span, context)
- }
- ast::ViewPath_::ViewPathGlob(ref path) => {
- // 4 = "::*".len()
- let prefix_shape = try_opt!(shape.sub_width(3));
- let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
- Some(format!("{}::*", path_str))
- }
- ast::ViewPath_::ViewPathSimple(ident, ref path) => {
- let ident_str = ident.to_string();
- // 4 = " as ".len()
- let prefix_shape = try_opt!(shape.sub_width(ident_str.len() + 4));
- let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
-
- Some(if path.segments.last().unwrap().identifier == ident {
- path_str
- } else {
- format!("{} as {}", path_str, ident_str)
- })
+ let vis = format_visibility(vis);
+ // 4 = `use `, 1 = `;`
+ let rw = shape
+ .offset_left(vis.len() + 4)
+ .and_then(|shape| shape.sub_width(1))
+ .and_then(|shape| {
+ // If we have an empty nested group with no attributes, we erase it
+ if is_unused_import(tree, attrs) {
+ Some("".to_owned())
+ } else {
+ tree.rewrite(context, shape)
}
- }
+ });
+ match rw {
+ Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
+ _ => rw,
}
}
impl<'a> FmtVisitor<'a> {
- pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
- // Find the location immediately before the first use item in the run. This must not lie
- // before the current `self.last_pos`
- let pos_before_first_use_item = use_items
- .first()
- .map(|p_i| {
- cmp::max(
- self.last_pos,
- p_i.attrs
- .iter()
- .map(|attr| attr.span.lo())
- .min()
- .unwrap_or(p_i.span.lo()),
- )
- })
- .unwrap_or(self.last_pos);
- // Construct a list of pairs, each containing a `use` item and the start of span before
- // that `use` item.
- let mut last_pos_of_prev_use_item = pos_before_first_use_item;
- let mut ordered_use_items = use_items
- .iter()
- .map(|p_i| {
- let new_item = (&*p_i, last_pos_of_prev_use_item);
- last_pos_of_prev_use_item = p_i.span.hi();
- new_item
- })
- .collect::<Vec<_>>();
- let pos_after_last_use_item = last_pos_of_prev_use_item;
- // Order the imports by view-path & other import path properties
- ordered_use_items.sort_by(|a, b| {
- compare_use_items(&self.get_context(), a.0, b.0).unwrap()
- });
- // First, output the span before the first import
- let prev_span_str = self.snippet(utils::mk_sp(self.last_pos, pos_before_first_use_item));
- // Look for purely trailing space at the start of the prefix snippet before a linefeed, or
- // a prefix that's entirely horizontal whitespace.
- let prefix_span_start = match prev_span_str.find('\n') {
- Some(offset) if prev_span_str[..offset].trim().is_empty() => {
- self.last_pos + BytePos(offset as u32)
- }
- None if prev_span_str.trim().is_empty() => pos_before_first_use_item,
- _ => self.last_pos,
- };
- // Look for indent (the line part preceding the use is all whitespace) and excise that
- // from the prefix
- let span_end = match prev_span_str.rfind('\n') {
- Some(offset) if prev_span_str[offset..].trim().is_empty() => {
- self.last_pos + BytePos(offset as u32)
- }
- _ => pos_before_first_use_item,
- };
-
- self.last_pos = prefix_span_start;
- self.format_missing(span_end);
- for ordered in ordered_use_items {
- // Fake out the formatter by setting `self.last_pos` to the appropriate location before
- // each item before visiting it.
- self.last_pos = ordered.1;
- self.visit_item(ordered.0);
- }
- self.last_pos = pos_after_last_use_item;
- }
-
- pub fn format_import(
- &mut self,
- vis: &ast::Visibility,
- vp: &ast::ViewPath,
- span: Span,
- attrs: &[ast::Attribute],
- ) {
- let vis = utils::format_visibility(vis);
- // 4 = `use `, 1 = `;`
- let rw = self.shape()
- .offset_left(vis.len() + 4)
- .and_then(|shape| shape.sub_width(1))
- .and_then(|shape| match vp.node {
- // If we have an empty path list with no attributes, we erase it
- ast::ViewPath_::ViewPathList(_, ref path_list)
- if path_list.is_empty() && attrs.is_empty() =>
- {
- Some("".into())
- }
- _ => vp.rewrite(&self.get_context(), shape),
- });
+ pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
+ let span = item.span;
+ let shape = self.shape();
+ let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
match rw {
Some(ref s) if s.is_empty() => {
// Format up to last newline
- let prev_span = utils::mk_sp(self.last_pos, source!(self, span).lo());
- let span_end = match self.snippet(prev_span).rfind('\n') {
- Some(offset) => self.last_pos + BytePos(offset as u32),
- None => source!(self, span).lo(),
- };
+ let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
+ let trimmed_snippet = self.snippet(prev_span).trim_right();
+ let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
self.format_missing(span_end);
+ // We have an excessive newline from the removed import.
+ if self.buffer.ends_with('\n') {
+ self.buffer.pop();
+ self.line_number -= 1;
+ }
self.last_pos = source!(self, span).hi();
}
Some(ref s) => {
- let s = format!("{}use {};", vis, s);
self.format_missing_with_indent(source!(self, span).lo());
- self.buffer.push_str(&s);
+ self.push_str(s);
self.last_pos = source!(self, span).hi();
}
None => {
}
}
-fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
- let mut item_str = vpi.node.name.to_string();
- if item_str == "self" {
- item_str = "".to_owned();
- }
- let path_item_str = if path_str.is_empty() {
- if item_str.is_empty() {
- "self".to_owned()
- } else {
- item_str
- }
- } else if item_str.is_empty() {
- path_str
- } else {
- format!("{}::{}", path_str, item_str)
- };
- append_alias(path_item_str, vpi)
-}
-
-fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
- Some(append_alias(vpi.node.name.to_string(), vpi))
-}
+fn rewrite_nested_use_tree_single(
+ context: &RewriteContext,
+ path_str: &str,
+ tree: &ast::UseTree,
+ shape: Shape,
+) -> Option<String> {
+ match tree.kind {
+ ast::UseTreeKind::Simple(opt_rename) => {
+ let mut item_str = rewrite_prefix(&tree.prefix, context, shape)?;
+ if item_str == "self" {
+ item_str = "".to_owned();
+ }
-fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
- match vpi.node.rename {
- Some(rename) => format!("{} as {}", path_item_str, rename),
- None => path_item_str,
+ let path_item_str = if path_str.is_empty() {
+ if item_str.is_empty() {
+ "self".to_owned()
+ } else {
+ item_str
+ }
+ } else if item_str.is_empty() {
+ path_str.to_owned()
+ } else {
+ format!("{}::{}", path_str, item_str)
+ };
+
+ Some(if same_rename(&opt_rename, &tree.prefix) {
+ path_item_str
+ } else {
+ format!("{} as {}", path_item_str, opt_rename?)
+ })
+ }
+ ast::UseTreeKind::Glob | ast::UseTreeKind::Nested(..) => {
+ // 2 = "::"
+ let nested_shape = shape.offset_left(path_str.len() + 2)?;
+ tree.rewrite(context, nested_shape)
+ .map(|item| format!("{}::{}", path_str, item))
+ }
}
}
fn to_str(&self) -> Option<&str> {
match *self {
- ImportItem::SelfImport(s) |
- ImportItem::SnakeCase(s) |
- ImportItem::CamelCase(s) |
- ImportItem::AllCaps(s) => Some(s),
+ ImportItem::SelfImport(s)
+ | ImportItem::SnakeCase(s)
+ | ImportItem::CamelCase(s)
+ | ImportItem::AllCaps(s) => Some(s),
ImportItem::Invalid => None,
}
}
// Pretty prints a multi-item import.
// If the path list is empty, it leaves the braces empty.
-fn rewrite_use_list(
+fn rewrite_nested_use_tree(
shape: Shape,
path: &ast::Path,
- path_list: &[ast::PathListItem],
+ trees: &[(ast::UseTree, ast::NodeId)],
span: Span,
context: &RewriteContext,
) -> Option<String> {
// Returns a different option to distinguish `::foo` and `foo`
- let path_str = try_opt!(rewrite_path(
- context,
- PathContext::Import,
- None,
- path,
- shape,
- ));
-
- match path_list.len() {
+ let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
+
+ match trees.len() {
0 => {
+ let shape = shape.offset_left(path_str.len() + 3)?;
return rewrite_path(context, PathContext::Import, None, path, shape)
.map(|path_str| format!("{}::{{}}", path_str));
}
- 1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
+ 1 => {
+ return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
+ }
_ => (),
}
// 2 = "{}"
let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
+ let nested_indent = match context.config.imports_indent() {
+ IndentStyle::Block => shape.indent.block_indent(context.config),
+ // 1 = `{`
+ IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
+ };
+
+ let nested_shape = match context.config.imports_indent() {
+ IndentStyle::Block => Shape::indented(nested_indent, context.config).sub_width(1)?,
+ IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
+ };
let mut items = {
// Dummy value, see explanation below.
let mut items = vec![ListItem::from_str("")];
let iter = itemize_list(
- context.codemap,
- path_list.iter(),
+ context.snippet_provider,
+ trees.iter().map(|tree| &tree.0),
"}",
- |vpi| vpi.span.lo(),
- |vpi| vpi.span.hi(),
- rewrite_path_item,
- context.codemap.span_after(span, "{"),
+ ",",
+ |tree| tree.span.lo(),
+ |tree| tree.span.hi(),
+ |tree| tree.rewrite(context, nested_shape),
+ context.snippet_provider.span_after(span, "{"),
span.hi(),
false,
);
remaining_width,
);
- let nested_indent = match context.config.imports_indent() {
- IndentStyle::Block => shape.indent.block_indent(context.config),
- // 1 = `{`
- IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
- };
-
- let nested_shape = match context.config.imports_indent() {
- IndentStyle::Block => Shape::indented(nested_indent, context.config),
- IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
- };
-
- let ends_with_newline = context.config.imports_indent() == IndentStyle::Block &&
- tactic != DefinitiveListTactic::Horizontal;
+ let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
+ && tactic != DefinitiveListTactic::Horizontal;
let fmt = ListFormatting {
- tactic: tactic,
+ tactic,
separator: ",",
trailing_separator: if ends_with_newline {
context.config.trailing_comma()
},
separator_place: SeparatorPlace::Back,
shape: nested_shape,
- ends_with_newline: ends_with_newline,
+ ends_with_newline,
preserve_newline: true,
config: context.config,
};
- let list_str = try_opt!(write_list(&items[first_index..], &fmt));
+ let list_str = write_list(&items[first_index..], &fmt)?;
let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
{