]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Merge pull request #2355 from topecongiro/hide-parse-error-format-snippet
[rust.git] / src / imports.rs
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.
4 //
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.
10
11 use std::cmp::Ordering;
12
13 use syntax::ast;
14 use syntax::codemap::{BytePos, Span};
15
16 use codemap::SpanUtils;
17 use comment::combine_strs_with_missing_comments;
18 use config::IndentStyle;
19 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
20             ListItem, Separator, SeparatorPlace, SeparatorTactic};
21 use rewrite::{Rewrite, RewriteContext};
22 use shape::Shape;
23 use spanned::Spanned;
24 use types::{rewrite_path, PathContext};
25 use utils::{format_visibility, mk_sp};
26 use visitor::{rewrite_extern_crate, FmtVisitor};
27
28 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
29     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
30 }
31
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 {
36             return ord;
37         }
38     }
39     a.segments.len().cmp(&b.segments.len())
40 }
41
42 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
43     use ast::UseTreeKind::*;
44
45     // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
46     // fully added
47     if !nested {
48         let paths_cmp = compare_paths(&a.prefix, &b.prefix);
49         if paths_cmp != Ordering::Equal {
50             return paths_cmp;
51         }
52     }
53
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" {
59                 if name_b == "self" {
60                     Ordering::Equal
61                 } else {
62                     Ordering::Less
63                 }
64             } else if name_b == "self" {
65                 Ordering::Greater
66             } else {
67                 name_a.cmp(name_b)
68             };
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())
73                     } else {
74                         Ordering::Greater
75                     }
76                 } else {
77                     Ordering::Less
78                 }
79             } else {
80                 name_ordering
81             }
82         }
83         (&Glob, &Glob) => Ordering::Equal,
84         (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
85         (&Nested(ref a_items), &Nested(ref b_items)) => {
86             let mut a = a_items
87                 .iter()
88                 .map(|&(ref tree, _)| tree.clone())
89                 .collect::<Vec<_>>();
90             let mut b = b_items
91                 .iter()
92                 .map(|&(ref tree, _)| tree.clone())
93                 .collect::<Vec<_>>();
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 {
99                     return ord;
100                 }
101             }
102             a.len().cmp(&b.len())
103         }
104         (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
105     }
106 }
107
108 fn compare_use_items(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))
112         }
113         (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
114             // `extern crate foo as bar;`
115             //               ^^^ Comparing this.
116             let a_orig_name =
117                 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
118             let b_orig_name =
119                 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
120             let result = a_orig_name.cmp(&b_orig_name);
121             if result != Ordering::Equal {
122                 return Some(result);
123             }
124
125             // `extern crate foo as bar;`
126             //                      ^^^ Comparing this.
127             let result = match (a_name, b_name) {
128                 (Some(..), None) => Ordering::Greater,
129                 (None, Some(..)) => Ordering::Less,
130                 (None, None) => Ordering::Equal,
131                 (Some(..), Some(..)) => a.ident.name.cmp(&b.ident.name),
132             };
133             Some(result)
134         }
135         _ => None,
136     }
137 }
138
139 // TODO (some day) remove unused imports, expand globs, compress many single
140 // imports into a list import.
141
142 fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
143     if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
144         let path = &ast::Path {
145             span: path.span,
146             segments: path.segments[..path.segments.len() - 1].to_owned(),
147         };
148         rewrite_path(context, PathContext::Import, None, path, shape)
149     } else {
150         rewrite_path(context, PathContext::Import, None, path, shape)
151     }
152 }
153
154 impl Rewrite for ast::UseTree {
155     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
156         match self.kind {
157             ast::UseTreeKind::Nested(ref items) => {
158                 rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
159             }
160             ast::UseTreeKind::Glob => {
161                 let prefix_shape = shape.sub_width(3)?;
162
163                 if !self.prefix.segments.is_empty() {
164                     let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
165                     Some(format!("{}::*", path_str))
166                 } else {
167                     Some("*".to_owned())
168                 }
169             }
170             ast::UseTreeKind::Simple(ident) => {
171                 let ident_str = ident.to_string();
172
173                 // 4 = " as ".len()
174                 let is_same_name_bind = path_to_imported_ident(&self.prefix) == ident;
175                 let prefix_shape = if is_same_name_bind {
176                     shape
177                 } else {
178                     shape.sub_width(ident_str.len() + 4)?
179                 };
180                 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)
181                     .unwrap_or_else(|| context.snippet(self.prefix.span).to_owned());
182
183                 if is_same_name_bind {
184                     Some(path_str)
185                 } else {
186                     Some(format!("{} as {}", path_str, ident_str))
187                 }
188             }
189         }
190     }
191 }
192
193 fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
194     attrs.is_empty() && is_unused_import_inner(tree)
195 }
196
197 fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
198     match tree.kind {
199         ast::UseTreeKind::Nested(ref items) => match items.len() {
200             0 => true,
201             1 => is_unused_import_inner(&items[0].0),
202             _ => false,
203         },
204         _ => false,
205     }
206 }
207
208 // Rewrite `use foo;` WITHOUT attributes.
209 fn rewrite_import(
210     context: &RewriteContext,
211     vis: &ast::Visibility,
212     tree: &ast::UseTree,
213     attrs: &[ast::Attribute],
214     shape: Shape,
215 ) -> Option<String> {
216     let vis = format_visibility(vis);
217     // 4 = `use `, 1 = `;`
218     let rw = shape
219         .offset_left(vis.len() + 4)
220         .and_then(|shape| shape.sub_width(1))
221         .and_then(|shape| {
222             // If we have an empty nested group with no attributes, we erase it
223             if is_unused_import(tree, attrs) {
224                 Some("".to_owned())
225             } else {
226                 tree.rewrite(context, shape)
227             }
228         });
229     match rw {
230         Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
231         _ => rw,
232     }
233 }
234
235 fn rewrite_imports(
236     context: &RewriteContext,
237     use_items: &[&ast::Item],
238     shape: Shape,
239     span: Span,
240 ) -> Option<String> {
241     let items = itemize_list(
242         context.codemap,
243         use_items.iter(),
244         "",
245         ";",
246         |item| item.span().lo(),
247         |item| item.span().hi(),
248         |item| {
249             let attrs_str = item.attrs.rewrite(context, shape)?;
250
251             let missed_span = if item.attrs.is_empty() {
252                 mk_sp(item.span.lo(), item.span.lo())
253             } else {
254                 mk_sp(item.attrs.last().unwrap().span.hi(), item.span.lo())
255             };
256
257             let item_str = match item.node {
258                 ast::ItemKind::Use(ref tree) => {
259                     rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
260                 }
261                 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
262                 _ => return None,
263             };
264
265             combine_strs_with_missing_comments(
266                 context,
267                 &attrs_str,
268                 &item_str,
269                 missed_span,
270                 shape,
271                 false,
272             )
273         },
274         span.lo(),
275         span.hi(),
276         false,
277     );
278     let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
279     item_pair_vec.sort_by(|a, b| compare_use_items(a.1, b.1).unwrap());
280     let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
281
282     let fmt = ListFormatting {
283         tactic: DefinitiveListTactic::Vertical,
284         separator: "",
285         trailing_separator: SeparatorTactic::Never,
286         separator_place: SeparatorPlace::Back,
287         shape: shape,
288         ends_with_newline: true,
289         preserve_newline: false,
290         config: context.config,
291     };
292
293     write_list(&item_vec, &fmt)
294 }
295
296 impl<'a> FmtVisitor<'a> {
297     pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
298         if use_items.is_empty() {
299             return;
300         }
301
302         let lo = use_items.first().unwrap().span().lo();
303         let hi = use_items.last().unwrap().span().hi();
304         let span = mk_sp(lo, hi);
305         let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
306         self.push_rewrite(span, rw);
307     }
308
309     pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
310         let span = item.span;
311         let shape = self.shape();
312         let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
313         match rw {
314             Some(ref s) if s.is_empty() => {
315                 // Format up to last newline
316                 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
317                 let trimmed_snippet = self.snippet(prev_span).trim_right();
318                 let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
319                 self.format_missing(span_end);
320                 // We have an excessive newline from the removed import.
321                 if self.buffer.ends_with('\n') {
322                     self.buffer.pop();
323                     self.line_number -= 1;
324                 }
325                 self.last_pos = source!(self, span).hi();
326             }
327             Some(ref s) => {
328                 self.format_missing_with_indent(source!(self, span).lo());
329                 self.push_str(s);
330                 self.last_pos = source!(self, span).hi();
331             }
332             None => {
333                 self.format_missing_with_indent(source!(self, span).lo());
334                 self.format_missing(source!(self, span).hi());
335             }
336         }
337     }
338 }
339
340 fn rewrite_nested_use_tree_single(
341     context: &RewriteContext,
342     path_str: &str,
343     tree: &ast::UseTree,
344     shape: Shape,
345 ) -> Option<String> {
346     match tree.kind {
347         ast::UseTreeKind::Simple(rename) => {
348             let ident = path_to_imported_ident(&tree.prefix);
349             let mut item_str = rewrite_prefix(&tree.prefix, context, shape)?;
350             if item_str == "self" {
351                 item_str = "".to_owned();
352             }
353
354             let path_item_str = if path_str.is_empty() {
355                 if item_str.is_empty() {
356                     "self".to_owned()
357                 } else {
358                     item_str
359                 }
360             } else if item_str.is_empty() {
361                 path_str.to_owned()
362             } else {
363                 format!("{}::{}", path_str, item_str)
364             };
365
366             Some(if ident == rename {
367                 path_item_str
368             } else {
369                 format!("{} as {}", path_item_str, rename)
370             })
371         }
372         ast::UseTreeKind::Glob | ast::UseTreeKind::Nested(..) => {
373             // 2 = "::"
374             let nested_shape = shape.offset_left(path_str.len() + 2)?;
375             tree.rewrite(context, nested_shape)
376                 .map(|item| format!("{}::{}", path_str, item))
377         }
378     }
379 }
380
381 #[derive(Eq, PartialEq)]
382 enum ImportItem<'a> {
383     // `self` or `self as a`
384     SelfImport(&'a str),
385     // name_one, name_two, ...
386     SnakeCase(&'a str),
387     // NameOne, NameTwo, ...
388     CamelCase(&'a str),
389     // NAME_ONE, NAME_TWO, ...
390     AllCaps(&'a str),
391     // Failed to format the import item
392     Invalid,
393 }
394
395 impl<'a> ImportItem<'a> {
396     fn from_str(s: &str) -> ImportItem {
397         if s == "self" || s.starts_with("self as") {
398             ImportItem::SelfImport(s)
399         } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
400             ImportItem::SnakeCase(s)
401         } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
402             ImportItem::AllCaps(s)
403         } else {
404             ImportItem::CamelCase(s)
405         }
406     }
407
408     fn from_opt_str(s: Option<&String>) -> ImportItem {
409         s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
410     }
411
412     fn to_str(&self) -> Option<&str> {
413         match *self {
414             ImportItem::SelfImport(s)
415             | ImportItem::SnakeCase(s)
416             | ImportItem::CamelCase(s)
417             | ImportItem::AllCaps(s) => Some(s),
418             ImportItem::Invalid => None,
419         }
420     }
421
422     fn to_u32(&self) -> u32 {
423         match *self {
424             ImportItem::SelfImport(..) => 0,
425             ImportItem::SnakeCase(..) => 1,
426             ImportItem::CamelCase(..) => 2,
427             ImportItem::AllCaps(..) => 3,
428             ImportItem::Invalid => 4,
429         }
430     }
431 }
432
433 impl<'a> PartialOrd for ImportItem<'a> {
434     fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
435         Some(self.cmp(other))
436     }
437 }
438
439 impl<'a> Ord for ImportItem<'a> {
440     fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
441         let res = self.to_u32().cmp(&other.to_u32());
442         if res != Ordering::Equal {
443             return res;
444         }
445         self.to_str().map_or(Ordering::Greater, |self_str| {
446             other
447                 .to_str()
448                 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
449         })
450     }
451 }
452
453 // Pretty prints a multi-item import.
454 // If the path list is empty, it leaves the braces empty.
455 fn rewrite_nested_use_tree(
456     shape: Shape,
457     path: &ast::Path,
458     trees: &[(ast::UseTree, ast::NodeId)],
459     span: Span,
460     context: &RewriteContext,
461 ) -> Option<String> {
462     // Returns a different option to distinguish `::foo` and `foo`
463     let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
464
465     match trees.len() {
466         0 => {
467             let shape = shape.offset_left(path_str.len() + 3)?;
468             return rewrite_path(context, PathContext::Import, None, path, shape)
469                 .map(|path_str| format!("{}::{{}}", path_str));
470         }
471         1 => {
472             return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
473         }
474         _ => (),
475     }
476
477     let path_str = if path_str.is_empty() {
478         path_str
479     } else {
480         format!("{}::", path_str)
481     };
482
483     // 2 = "{}"
484     let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
485     let nested_indent = match context.config.imports_indent() {
486         IndentStyle::Block => shape.indent.block_indent(context.config),
487         // 1 = `{`
488         IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
489     };
490
491     let nested_shape = match context.config.imports_indent() {
492         IndentStyle::Block => Shape::indented(nested_indent, context.config).sub_width(1)?,
493         IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
494     };
495
496     let mut items = {
497         // Dummy value, see explanation below.
498         let mut items = vec![ListItem::from_str("")];
499         let iter = itemize_list(
500             context.codemap,
501             trees.iter().map(|tree| &tree.0),
502             "}",
503             ",",
504             |tree| tree.span.lo(),
505             |tree| tree.span.hi(),
506             |tree| tree.rewrite(context, nested_shape),
507             context.codemap.span_after(span, "{"),
508             span.hi(),
509             false,
510         );
511         items.extend(iter);
512         items
513     };
514
515     // We prefixed the item list with a dummy value so that we can
516     // potentially move "self" to the front of the vector without touching
517     // the rest of the items.
518     let has_self = move_self_to_front(&mut items);
519     let first_index = if has_self { 0 } else { 1 };
520
521     if context.config.reorder_imported_names() {
522         items[1..].sort_by(|a, b| {
523             let a = ImportItem::from_opt_str(a.item.as_ref());
524             let b = ImportItem::from_opt_str(b.item.as_ref());
525             a.cmp(&b)
526         });
527     }
528
529     let tactic = definitive_tactic(
530         &items[first_index..],
531         context.config.imports_layout(),
532         Separator::Comma,
533         remaining_width,
534     );
535
536     let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
537         && tactic != DefinitiveListTactic::Horizontal;
538
539     let fmt = ListFormatting {
540         tactic: tactic,
541         separator: ",",
542         trailing_separator: if ends_with_newline {
543             context.config.trailing_comma()
544         } else {
545             SeparatorTactic::Never
546         },
547         separator_place: SeparatorPlace::Back,
548         shape: nested_shape,
549         ends_with_newline: ends_with_newline,
550         preserve_newline: true,
551         config: context.config,
552     };
553     let list_str = write_list(&items[first_index..], &fmt)?;
554
555     let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
556     {
557         format!(
558             "{}{{\n{}{}\n{}}}",
559             path_str,
560             nested_shape.indent.to_string(context.config),
561             list_str,
562             shape.indent.to_string(context.config)
563         )
564     } else {
565         format!("{}{{{}}}", path_str, list_str)
566     };
567     Some(result)
568 }
569
570 // Returns true when self item was found.
571 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
572     match items
573         .iter()
574         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
575     {
576         Some(pos) => {
577             items[0] = items.remove(pos);
578             true
579         }
580         None => false,
581     }
582 }
583
584 fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
585     path.segments.last().unwrap().identifier
586 }