From 92b3f69934efb61433223fc10888746e0c705afe Mon Sep 17 00:00:00 2001 From: cassiersg Date: Mon, 20 Jul 2015 21:33:23 +0200 Subject: [PATCH] Add a helper method to format imports --- src/visitor.rs | 62 +++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/src/visitor.rs b/src/visitor.rs index 375107c00ea..6e550c2f330 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -164,33 +164,7 @@ fn visit_item(&mut self, item: &'v ast::Item) { match item.node { ast::Item_::ItemUse(ref vp) => { - let vis = utils::format_visibility(item.vis); - let offset = self.block_indent + vis.len() + "use ".len(); - let context = RewriteContext { - codemap: self.codemap, config: self.config, block_indent: self.block_indent }; - // 1 = ";" - match vp.rewrite(&context, self.config.max_width - offset - 1, offset) { - Some(ref s) if s.len() == 0 => { - // Format up to last newline - let span = codemap::mk_sp(self.last_pos, item.span.lo); - let span_end = match self.snippet(span).rfind('\n') { - Some(offset) => self.last_pos + BytePos(offset as u32), - None => item.span.lo - }; - self.format_missing(span_end); - self.last_pos = item.span.hi; - } - Some(ref s) => { - let s = format!("{}use {};", vis, s); - self.format_missing_with_indent(item.span.lo); - self.changes.push_str_span(item.span, &s); - self.last_pos = item.span.hi; - } - None => { - self.format_missing_with_indent(item.span.lo); - } - } - visit::walk_item(self, item); + self.format_import(item.vis, vp, item.span); } ast::Item_::ItemImpl(..) | ast::Item_::ItemTrait(..) => { @@ -211,7 +185,6 @@ fn visit_item(&mut self, item: &'v ast::Item) { def, generics, item.span); - self.last_pos = item.span.hi; } ast::Item_::ItemEnum(ref def, ref generics) => { self.format_missing_with_indent(item.span.lo); @@ -408,4 +381,37 @@ fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) { self.last_pos = last_pos; self.block_indent = block_indent; } + + fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) { + let vis = utils::format_visibility(vis); + let offset = self.block_indent + vis.len() + "use ".len(); + let context = RewriteContext { + codemap: self.codemap, + config: self.config, + block_indent: self.block_indent, + }; + // 1 = ";" + match vp.rewrite(&context, self.config.max_width - offset - 1, offset) { + Some(ref s) if s.len() == 0 => { + // Format up to last newline + let prev_span = codemap::mk_sp(self.last_pos, span.lo); + let span_end = match self.snippet(prev_span).rfind('\n') { + Some(offset) => self.last_pos + BytePos(offset as u32), + None => span.lo + }; + self.format_missing(span_end); + self.last_pos = span.hi; + } + Some(ref s) => { + let s = format!("{}use {};", vis, s); + self.format_missing_with_indent(span.lo); + self.changes.push_str_span(span, &s); + self.last_pos = span.hi; + } + None => { + self.format_missing_with_indent(span.lo); + self.format_missing(span.hi); + } + } + } }