From 384d985df9648027e26125a5d2e38dfbd4a010a3 Mon Sep 17 00:00:00 2001 From: topecongiro Date: Wed, 14 Jun 2017 00:08:31 +0900 Subject: [PATCH] Do not rely on format_missing for rewriting attributes --- src/expr.rs | 38 +++++++++++++++++++++++++++++++++----- src/visitor.rs | 17 ++++++++++++++--- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index 80c89a3a91b..1e92b5b9368 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -47,16 +47,45 @@ enum ExprType { SubExpression, } +fn combine_attr_and_expr( + context: &RewriteContext, + shape: Shape, + attr_str: &str, + expr_str: &str, +) -> String { + let separator = if attr_str.is_empty() { + String::new() + } else { + if expr_str.contains('\n') || attr_str.contains('\n') || + attr_str.len() + expr_str.len() > shape.width + { + format!("\n{}", shape.indent.to_string(context.config)) + } else { + String::from(" ") + } + }; + format!("{}{}{}", attr_str, separator, expr_str) +} + fn format_expr( expr: &ast::Expr, expr_type: ExprType, context: &RewriteContext, shape: Shape, ) -> Option { - if contains_skip(&*expr.attrs) { - return Some(context.snippet(expr.span)); - } let attr_rw = (&*expr.attrs).rewrite(context, shape); + if contains_skip(&*expr.attrs) { + if let Some(attr_str) = attr_rw { + return Some(combine_attr_and_expr( + context, + shape, + &attr_str, + &context.snippet(expr.span), + )); + } else { + return Some(context.snippet(expr.span)); + } + } let expr_rw = match expr.node { ast::ExprKind::Array(ref expr_vec) => { rewrite_array( @@ -289,9 +318,8 @@ fn format_expr( }; match (attr_rw, expr_rw) { (Some(attr_str), Some(expr_str)) => { - let space = if attr_str.is_empty() { "" } else { " " }; recover_comment_removed( - format!("{}{}{}", attr_str, space, expr_str), + combine_attr_and_expr(context, shape, &attr_str, &expr_str), expr.span, context, shape, diff --git a/src/visitor.rs b/src/visitor.rs index 6358cc7531f..08ff3cd4c61 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -82,15 +82,26 @@ impl<'a> FmtVisitor<'a> { ast::StmtKind::Item(ref item) => { self.visit_item(item); } - ast::StmtKind::Local(..) | - ast::StmtKind::Expr(..) | - ast::StmtKind::Semi(..) => { + ast::StmtKind::Local(..) => { let rewrite = stmt.rewrite( &self.get_context(), Shape::indented(self.block_indent, self.config), ); self.push_rewrite(stmt.span, rewrite); } + ast::StmtKind::Expr(ref expr) | + ast::StmtKind::Semi(ref expr) => { + let rewrite = stmt.rewrite( + &self.get_context(), + Shape::indented(self.block_indent, self.config), + ); + let span = if expr.attrs.is_empty() { + stmt.span + } else { + mk_sp(expr.attrs[0].span.lo, stmt.span.hi) + }; + self.push_rewrite(span, rewrite) + } ast::StmtKind::Mac(ref mac) => { let (ref mac, _macro_style, _) = **mac; self.visit_mac(mac, None, MacroPosition::Statement);