]> git.lizzy.rs Git - rust.git/blobdiff - src/imports.rs
Fix libsyntax updates
[rust.git] / src / imports.rs
index f38e41eca8942ae3ceba5f1c814d4ea2e78afaa2..f631f4b9c2667e32df2bd64267502b0374006d11 100644 (file)
 
 use std::cmp::Ordering;
 
+use config::lists::*;
 use syntax::ast;
 use syntax::codemap::{BytePos, Span};
 
-use spanned::Spanned;
 use codemap::SpanUtils;
-use comment::combine_strs_with_missing_comments;
 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::{format_visibility, mk_sp};
-use visitor::{rewrite_extern_crate, FmtVisitor};
+use visitor::FmtVisitor;
 
-fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
-    a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
+/// 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_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())
+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_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
-    use ast::UseTreeKind::*;
-
-    // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
-    // fully added
-    if !nested {
-        let paths_cmp = compare_paths(&a.prefix, &b.prefix);
-        if paths_cmp != Ordering::Equal {
-            return paths_cmp;
-        }
-    }
-
-    match (&a.kind, &b.kind) {
-        (&Simple(ident_a), &Simple(ident_b)) => {
-            let name_a = &*a.prefix.segments.last().unwrap().identifier.name.as_str();
-            let name_b = &*b.prefix.segments.last().unwrap().identifier.name.as_str();
-            let name_ordering = if name_a == "self" {
-                if name_b == "self" {
-                    Ordering::Equal
-                } else {
-                    Ordering::Less
-                }
-            } else if name_b == "self" {
-                Ordering::Greater
-            } else {
-                name_a.cmp(name_b)
-            };
-            if name_ordering == Ordering::Equal {
-                if ident_a.name.as_str() != name_a {
-                    if ident_b.name.as_str() != name_b {
-                        ident_a.name.as_str().cmp(&ident_b.name.as_str())
-                    } else {
-                        Ordering::Greater
-                    }
-                } else {
-                    Ordering::Less
-                }
-            } else {
-                name_ordering
-            }
-        }
-        (&Glob, &Glob) => Ordering::Equal,
-        (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
-        (&Nested(ref a_items), &Nested(ref b_items)) => {
-            let mut a = a_items
-                .iter()
-                .map(|&(ref tree, _)| tree.clone())
-                .collect::<Vec<_>>();
-            let mut b = b_items
-                .iter()
-                .map(|&(ref tree, _)| tree.clone())
-                .collect::<Vec<_>>();
-            a.sort_by(|a, b| compare_use_trees(a, b, true));
-            b.sort_by(|a, b| compare_use_trees(a, b, true));
-            for comparison_pair in a.iter().zip(b.iter()) {
-                let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
-                if ord != Ordering::Equal {
-                    return ord;
-                }
-            }
-            a.len().cmp(&b.len())
-        }
-        (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
-    }
-}
-
-fn compare_use_items(context: &RewriteContext, a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
-    match (&a.node, &b.node) {
-        (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
-            Some(compare_use_trees(&a_tree, &b_tree, false))
-        }
-        (&ast::ItemKind::ExternCrate(..), &ast::ItemKind::ExternCrate(..)) => {
-            Some(context.snippet(a.span).cmp(&context.snippet(b.span)))
-        }
-        _ => None,
-    }
-}
-
-// TODO (some day) remove unused imports, expand globs, compress many single
-// imports into a list import.
-
 fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
-    let path_str = if path.segments.last().unwrap().identifier.to_string() == "self"
-        && path.segments.len() > 1
-    {
+    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)?
+        rewrite_path(context, PathContext::Import, None, path, shape)
     } else {
-        rewrite_path(context, PathContext::Import, None, path, shape)?
-    };
-    Some(path_str)
+        rewrite_path(context, PathContext::Import, None, path, shape)
+    }
 }
 
 impl Rewrite for ast::UseTree {
@@ -144,23 +54,23 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             ast::UseTreeKind::Glob => {
                 let prefix_shape = shape.sub_width(3)?;
 
-                if self.prefix.segments.len() > 0 {
+                if !self.prefix.segments.is_empty() {
                     let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
                     Some(format!("{}::*", path_str))
                 } else {
-                    Some("*".into())
+                    Some("*".to_owned())
                 }
             }
-            ast::UseTreeKind::Simple(ident) => {
-                let ident_str = 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)?;
-
-                if self.prefix.segments.last().unwrap().identifier == ident {
-                    Some(path_str)
+            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))
                 }
             }
@@ -168,8 +78,23 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
     }
 }
 
+fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
+    attrs.is_empty() && is_unused_import_inner(tree)
+}
+
+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,
+    }
+}
+
 // Rewrite `use foo;` WITHOUT attributes.
-fn rewrite_import(
+pub fn rewrite_import(
     context: &RewriteContext,
     vis: &ast::Visibility,
     tree: &ast::UseTree,
@@ -181,12 +106,13 @@ fn rewrite_import(
     let rw = shape
         .offset_left(vis.len() + 4)
         .and_then(|shape| shape.sub_width(1))
-        .and_then(|shape| match tree.kind {
+        .and_then(|shape| {
             // If we have an empty nested group with no attributes, we erase it
-            ast::UseTreeKind::Nested(ref items) if items.is_empty() && attrs.is_empty() => {
-                Some("".into())
+            if is_unused_import(tree, attrs) {
+                Some("".to_owned())
+            } else {
+                tree.rewrite(context, shape)
             }
-            _ => tree.rewrite(context, shape),
         });
     match rw {
         Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
@@ -194,80 +120,7 @@ fn rewrite_import(
     }
 }
 
-fn rewrite_imports(
-    context: &RewriteContext,
-    use_items: &[&ast::Item],
-    shape: Shape,
-    span: Span,
-) -> Option<String> {
-    let items = itemize_list(
-        context.codemap,
-        use_items.iter(),
-        "",
-        ";",
-        |item| item.span().lo(),
-        |item| item.span().hi(),
-        |item| {
-            let attrs_str = item.attrs.rewrite(context, shape)?;
-
-            let missed_span = if item.attrs.is_empty() {
-                mk_sp(item.span.lo(), item.span.lo())
-            } else {
-                mk_sp(item.attrs.last().unwrap().span.hi(), item.span.lo())
-            };
-
-            let item_str = match item.node {
-                ast::ItemKind::Use(ref tree) => {
-                    rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
-                }
-                ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
-                _ => return None,
-            };
-
-            combine_strs_with_missing_comments(
-                context,
-                &attrs_str,
-                &item_str,
-                missed_span,
-                shape,
-                false,
-            )
-        },
-        span.lo(),
-        span.hi(),
-        false,
-    );
-    let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
-    item_pair_vec.sort_by(|a, b| compare_use_items(context, a.1, b.1).unwrap());
-    let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
-
-    let fmt = ListFormatting {
-        tactic: DefinitiveListTactic::Vertical,
-        separator: "",
-        trailing_separator: SeparatorTactic::Never,
-        separator_place: SeparatorPlace::Back,
-        shape: shape,
-        ends_with_newline: true,
-        preserve_newline: false,
-        config: context.config,
-    };
-
-    write_list(&item_vec, &fmt)
-}
-
 impl<'a> FmtVisitor<'a> {
-    pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
-        if use_items.is_empty() {
-            return;
-        }
-
-        let lo = use_items.first().unwrap().span().lo();
-        let hi = use_items.last().unwrap().span().hi();
-        let span = mk_sp(lo, hi);
-        let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
-        self.push_rewrite(span, rw);
-    }
-
     pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
         let span = item.span;
         let shape = self.shape();
@@ -276,16 +129,19 @@ pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
             Some(ref s) if s.is_empty() => {
                 // Format up to last newline
                 let prev_span = 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 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) => {
                 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 => {
@@ -296,48 +152,44 @@ pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
     }
 }
 
-fn rewrite_nested_use_tree_single(path_str: String, tree: &ast::UseTree) -> String {
-    if let ast::UseTreeKind::Simple(rename) = tree.kind {
-        let ident = tree.prefix.segments.last().unwrap().identifier;
-        let mut item_str = ident.name.to_string();
-        if item_str == "self" {
-            item_str = "".to_owned();
-        }
+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();
+            }
 
-        let path_item_str = if path_str.is_empty() {
-            if item_str.is_empty() {
-                "self".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.to_owned()
             } else {
-                item_str
-            }
-        } else if item_str.is_empty() {
-            path_str
-        } else {
-            format!("{}::{}", path_str, item_str)
-        };
+                format!("{}::{}", path_str, item_str)
+            };
 
-        if ident == rename {
-            path_item_str
-        } else {
-            format!("{} as {}", path_item_str, rename)
+            Some(if same_rename(&opt_rename, &tree.prefix) {
+                path_item_str
+            } else {
+                format!("{} as {}", path_item_str, opt_rename?)
+            })
         }
-    } else {
-        unimplemented!("`use_nested_groups` is not yet fully supported");
-    }
-}
-
-fn rewrite_nested_use_tree_item(tree: &&ast::UseTree) -> Option<String> {
-    Some(if let ast::UseTreeKind::Simple(rename) = tree.kind {
-        let ident = tree.prefix.segments.last().unwrap().identifier;
-
-        if ident == rename {
-            ident.name.to_string()
-        } else {
-            format!("{} as {}", ident.name.to_string(), 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))
         }
-    } else {
-        unimplemented!("`use_nested_groups` is not yet fully supported");
-    })
+    }
 }
 
 #[derive(Eq, PartialEq)]
@@ -426,11 +278,13 @@ fn rewrite_nested_use_tree(
 
     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));
         }
-        // TODO: fix this
-        1 => return Some(rewrite_nested_use_tree_single(path_str, &trees[0].0)),
+        1 => {
+            return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
+        }
         _ => (),
     }
 
@@ -442,19 +296,29 @@ fn rewrite_nested_use_tree(
 
     // 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,
-            trees.iter().map(|ref tree| &tree.0),
+            context.snippet_provider,
+            trees.iter().map(|tree| &tree.0),
             "}",
             ",",
             |tree| tree.span.lo(),
             |tree| tree.span.hi(),
-            rewrite_nested_use_tree_item,
-            context.codemap.span_after(span, "{"),
+            |tree| tree.rewrite(context, nested_shape),
+            context.snippet_provider.span_after(span, "{"),
             span.hi(),
             false,
         );
@@ -483,22 +347,11 @@ fn rewrite_nested_use_tree(
         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 fmt = ListFormatting {
-        tactic: tactic,
+        tactic,
         separator: ",",
         trailing_separator: if ends_with_newline {
             context.config.trailing_comma()
@@ -507,7 +360,7 @@ fn rewrite_nested_use_tree(
         },
         separator_place: SeparatorPlace::Back,
         shape: nested_shape,
-        ends_with_newline: ends_with_newline,
+        ends_with_newline,
         preserve_newline: true,
         config: context.config,
     };