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.
13 use syntax::codemap::{self, BytePos, Span};
14 use codemap::SpanUtils;
15 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, definitive_tactic};
16 use types::{rewrite_path, PathContext};
17 use rewrite::{Rewrite, RewriteContext};
18 use visitor::FmtVisitor;
19 use std::cmp::{self, Ordering};
21 use syntax::{ast, ptr};
23 fn path_of(a: &ast::ViewPath_) -> &ast::Path {
25 ast::ViewPath_::ViewPathSimple(_, ref p) => p,
26 ast::ViewPath_::ViewPathGlob(ref p) => p,
27 ast::ViewPath_::ViewPathList(ref p, _) => p,
31 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
32 a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
35 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
36 for segment in a.segments.iter().zip(b.segments.iter()) {
37 let ord = compare_path_segments(segment.0, segment.1);
38 if ord != Ordering::Equal {
42 a.segments.len().cmp(&b.segments.len())
45 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
46 let a_name_str = &*a.node.name.name.as_str();
47 let b_name_str = &*b.node.name.name.as_str();
48 let name_ordering = if a_name_str == "self" {
49 if b_name_str == "self" {
55 if b_name_str == "self" {
58 a_name_str.cmp(&b_name_str)
61 if name_ordering == Ordering::Equal {
65 Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
66 None => Ordering::Greater,
69 None => Ordering::Less,
76 fn compare_path_list_item_lists(a_items: &Vec<ast::PathListItem>,
77 b_items: &Vec<ast::PathListItem>)
79 let mut a = a_items.clone();
80 let mut b = b_items.clone();
81 a.sort_by(|a, b| compare_path_list_items(a, b));
82 b.sort_by(|a, b| compare_path_list_items(a, b));
83 for comparison_pair in a.iter().zip(b.iter()) {
84 let ord = compare_path_list_items(comparison_pair.0, comparison_pair.1);
85 if ord != Ordering::Equal {
92 fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
93 use syntax::ast::ViewPath_::*;
95 (&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
96 (&ViewPathSimple(..), _) => Ordering::Less,
97 (&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
98 (&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
99 (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
100 (&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
101 compare_path_list_item_lists(a_items, b_items)
103 (&ViewPathList(..), _) => Ordering::Greater,
107 fn compare_view_paths(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
108 match compare_paths(path_of(a), path_of(b)) {
109 Ordering::Equal => compare_view_path_types(a, b),
114 fn compare_use_items(a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
115 match (&a.node, &b.node) {
116 (&ast::ItemKind::Use(ref a_vp), &ast::ItemKind::Use(ref b_vp)) => {
117 Some(compare_view_paths(&a_vp.node, &b_vp.node))
123 // TODO (some day) remove unused imports, expand globs, compress many single
124 // imports into a list import.
126 fn rewrite_view_path_prefix(path: &ast::Path,
127 context: &RewriteContext,
130 let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
131 path.segments.len() > 1 {
132 let path = &ast::Path {
133 span: path.span.clone(),
134 segments: path.segments[..path.segments.len() - 1].to_owned(),
136 try_opt!(rewrite_path(context, PathContext::Import, None, path, shape))
138 try_opt!(rewrite_path(context, PathContext::Import, None, path, shape))
143 impl Rewrite for ast::ViewPath {
144 // Returns an empty string when the ViewPath is empty (like foo::bar::{})
145 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
147 ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => {
150 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
151 rewrite_use_list(shape, path, path_list, self.span, context)
153 ast::ViewPath_::ViewPathGlob(ref path) => {
155 let prefix_shape = try_opt!(shape.sub_width(3));
156 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
157 Some(format!("{}::*", path_str))
159 ast::ViewPath_::ViewPathSimple(ident, ref path) => {
160 let ident_str = ident.to_string();
162 let prefix_shape = try_opt!(shape.sub_width(ident_str.len() + 4));
163 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
165 Some(if path.segments.last().unwrap().identifier == ident {
168 format!("{} as {}", path_str, ident_str)
175 impl<'a> FmtVisitor<'a> {
176 pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
177 // Find the location immediately before the first use item in the run. This must not lie
178 // before the current `self.last_pos`
179 let pos_before_first_use_item = use_items
182 cmp::max(self.last_pos,
185 .map(|attr| attr.span.lo)
187 .unwrap_or(p_i.span.lo))
189 .unwrap_or(self.last_pos);
190 // Construct a list of pairs, each containing a `use` item and the start of span before
192 let mut last_pos_of_prev_use_item = pos_before_first_use_item;
193 let mut ordered_use_items = use_items
196 let new_item = (&*p_i, last_pos_of_prev_use_item);
197 last_pos_of_prev_use_item = p_i.span.hi;
200 .collect::<Vec<_>>();
201 let pos_after_last_use_item = last_pos_of_prev_use_item;
202 // Order the imports by view-path & other import path properties
203 ordered_use_items.sort_by(|a, b| compare_use_items(a.0, b.0).unwrap());
204 // First, output the span before the first import
205 let prev_span_str = self.snippet(codemap::mk_sp(self.last_pos, pos_before_first_use_item));
206 // Look for purely trailing space at the start of the prefix snippet before a linefeed, or
207 // a prefix that's entirely horizontal whitespace.
208 let prefix_span_start = match prev_span_str.find('\n') {
209 Some(offset) if prev_span_str[..offset].trim().is_empty() => {
210 self.last_pos + BytePos(offset as u32)
212 None if prev_span_str.trim().is_empty() => pos_before_first_use_item,
215 // Look for indent (the line part preceding the use is all whitespace) and excise that
217 let span_end = match prev_span_str.rfind('\n') {
218 Some(offset) if prev_span_str[offset..].trim().is_empty() => {
219 self.last_pos + BytePos(offset as u32)
221 _ => pos_before_first_use_item,
224 self.last_pos = prefix_span_start;
225 self.format_missing(span_end);
226 for ordered in ordered_use_items {
227 // Fake out the formatter by setting `self.last_pos` to the appropriate location before
228 // each item before visiting it.
229 self.last_pos = ordered.1;
230 self.visit_item(ordered.0);
232 self.last_pos = pos_after_last_use_item;
235 pub fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
236 let vis = utils::format_visibility(vis);
237 let mut offset = self.block_indent;
238 offset.alignment += vis.len() + "use ".len();
240 match vp.rewrite(&self.get_context(),
241 Shape::legacy(self.config.max_width() - offset.width() - 1, offset)) {
242 Some(ref s) if s.is_empty() => {
243 // Format up to last newline
244 let prev_span = codemap::mk_sp(self.last_pos, source!(self, span).lo);
245 let span_end = match self.snippet(prev_span).rfind('\n') {
246 Some(offset) => self.last_pos + BytePos(offset as u32),
247 None => source!(self, span).lo,
249 self.format_missing(span_end);
250 self.last_pos = source!(self, span).hi;
253 let s = format!("{}use {};", vis, s);
254 self.format_missing_with_indent(source!(self, span).lo);
255 self.buffer.push_str(&s);
256 self.last_pos = source!(self, span).hi;
259 self.format_missing_with_indent(source!(self, span).lo);
260 self.format_missing(source!(self, span).hi);
266 fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
267 let mut item_str = vpi.node.name.to_string();
268 if item_str == "self" {
269 item_str = "".to_owned();
271 let path_item_str = if path_str.is_empty() {
272 if item_str.is_empty() {
277 } else if item_str.is_empty() {
280 format!("{}::{}", path_str, item_str)
282 append_alias(path_item_str, vpi)
285 fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
286 Some(append_alias(vpi.node.name.to_string(), vpi))
289 fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
290 match vpi.node.rename {
291 Some(rename) => format!("{} as {}", path_item_str, rename),
292 None => path_item_str,
296 // Pretty prints a multi-item import.
297 // Assumes that path_list.len() > 0.
298 pub fn rewrite_use_list(shape: Shape,
300 path_list: &[ast::PathListItem],
302 context: &RewriteContext)
304 // Returns a different option to distinguish `::foo` and `foo`
305 let path_str = try_opt!(rewrite_path(context, PathContext::Import, None, path, shape));
307 match path_list.len() {
309 1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
313 let colons_offset = if path_str.is_empty() { 0 } else { 2 };
316 let remaining_width = shape
318 .checked_sub(path_str.len() + 2 + colons_offset)
322 // Dummy value, see explanation below.
323 let mut items = vec![ListItem::from_str("")];
324 let iter = itemize_list(context.codemap,
330 context.codemap.span_after(span, "{"),
336 // We prefixed the item list with a dummy value so that we can
337 // potentially move "self" to the front of the vector without touching
338 // the rest of the items.
339 let has_self = move_self_to_front(&mut items);
340 let first_index = if has_self { 0 } else { 1 };
342 if context.config.reorder_imported_names() {
343 items[1..].sort_by(|a, b| a.item.cmp(&b.item));
347 let tactic = definitive_tactic(&items[first_index..],
348 ::lists::ListTactic::Mixed,
351 let fmt = ListFormatting {
354 trailing_separator: SeparatorTactic::Never,
355 // Add one to the indent to account for "{"
356 shape: Shape::legacy(remaining_width,
357 shape.indent + path_str.len() + colons_offset + 1),
358 ends_with_newline: false,
359 config: context.config,
361 let list_str = try_opt!(write_list(&items[first_index..], &fmt));
363 Some(if path_str.is_empty() {
364 format!("{{{}}}", list_str)
366 format!("{}::{{{}}}", path_str, list_str)
370 // Returns true when self item was found.
371 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
374 .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self")) {
376 items[0] = items.remove(pos);