1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::cmp::Ordering;
14 use syntax::codemap::{BytePos, Span};
17 use codemap::SpanUtils;
18 use comment::combine_strs_with_missing_comments;
19 use config::IndentStyle;
20 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
21 ListItem, Separator, SeparatorPlace, SeparatorTactic};
22 use rewrite::{Rewrite, RewriteContext};
24 use types::{rewrite_path, PathContext};
25 use utils::{format_visibility, mk_sp};
26 use visitor::{rewrite_extern_crate, FmtVisitor};
28 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
29 a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
32 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
33 for segment in a.segments.iter().zip(b.segments.iter()) {
34 let ord = compare_path_segments(segment.0, segment.1);
35 if ord != Ordering::Equal {
39 a.segments.len().cmp(&b.segments.len())
42 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
43 use ast::UseTreeKind::*;
45 // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
48 let paths_cmp = compare_paths(&a.prefix, &b.prefix);
49 if paths_cmp != Ordering::Equal {
54 match (&a.kind, &b.kind) {
55 (&Simple(ident_a), &Simple(ident_b)) => {
56 let name_a = &*path_to_imported_ident(&a.prefix).name.as_str();
57 let name_b = &*path_to_imported_ident(&b.prefix).name.as_str();
58 let name_ordering = if name_a == "self" {
64 } else if name_b == "self" {
69 if name_ordering == Ordering::Equal {
70 if ident_a.name.as_str() != name_a {
71 if ident_b.name.as_str() != name_b {
72 ident_a.name.as_str().cmp(&ident_b.name.as_str())
83 (&Glob, &Glob) => Ordering::Equal,
84 (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
85 (&Nested(ref a_items), &Nested(ref b_items)) => {
88 .map(|&(ref tree, _)| tree.clone())
92 .map(|&(ref tree, _)| tree.clone())
94 a.sort_by(|a, b| compare_use_trees(a, b, true));
95 b.sort_by(|a, b| compare_use_trees(a, b, true));
96 for comparison_pair in a.iter().zip(b.iter()) {
97 let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
98 if ord != Ordering::Equal {
102 a.len().cmp(&b.len())
104 (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
108 fn compare_use_items(context: &RewriteContext, a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
109 match (&a.node, &b.node) {
110 (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
111 Some(compare_use_trees(&a_tree, &b_tree, false))
113 (&ast::ItemKind::ExternCrate(..), &ast::ItemKind::ExternCrate(..)) => {
114 Some(context.snippet(a.span).cmp(&context.snippet(b.span)))
120 // TODO (some day) remove unused imports, expand globs, compress many single
121 // imports into a list import.
123 fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
124 if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
125 let path = &ast::Path {
127 segments: path.segments[..path.segments.len() - 1].to_owned(),
129 rewrite_path(context, PathContext::Import, None, path, shape)
131 rewrite_path(context, PathContext::Import, None, path, shape)
135 impl Rewrite for ast::UseTree {
136 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
138 ast::UseTreeKind::Nested(ref items) => {
139 rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
141 ast::UseTreeKind::Glob => {
142 let prefix_shape = shape.sub_width(3)?;
144 if self.prefix.segments.len() > 0 {
145 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
146 Some(format!("{}::*", path_str))
151 ast::UseTreeKind::Simple(ident) => {
152 let ident_str = ident.to_string();
155 let is_same_name_bind = path_to_imported_ident(&self.prefix) == ident;
156 let prefix_shape = if is_same_name_bind {
159 shape.sub_width(ident_str.len() + 4)?
161 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)
162 .unwrap_or_else(|| context.snippet(self.prefix.span).to_owned());
164 if is_same_name_bind {
167 Some(format!("{} as {}", path_str, ident_str))
174 fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
175 attrs.is_empty() && is_unused_import_inner(tree)
178 fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
180 ast::UseTreeKind::Nested(ref items) => match items.len() {
182 1 => is_unused_import_inner(&items[0].0),
189 // Rewrite `use foo;` WITHOUT attributes.
191 context: &RewriteContext,
192 vis: &ast::Visibility,
194 attrs: &[ast::Attribute],
196 ) -> Option<String> {
197 let vis = format_visibility(vis);
198 // 4 = `use `, 1 = `;`
200 .offset_left(vis.len() + 4)
201 .and_then(|shape| shape.sub_width(1))
203 // If we have an empty nested group with no attributes, we erase it
204 if is_unused_import(tree, attrs) {
207 tree.rewrite(context, shape)
211 Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
217 context: &RewriteContext,
218 use_items: &[&ast::Item],
221 ) -> Option<String> {
222 let items = itemize_list(
227 |item| item.span().lo(),
228 |item| item.span().hi(),
230 let attrs_str = item.attrs.rewrite(context, shape)?;
232 let missed_span = if item.attrs.is_empty() {
233 mk_sp(item.span.lo(), item.span.lo())
235 mk_sp(item.attrs.last().unwrap().span.hi(), item.span.lo())
238 let item_str = match item.node {
239 ast::ItemKind::Use(ref tree) => {
240 rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
242 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
246 combine_strs_with_missing_comments(
259 let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
260 item_pair_vec.sort_by(|a, b| compare_use_items(context, a.1, b.1).unwrap());
261 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
263 let fmt = ListFormatting {
264 tactic: DefinitiveListTactic::Vertical,
266 trailing_separator: SeparatorTactic::Never,
267 separator_place: SeparatorPlace::Back,
269 ends_with_newline: true,
270 preserve_newline: false,
271 config: context.config,
274 write_list(&item_vec, &fmt)
277 impl<'a> FmtVisitor<'a> {
278 pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
279 if use_items.is_empty() {
283 let lo = use_items.first().unwrap().span().lo();
284 let hi = use_items.last().unwrap().span().hi();
285 let span = mk_sp(lo, hi);
286 let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
287 self.push_rewrite(span, rw);
290 pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
291 let span = item.span;
292 let shape = self.shape();
293 let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
295 Some(ref s) if s.is_empty() => {
296 // Format up to last newline
297 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
298 let span_end = match self.snippet(prev_span).rfind('\n') {
299 Some(offset) => self.last_pos + BytePos(offset as u32),
300 None => source!(self, span).lo(),
302 self.format_missing(span_end);
303 self.last_pos = source!(self, span).hi();
306 self.format_missing_with_indent(source!(self, span).lo());
308 self.last_pos = source!(self, span).hi();
311 self.format_missing_with_indent(source!(self, span).lo());
312 self.format_missing(source!(self, span).hi());
318 fn rewrite_nested_use_tree_single(
319 context: &RewriteContext,
323 ) -> Option<String> {
325 ast::UseTreeKind::Simple(rename) => {
326 let ident = path_to_imported_ident(&tree.prefix);
327 let mut item_str = rewrite_prefix(&tree.prefix, context, shape)?;
328 if item_str == "self" {
329 item_str = "".to_owned();
332 let path_item_str = if path_str.is_empty() {
333 if item_str.is_empty() {
338 } else if item_str.is_empty() {
341 format!("{}::{}", path_str, item_str)
344 Some(if ident == rename {
347 format!("{} as {}", path_item_str, rename)
350 ast::UseTreeKind::Glob | ast::UseTreeKind::Nested(..) => {
352 let nested_shape = shape.offset_left(path_str.len() + 2)?;
353 tree.rewrite(context, nested_shape)
354 .map(|item| format!("{}::{}", path_str, item))
359 #[derive(Eq, PartialEq)]
360 enum ImportItem<'a> {
361 // `self` or `self as a`
363 // name_one, name_two, ...
365 // NameOne, NameTwo, ...
367 // NAME_ONE, NAME_TWO, ...
369 // Failed to format the import item
373 impl<'a> ImportItem<'a> {
374 fn from_str(s: &str) -> ImportItem {
375 if s == "self" || s.starts_with("self as") {
376 ImportItem::SelfImport(s)
377 } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
378 ImportItem::SnakeCase(s)
379 } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
380 ImportItem::AllCaps(s)
382 ImportItem::CamelCase(s)
386 fn from_opt_str(s: Option<&String>) -> ImportItem {
387 s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
390 fn to_str(&self) -> Option<&str> {
392 ImportItem::SelfImport(s)
393 | ImportItem::SnakeCase(s)
394 | ImportItem::CamelCase(s)
395 | ImportItem::AllCaps(s) => Some(s),
396 ImportItem::Invalid => None,
400 fn to_u32(&self) -> u32 {
402 ImportItem::SelfImport(..) => 0,
403 ImportItem::SnakeCase(..) => 1,
404 ImportItem::CamelCase(..) => 2,
405 ImportItem::AllCaps(..) => 3,
406 ImportItem::Invalid => 4,
411 impl<'a> PartialOrd for ImportItem<'a> {
412 fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
413 Some(self.cmp(other))
417 impl<'a> Ord for ImportItem<'a> {
418 fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
419 let res = self.to_u32().cmp(&other.to_u32());
420 if res != Ordering::Equal {
423 self.to_str().map_or(Ordering::Greater, |self_str| {
426 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
431 // Pretty prints a multi-item import.
432 // If the path list is empty, it leaves the braces empty.
433 fn rewrite_nested_use_tree(
436 trees: &[(ast::UseTree, ast::NodeId)],
438 context: &RewriteContext,
439 ) -> Option<String> {
440 // Returns a different option to distinguish `::foo` and `foo`
441 let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
445 let shape = shape.offset_left(path_str.len() + 3)?;
446 return rewrite_path(context, PathContext::Import, None, path, shape)
447 .map(|path_str| format!("{}::{{}}", path_str));
450 return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
455 let path_str = if path_str.is_empty() {
458 format!("{}::", path_str)
462 let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
463 let nested_indent = match context.config.imports_indent() {
464 IndentStyle::Block => shape.indent.block_indent(context.config),
466 IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
469 let nested_shape = match context.config.imports_indent() {
470 IndentStyle::Block => Shape::indented(nested_indent, context.config).sub_width(1)?,
471 IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
475 // Dummy value, see explanation below.
476 let mut items = vec![ListItem::from_str("")];
477 let iter = itemize_list(
479 trees.iter().map(|ref tree| &tree.0),
482 |tree| tree.span.lo(),
483 |tree| tree.span.hi(),
484 |tree| tree.rewrite(context, nested_shape),
485 context.codemap.span_after(span, "{"),
493 // We prefixed the item list with a dummy value so that we can
494 // potentially move "self" to the front of the vector without touching
495 // the rest of the items.
496 let has_self = move_self_to_front(&mut items);
497 let first_index = if has_self { 0 } else { 1 };
499 if context.config.reorder_imported_names() {
500 items[1..].sort_by(|a, b| {
501 let a = ImportItem::from_opt_str(a.item.as_ref());
502 let b = ImportItem::from_opt_str(b.item.as_ref());
507 let tactic = definitive_tactic(
508 &items[first_index..],
509 context.config.imports_layout(),
514 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
515 && tactic != DefinitiveListTactic::Horizontal;
517 let fmt = ListFormatting {
520 trailing_separator: if ends_with_newline {
521 context.config.trailing_comma()
523 SeparatorTactic::Never
525 separator_place: SeparatorPlace::Back,
527 ends_with_newline: ends_with_newline,
528 preserve_newline: true,
529 config: context.config,
531 let list_str = write_list(&items[first_index..], &fmt)?;
533 let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
538 nested_shape.indent.to_string(context.config),
540 shape.indent.to_string(context.config)
543 format!("{}{{{}}}", path_str, list_str)
548 // Returns true when self item was found.
549 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
552 .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
555 items[0] = items.remove(pos);
562 fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
563 path.segments.last().unwrap().identifier