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;
15 use syntax::codemap::{BytePos, Span};
17 use codemap::SpanUtils;
18 use config::IndentStyle;
19 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
20 use rewrite::{Rewrite, RewriteContext};
22 use types::{rewrite_path, PathContext};
23 use utils::{format_visibility, mk_sp};
24 use visitor::FmtVisitor;
26 /// Returns a name imported by a `use` declaration. e.g. returns `Ordering`
27 /// for `std::cmp::Ordering` and `self` for `std::cmp::self`.
28 pub fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
29 path.segments.last().unwrap().identifier
32 fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
33 if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
34 let path = &ast::Path {
36 segments: path.segments[..path.segments.len() - 1].to_owned(),
38 rewrite_path(context, PathContext::Import, None, path, shape)
40 rewrite_path(context, PathContext::Import, None, path, shape)
44 impl Rewrite for ast::UseTree {
45 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
47 ast::UseTreeKind::Nested(ref items) => {
48 rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
50 ast::UseTreeKind::Glob => {
51 let prefix_shape = shape.sub_width(3)?;
53 if !self.prefix.segments.is_empty() {
54 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
55 Some(format!("{}::*", path_str))
60 ast::UseTreeKind::Simple(ident) => {
61 let ident_str = ident.to_string();
64 let is_same_name_bind = path_to_imported_ident(&self.prefix) == ident;
65 let prefix_shape = if is_same_name_bind {
68 shape.sub_width(ident_str.len() + 4)?
70 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)
71 .unwrap_or_else(|| context.snippet(self.prefix.span).to_owned());
73 if is_same_name_bind {
76 Some(format!("{} as {}", path_str, ident_str))
83 fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
84 attrs.is_empty() && is_unused_import_inner(tree)
87 fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
89 ast::UseTreeKind::Nested(ref items) => match items.len() {
91 1 => is_unused_import_inner(&items[0].0),
98 // Rewrite `use foo;` WITHOUT attributes.
99 pub fn rewrite_import(
100 context: &RewriteContext,
101 vis: &ast::Visibility,
103 attrs: &[ast::Attribute],
105 ) -> Option<String> {
106 let vis = format_visibility(vis);
107 // 4 = `use `, 1 = `;`
109 .offset_left(vis.len() + 4)
110 .and_then(|shape| shape.sub_width(1))
112 // If we have an empty nested group with no attributes, we erase it
113 if is_unused_import(tree, attrs) {
116 tree.rewrite(context, shape)
120 Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
125 impl<'a> FmtVisitor<'a> {
126 pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
127 let span = item.span;
128 let shape = self.shape();
129 let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
131 Some(ref s) if s.is_empty() => {
132 // Format up to last newline
133 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
134 let trimmed_snippet = self.snippet(prev_span).trim_right();
135 let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
136 self.format_missing(span_end);
137 // We have an excessive newline from the removed import.
138 if self.buffer.ends_with('\n') {
140 self.line_number -= 1;
142 self.last_pos = source!(self, span).hi();
145 self.format_missing_with_indent(source!(self, span).lo());
147 self.last_pos = source!(self, span).hi();
150 self.format_missing_with_indent(source!(self, span).lo());
151 self.format_missing(source!(self, span).hi());
157 fn rewrite_nested_use_tree_single(
158 context: &RewriteContext,
162 ) -> Option<String> {
164 ast::UseTreeKind::Simple(rename) => {
165 let ident = path_to_imported_ident(&tree.prefix);
166 let mut item_str = rewrite_prefix(&tree.prefix, context, shape)?;
167 if item_str == "self" {
168 item_str = "".to_owned();
171 let path_item_str = if path_str.is_empty() {
172 if item_str.is_empty() {
177 } else if item_str.is_empty() {
180 format!("{}::{}", path_str, item_str)
183 Some(if ident == rename {
186 format!("{} as {}", path_item_str, rename)
189 ast::UseTreeKind::Glob | ast::UseTreeKind::Nested(..) => {
191 let nested_shape = shape.offset_left(path_str.len() + 2)?;
192 tree.rewrite(context, nested_shape)
193 .map(|item| format!("{}::{}", path_str, item))
198 #[derive(Eq, PartialEq)]
199 enum ImportItem<'a> {
200 // `self` or `self as a`
202 // name_one, name_two, ...
204 // NameOne, NameTwo, ...
206 // NAME_ONE, NAME_TWO, ...
208 // Failed to format the import item
212 impl<'a> ImportItem<'a> {
213 fn from_str(s: &str) -> ImportItem {
214 if s == "self" || s.starts_with("self as") {
215 ImportItem::SelfImport(s)
216 } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
217 ImportItem::SnakeCase(s)
218 } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
219 ImportItem::AllCaps(s)
221 ImportItem::CamelCase(s)
225 fn from_opt_str(s: Option<&String>) -> ImportItem {
226 s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
229 fn to_str(&self) -> Option<&str> {
231 ImportItem::SelfImport(s)
232 | ImportItem::SnakeCase(s)
233 | ImportItem::CamelCase(s)
234 | ImportItem::AllCaps(s) => Some(s),
235 ImportItem::Invalid => None,
239 fn to_u32(&self) -> u32 {
241 ImportItem::SelfImport(..) => 0,
242 ImportItem::SnakeCase(..) => 1,
243 ImportItem::CamelCase(..) => 2,
244 ImportItem::AllCaps(..) => 3,
245 ImportItem::Invalid => 4,
250 impl<'a> PartialOrd for ImportItem<'a> {
251 fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
252 Some(self.cmp(other))
256 impl<'a> Ord for ImportItem<'a> {
257 fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
258 let res = self.to_u32().cmp(&other.to_u32());
259 if res != Ordering::Equal {
262 self.to_str().map_or(Ordering::Greater, |self_str| {
265 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
270 // Pretty prints a multi-item import.
271 // If the path list is empty, it leaves the braces empty.
272 fn rewrite_nested_use_tree(
275 trees: &[(ast::UseTree, ast::NodeId)],
277 context: &RewriteContext,
278 ) -> Option<String> {
279 // Returns a different option to distinguish `::foo` and `foo`
280 let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
284 let shape = shape.offset_left(path_str.len() + 3)?;
285 return rewrite_path(context, PathContext::Import, None, path, shape)
286 .map(|path_str| format!("{}::{{}}", path_str));
289 return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
294 let path_str = if path_str.is_empty() {
297 format!("{}::", path_str)
301 let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
302 let nested_indent = match context.config.imports_indent() {
303 IndentStyle::Block => shape.indent.block_indent(context.config),
305 IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
308 let nested_shape = match context.config.imports_indent() {
309 IndentStyle::Block => Shape::indented(nested_indent, context.config).sub_width(1)?,
310 IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
314 // Dummy value, see explanation below.
315 let mut items = vec![ListItem::from_str("")];
316 let iter = itemize_list(
317 context.snippet_provider,
318 trees.iter().map(|tree| &tree.0),
321 |tree| tree.span.lo(),
322 |tree| tree.span.hi(),
323 |tree| tree.rewrite(context, nested_shape),
324 context.snippet_provider.span_after(span, "{"),
332 // We prefixed the item list with a dummy value so that we can
333 // potentially move "self" to the front of the vector without touching
334 // the rest of the items.
335 let has_self = move_self_to_front(&mut items);
336 let first_index = if has_self { 0 } else { 1 };
338 if context.config.reorder_imported_names() {
339 items[1..].sort_by(|a, b| {
340 let a = ImportItem::from_opt_str(a.item.as_ref());
341 let b = ImportItem::from_opt_str(b.item.as_ref());
346 let tactic = definitive_tactic(
347 &items[first_index..],
348 context.config.imports_layout(),
353 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
354 && tactic != DefinitiveListTactic::Horizontal;
356 let fmt = ListFormatting {
359 trailing_separator: if ends_with_newline {
360 context.config.trailing_comma()
362 SeparatorTactic::Never
364 separator_place: SeparatorPlace::Back,
367 preserve_newline: true,
368 config: context.config,
370 let list_str = write_list(&items[first_index..], &fmt)?;
372 let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
377 nested_shape.indent.to_string(context.config),
379 shape.indent.to_string(context.config)
382 format!("{}{{{}}}", path_str, list_str)
387 // Returns true when self item was found.
388 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
391 .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
394 items[0] = items.remove(pos);