]> git.lizzy.rs Git - rust.git/blobdiff - src/macros.rs
Merge pull request #3129 from otavio/issue-3104
[rust.git] / src / macros.rs
index dab27d8a073bf08930fd0bbc6cb37a5290a03306..d378bb8ffb1499595184c6c96034906579d53f7d 100644 (file)
 use syntax::ThinVec;
 use syntax::{ast, ptr};
 
-use comment::{
-    contains_comment, remove_trailing_white_spaces, CharClasses, FindUncommented, FullCodeCharKind,
-    LineClasses,
-};
+use comment::{contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses};
 use expr::rewrite_array;
 use lists::{itemize_list, write_list, ListFormatting};
 use overflow;
@@ -43,7 +40,7 @@
 use shape::{Indent, Shape};
 use source_map::SpanUtils;
 use spanned::Spanned;
-use utils::{format_visibility, mk_sp, rewrite_ident, wrap_str};
+use utils::{format_visibility, mk_sp, remove_trailing_white_spaces, rewrite_ident, wrap_str};
 use visitor::FmtVisitor;
 
 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
@@ -432,7 +429,7 @@ pub fn rewrite_macro_def(
             Some(v) => Some(v),
             // if the rewrite returned None because a macro could not be rewritten, then return the
             // original body
-            None if *context.macro_rewrite_failure.borrow() == true => {
+            None if *context.macro_rewrite_failure.borrow() => {
                 Some(context.snippet(branch.body).trim().to_string())
             }
             None => None,
@@ -867,7 +864,8 @@ fn need_space_prefix(&self) -> bool {
 
     /// Returns a collection of parsed macro def's arguments.
     pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
-        let mut iter = (tokens.into(): TokenStream).trees();
+        let stream: TokenStream = tokens.into();
+        let mut iter = stream.trees();
 
         while let Some(ref tok) = iter.next() {
             match tok {
@@ -983,7 +981,7 @@ fn format_macro_args(
 ) -> Option<String> {
     if !context.config.format_macro_matchers() {
         let token_stream: TokenStream = toks.into();
-        let span = span_for_token_stream(token_stream);
+        let span = span_for_token_stream(&token_stream);
         return Some(match span {
             Some(span) => context.snippet(span).to_owned(),
             None => String::new(),
@@ -993,7 +991,7 @@ fn format_macro_args(
     wrap_macro_args(context, &parsed_args, shape)
 }
 
-fn span_for_token_stream(token_stream: TokenStream) -> Option<Span> {
+fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
     token_stream.trees().next().map(|tt| tt.span())
 }
 
@@ -1073,7 +1071,7 @@ fn next_space(tok: &Token) -> SpaceState {
 /// when the macro is not an instance of try! (or parsing the inner expression
 /// failed).
 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
-    if &format!("{}", mac.node.path) == "try" {
+    if &mac.node.path.to_string() == "try" {
         let ts: TokenStream = mac.node.tts.clone().into();
         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
 
@@ -1168,22 +1166,24 @@ fn indent_macro_snippet(
         .min()?;
 
     Some(
-        first_line + "\n" + &trimmed_lines
-            .iter()
-            .map(
-                |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
-                    _ if !trimmed => line.to_owned(),
-                    Some(original_indent_width) => {
-                        let new_indent_width = indent.width() + original_indent_width
-                            .saturating_sub(min_prefix_space_width);
-                        let new_indent = Indent::from_width(context.config, new_indent_width);
-                        format!("{}{}", new_indent.to_string(context.config), line)
-                    }
-                    None => String::new(),
-                },
-            )
-            .collect::<Vec<_>>()
-            .join("\n"),
+        first_line
+            + "\n"
+            + &trimmed_lines
+                .iter()
+                .map(
+                    |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
+                        _ if !trimmed => line.to_owned(),
+                        Some(original_indent_width) => {
+                            let new_indent_width = indent.width()
+                                + original_indent_width.saturating_sub(min_prefix_space_width);
+                            let new_indent = Indent::from_width(context.config, new_indent_width);
+                            format!("{}{}", new_indent.to_string(context.config), line)
+                        }
+                        None => String::new(),
+                    },
+                )
+                .collect::<Vec<_>>()
+                .join("\n"),
     )
 }
 
@@ -1323,7 +1323,7 @@ fn rewrite(
         config.set().max_width(new_width);
 
         // First try to format as items, then as statements.
-        let new_body = match ::format_snippet(&body_str, &config) {
+        let new_body_snippet = match ::format_snippet(&body_str, &config) {
             Some(new_body) => new_body,
             None => {
                 let new_width = new_width + config.tab_spaces();
@@ -1334,15 +1334,23 @@ fn rewrite(
                 }
             }
         };
-        let new_body = wrap_str(new_body, config.max_width(), shape)?;
+        let new_body = wrap_str(
+            new_body_snippet.snippet.to_string(),
+            config.max_width(),
+            shape,
+        )?;
 
         // Indent the body since it is in a block.
         let indent_str = body_indent.to_string(&config);
         let mut new_body = LineClasses::new(new_body.trim_right())
+            .enumerate()
             .fold(
                 (String::new(), true),
-                |(mut s, need_indent), (kind, ref l)| {
-                    if !l.is_empty() && need_indent {
+                |(mut s, need_indent), (i, (kind, ref l))| {
+                    if !l.is_empty()
+                        && need_indent
+                        && !new_body_snippet.is_line_non_formatted(i + 1)
+                    {
                         s += &indent_str;
                     }
                     (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
@@ -1396,21 +1404,23 @@ fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream)
     result.push_str("lazy_static! {");
     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
 
-    macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
-        match parser.$method($($arg,)*) {
-            Ok(val) => {
-                if parser.sess.span_diagnostic.has_errors() {
+    macro_rules! parse_or {
+        ($method:ident $(,)* $($arg:expr),* $(,)*) => {
+            match parser.$method($($arg,)*) {
+                Ok(val) => {
+                    if parser.sess.span_diagnostic.has_errors() {
+                        parser.sess.span_diagnostic.reset_err_count();
+                        return None;
+                    } else {
+                        val
+                    }
+                }
+                Err(mut err) => {
+                    err.cancel();
                     parser.sess.span_diagnostic.reset_err_count();
                     return None;
-                } else {
-                    val
                 }
             }
-            Err(mut err) => {
-                err.cancel();
-                parser.sess.span_diagnostic.reset_err_count();
-                return None;
-            }
         }
     }
 
@@ -1491,5 +1501,5 @@ fn rewrite_macro_with_items(
     result.push_str(&shape.indent.to_string_with_newline(context.config));
     result.push_str(closer);
     result.push_str(trailing_semicolon);
-    return Some(result);
+    Some(result)
 }