From 106625bc5c43da24673c84c2e85e082e3f591a15 Mon Sep 17 00:00:00 2001 From: topecongiro Date: Thu, 5 Oct 2017 16:17:59 +0900 Subject: [PATCH] Remove trailing whitespaces in macro def --- src/comment.rs | 29 +++++++++++++++++++++++++++++ src/visitor.rs | 6 +++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index a236c2699a6..3c863086a36 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -505,6 +505,35 @@ pub fn contains_comment(text: &str) -> bool { CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment()) } +/// Remove trailing spaces from the specified snippet. We do not remove spaces +/// inside strings or comments. +pub fn remove_trailing_white_spaces(text: &str) -> String { + let mut buffer = String::with_capacity(text.len()); + let mut space_buffer = String::with_capacity(128); + for (char_kind, c) in CharClasses::new(text.chars()) { + match c { + '\n' => { + if char_kind == FullCodeCharKind::InString { + buffer.push_str(&space_buffer); + } + space_buffer.clear(); + buffer.push('\n'); + } + _ if c.is_whitespace() => { + space_buffer.push(c); + } + _ => { + if !space_buffer.is_empty() { + buffer.push_str(&space_buffer); + space_buffer.clear(); + } + buffer.push(c); + } + } + } + buffer +} + struct CharClasses where T: Iterator, diff --git a/src/visitor.rs b/src/visitor.rs index f6f46ca6188..29eaea39a7f 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -18,8 +18,8 @@ use spanned::Spanned; use codemap::{LineRangeUtils, SpanUtils}; -use comment::{contains_comment, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices, - FindUncommented}; +use comment::{contains_comment, recover_missing_comment_in_span, remove_trailing_white_spaces, + CodeCharKind, CommentCodeSlices, FindUncommented}; use comment::rewrite_comment; use config::{BraceStyle, Config}; use items::{format_impl, format_struct, format_struct_struct, format_trait, @@ -470,7 +470,7 @@ pub fn visit_item(&mut self, item: &ast::Item) { } ast::ItemKind::MacroDef(..) => { // FIXME(#1539): macros 2.0 - let mac_snippet = Some(self.snippet(item.span)); + let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span))); self.push_rewrite(item.span, mac_snippet); } } -- 2.44.0