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 = &*a.prefix.segments.last().unwrap().identifier.name.as_str();
57 let name_b = &*b.prefix.segments.last().unwrap().identifier.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 let path_str = if path.segments.last().unwrap().identifier.to_string() == "self"
125 && path.segments.len() > 1
127 let path = &ast::Path {
129 segments: path.segments[..path.segments.len() - 1].to_owned(),
131 rewrite_path(context, PathContext::Import, None, path, shape)?
133 rewrite_path(context, PathContext::Import, None, path, shape)?
138 impl Rewrite for ast::UseTree {
139 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
141 ast::UseTreeKind::Nested(ref items) => {
142 rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
144 ast::UseTreeKind::Glob => {
145 let prefix_shape = shape.sub_width(3)?;
147 if self.prefix.segments.len() > 0 {
148 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
149 Some(format!("{}::*", path_str))
154 ast::UseTreeKind::Simple(ident) => {
155 let ident_str = ident.to_string();
158 let prefix_shape = shape.sub_width(ident_str.len() + 4)?;
159 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
161 if self.prefix.segments.last().unwrap().identifier == ident {
164 Some(format!("{} as {}", path_str, ident_str))
171 // Rewrite `use foo;` WITHOUT attributes.
173 context: &RewriteContext,
174 vis: &ast::Visibility,
176 attrs: &[ast::Attribute],
178 ) -> Option<String> {
179 let vis = format_visibility(vis);
180 // 4 = `use `, 1 = `;`
182 .offset_left(vis.len() + 4)
183 .and_then(|shape| shape.sub_width(1))
184 .and_then(|shape| match tree.kind {
185 // If we have an empty nested group with no attributes, we erase it
186 ast::UseTreeKind::Nested(ref items) if items.is_empty() && attrs.is_empty() => {
189 _ => tree.rewrite(context, shape),
192 Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
198 context: &RewriteContext,
199 use_items: &[&ast::Item],
202 ) -> Option<String> {
203 let items = itemize_list(
208 |item| item.span().lo(),
209 |item| item.span().hi(),
211 let attrs_str = item.attrs.rewrite(context, shape)?;
213 let missed_span = if item.attrs.is_empty() {
214 mk_sp(item.span.lo(), item.span.lo())
216 mk_sp(item.attrs.last().unwrap().span.hi(), item.span.lo())
219 let item_str = match item.node {
220 ast::ItemKind::Use(ref tree) => {
221 rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
223 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
227 combine_strs_with_missing_comments(
240 let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
241 item_pair_vec.sort_by(|a, b| compare_use_items(context, a.1, b.1).unwrap());
242 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
244 let fmt = ListFormatting {
245 tactic: DefinitiveListTactic::Vertical,
247 trailing_separator: SeparatorTactic::Never,
248 separator_place: SeparatorPlace::Back,
250 ends_with_newline: true,
251 preserve_newline: false,
252 config: context.config,
255 write_list(&item_vec, &fmt)
258 impl<'a> FmtVisitor<'a> {
259 pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
260 if use_items.is_empty() {
264 let lo = use_items.first().unwrap().span().lo();
265 let hi = use_items.last().unwrap().span().hi();
266 let span = mk_sp(lo, hi);
267 let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
268 self.push_rewrite(span, rw);
271 pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
272 let span = item.span;
273 let shape = self.shape();
274 let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
276 Some(ref s) if s.is_empty() => {
277 // Format up to last newline
278 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
279 let span_end = match self.snippet(prev_span).rfind('\n') {
280 Some(offset) => self.last_pos + BytePos(offset as u32),
281 None => source!(self, span).lo(),
283 self.format_missing(span_end);
284 self.last_pos = source!(self, span).hi();
287 self.format_missing_with_indent(source!(self, span).lo());
288 self.buffer.push_str(s);
289 self.last_pos = source!(self, span).hi();
292 self.format_missing_with_indent(source!(self, span).lo());
293 self.format_missing(source!(self, span).hi());
299 fn rewrite_nested_use_tree_single(path_str: String, tree: &ast::UseTree) -> String {
300 if let ast::UseTreeKind::Simple(rename) = tree.kind {
301 let ident = tree.prefix.segments.last().unwrap().identifier;
302 let mut item_str = ident.name.to_string();
303 if item_str == "self" {
304 item_str = "".to_owned();
307 let path_item_str = if path_str.is_empty() {
308 if item_str.is_empty() {
313 } else if item_str.is_empty() {
316 format!("{}::{}", path_str, item_str)
322 format!("{} as {}", path_item_str, rename)
325 unimplemented!("`use_nested_groups` is not yet fully supported");
329 fn rewrite_nested_use_tree_item(tree: &&ast::UseTree) -> Option<String> {
330 Some(if let ast::UseTreeKind::Simple(rename) = tree.kind {
331 let ident = tree.prefix.segments.last().unwrap().identifier;
334 ident.name.to_string()
336 format!("{} as {}", ident.name.to_string(), rename)
339 unimplemented!("`use_nested_groups` is not yet fully supported");
343 #[derive(Eq, PartialEq)]
344 enum ImportItem<'a> {
345 // `self` or `self as a`
347 // name_one, name_two, ...
349 // NameOne, NameTwo, ...
351 // NAME_ONE, NAME_TWO, ...
353 // Failed to format the import item
357 impl<'a> ImportItem<'a> {
358 fn from_str(s: &str) -> ImportItem {
359 if s == "self" || s.starts_with("self as") {
360 ImportItem::SelfImport(s)
361 } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
362 ImportItem::SnakeCase(s)
363 } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
364 ImportItem::AllCaps(s)
366 ImportItem::CamelCase(s)
370 fn from_opt_str(s: Option<&String>) -> ImportItem {
371 s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
374 fn to_str(&self) -> Option<&str> {
376 ImportItem::SelfImport(s)
377 | ImportItem::SnakeCase(s)
378 | ImportItem::CamelCase(s)
379 | ImportItem::AllCaps(s) => Some(s),
380 ImportItem::Invalid => None,
384 fn to_u32(&self) -> u32 {
386 ImportItem::SelfImport(..) => 0,
387 ImportItem::SnakeCase(..) => 1,
388 ImportItem::CamelCase(..) => 2,
389 ImportItem::AllCaps(..) => 3,
390 ImportItem::Invalid => 4,
395 impl<'a> PartialOrd for ImportItem<'a> {
396 fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
397 Some(self.cmp(other))
401 impl<'a> Ord for ImportItem<'a> {
402 fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
403 let res = self.to_u32().cmp(&other.to_u32());
404 if res != Ordering::Equal {
407 self.to_str().map_or(Ordering::Greater, |self_str| {
410 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
415 // Pretty prints a multi-item import.
416 // If the path list is empty, it leaves the braces empty.
417 fn rewrite_nested_use_tree(
420 trees: &[(ast::UseTree, ast::NodeId)],
422 context: &RewriteContext,
423 ) -> Option<String> {
424 // Returns a different option to distinguish `::foo` and `foo`
425 let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
429 return rewrite_path(context, PathContext::Import, None, path, shape)
430 .map(|path_str| format!("{}::{{}}", path_str));
433 1 => return Some(rewrite_nested_use_tree_single(path_str, &trees[0].0)),
437 let path_str = if path_str.is_empty() {
440 format!("{}::", path_str)
444 let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
447 // Dummy value, see explanation below.
448 let mut items = vec![ListItem::from_str("")];
449 let iter = itemize_list(
451 trees.iter().map(|ref tree| &tree.0),
454 |tree| tree.span.lo(),
455 |tree| tree.span.hi(),
456 rewrite_nested_use_tree_item,
457 context.codemap.span_after(span, "{"),
465 // We prefixed the item list with a dummy value so that we can
466 // potentially move "self" to the front of the vector without touching
467 // the rest of the items.
468 let has_self = move_self_to_front(&mut items);
469 let first_index = if has_self { 0 } else { 1 };
471 if context.config.reorder_imported_names() {
472 items[1..].sort_by(|a, b| {
473 let a = ImportItem::from_opt_str(a.item.as_ref());
474 let b = ImportItem::from_opt_str(b.item.as_ref());
479 let tactic = definitive_tactic(
480 &items[first_index..],
481 context.config.imports_layout(),
486 let nested_indent = match context.config.imports_indent() {
487 IndentStyle::Block => shape.indent.block_indent(context.config),
489 IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
492 let nested_shape = match context.config.imports_indent() {
493 IndentStyle::Block => Shape::indented(nested_indent, context.config),
494 IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
497 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
498 && tactic != DefinitiveListTactic::Horizontal;
500 let fmt = ListFormatting {
503 trailing_separator: if ends_with_newline {
504 context.config.trailing_comma()
506 SeparatorTactic::Never
508 separator_place: SeparatorPlace::Back,
510 ends_with_newline: ends_with_newline,
511 preserve_newline: true,
512 config: context.config,
514 let list_str = write_list(&items[first_index..], &fmt)?;
516 let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
521 nested_shape.indent.to_string(context.config),
523 shape.indent.to_string(context.config)
526 format!("{}{{{}}}", path_str, list_str)
531 // Returns true when self item was found.
532 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
535 .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
538 items[0] = items.remove(pos);