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.
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.
11 use std::cmp::Ordering;
12 use std::borrow::Borrow;
15 use std::iter::ExactSizeIterator;
18 use {Indent, Spanned};
19 use codemap::SpanUtils;
20 use rewrite::{Rewrite, RewriteContext};
21 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
22 DefinitiveListTactic, definitive_tactic, ListItem, format_item_list};
23 use string::{StringFormat, rewrite_string};
24 use utils::{extra_offset, last_line_width, wrap_str, binary_search, first_line_width,
25 semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr};
26 use visitor::FmtVisitor;
27 use config::{Config, StructLitStyle, MultilineStyle, ElseIfBraceStyle, ControlBraceStyle};
28 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
29 use types::rewrite_path;
30 use items::{span_lo_for_arg, span_hi_for_arg};
31 use chains::rewrite_chain;
32 use macros::{rewrite_macro, MacroPosition};
34 use syntax::{ast, ptr};
35 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
36 use syntax::parse::classify;
38 impl Rewrite for ast::Expr {
39 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
40 format_expr(self, ExprType::SubExpression, context, width, offset)
50 fn format_expr(expr: &ast::Expr,
52 context: &RewriteContext,
56 let result = match expr.node {
57 ast::ExprKind::Vec(ref expr_vec) => {
58 rewrite_array(expr_vec.iter().map(|e| &**e),
59 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
64 ast::ExprKind::Lit(ref l) => {
66 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
67 rewrite_string_lit(context, l.span, width, offset)
70 wrap_str(context.snippet(expr.span),
71 context.config.max_width,
77 ast::ExprKind::Call(ref callee, ref args) => {
78 let inner_span = mk_sp(callee.span.hi, expr.span.hi);
79 rewrite_call(context, &**callee, args, inner_span, width, offset)
81 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, width, offset),
82 ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
83 rewrite_binary_op(context, op, lhs, rhs, width, offset)
85 ast::ExprKind::Unary(ref op, ref subexpr) => {
86 rewrite_unary_op(context, op, subexpr, width, offset)
88 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
89 rewrite_struct_lit(context,
92 base.as_ref().map(|e| &**e),
97 ast::ExprKind::Tup(ref items) => {
98 rewrite_tuple(context,
99 items.iter().map(|x| &**x),
104 ast::ExprKind::While(ref cond, ref block, label) => {
105 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
107 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
108 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
110 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
111 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
113 ast::ExprKind::Loop(ref block, label) => {
114 Loop::new_loop(block, label).rewrite(context, width, offset)
116 ast::ExprKind::Block(ref block) => block.rewrite(context, width, offset),
117 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
118 rewrite_if_else(context,
122 else_block.as_ref().map(|e| &**e),
129 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
130 rewrite_if_else(context,
134 else_block.as_ref().map(|e| &**e),
141 ast::ExprKind::Match(ref cond, ref arms) => {
142 rewrite_match(context, cond, arms, width, offset, expr.span)
144 ast::ExprKind::Path(ref qself, ref path) => {
145 rewrite_path(context, true, qself.as_ref(), path, width, offset)
147 ast::ExprKind::Assign(ref lhs, ref rhs) => {
148 rewrite_assignment(context, lhs, rhs, None, width, offset)
150 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
151 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
153 ast::ExprKind::Continue(ref opt_ident) => {
154 let id_str = match *opt_ident {
155 Some(ident) => format!(" {}", ident.node),
156 None => String::new(),
158 wrap_str(format!("continue{}", id_str),
159 context.config.max_width,
163 ast::ExprKind::Break(ref opt_ident) => {
164 let id_str = match *opt_ident {
165 Some(ident) => format!(" {}", ident.node),
166 None => String::new(),
168 wrap_str(format!("break{}", id_str),
169 context.config.max_width,
173 ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
174 rewrite_closure(capture, fn_decl, body, expr.span, context, width, offset)
176 ast::ExprKind::Try(..) |
177 ast::ExprKind::Field(..) |
178 ast::ExprKind::TupField(..) |
179 ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, width, offset),
180 ast::ExprKind::Mac(ref mac) => {
181 // Failure to rewrite a marco should not imply failure to
182 // rewrite the expression.
183 rewrite_macro(mac, None, context, width, offset, MacroPosition::Expression)
185 wrap_str(context.snippet(expr.span),
186 context.config.max_width,
191 ast::ExprKind::Ret(None) => {
192 wrap_str("return".to_owned(), context.config.max_width, width, offset)
194 ast::ExprKind::Ret(Some(ref expr)) => {
195 rewrite_unary_prefix(context, "return ", &**expr, width, offset)
197 ast::ExprKind::Box(ref expr) => {
198 rewrite_unary_prefix(context, "box ", &**expr, width, offset)
200 ast::ExprKind::AddrOf(mutability, ref expr) => {
201 rewrite_expr_addrof(context, mutability, expr, width, offset)
203 ast::ExprKind::Cast(ref expr, ref ty) => {
204 rewrite_pair(&**expr, &**ty, "", " as ", "", context, width, offset)
206 ast::ExprKind::Type(ref expr, ref ty) => {
207 rewrite_pair(&**expr, &**ty, "", ": ", "", context, width, offset)
209 ast::ExprKind::Index(ref expr, ref index) => {
210 let use_spaces = context.config.spaces_within_square_brackets;
211 let lbr = if use_spaces { "[ " } else { "[" };
212 let rbr = if use_spaces { " ]" } else { "]" };
213 rewrite_pair(&**expr, &**index, "", lbr, rbr, context, width, offset)
215 ast::ExprKind::Repeat(ref expr, ref repeats) => {
216 let use_spaces = context.config.spaces_within_square_brackets;
217 let lbr = if use_spaces { "[ " } else { "[" };
218 let rbr = if use_spaces { " ]" } else { "]" };
219 rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, width, offset)
221 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
222 let delim = match limits {
223 ast::RangeLimits::HalfOpen => "..",
224 ast::RangeLimits::Closed => "...",
227 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
228 (Some(ref lhs), Some(ref rhs)) => {
229 let sp_delim = if context.config.spaces_around_ranges {
230 format!(" {} ", delim)
234 rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, width, offset)
236 (None, Some(ref rhs)) => {
237 let sp_delim = if context.config.spaces_around_ranges {
238 format!("{} ", delim)
242 rewrite_unary_prefix(context, &sp_delim, &**rhs, width, offset)
244 (Some(ref lhs), None) => {
245 let sp_delim = if context.config.spaces_around_ranges {
246 format!(" {}", delim)
250 rewrite_unary_suffix(context, &sp_delim, &**lhs, width, offset)
252 (None, None) => wrap_str(delim.into(), context.config.max_width, width, offset),
255 // We do not format these expressions yet, but they should still
256 // satisfy our width restrictions.
257 ast::ExprKind::InPlace(..) |
258 ast::ExprKind::InlineAsm(..) => {
259 wrap_str(context.snippet(expr.span),
260 context.config.max_width,
265 result.and_then(|res| recover_comment_removed(res, expr.span, context, width, offset))
268 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
273 context: &RewriteContext,
280 let max_width = try_opt!(width.checked_sub(prefix.len() + infix.len() + suffix.len()));
282 binary_search(1, max_width, |lhs_budget| {
283 let lhs_offset = offset + prefix.len();
284 let lhs_str = match lhs.rewrite(context, lhs_budget, lhs_offset) {
285 Some(result) => result,
286 None => return Err(Ordering::Greater),
289 let last_line_width = last_line_width(&lhs_str);
290 let rhs_budget = match max_width.checked_sub(last_line_width) {
292 None => return Err(Ordering::Less),
294 let rhs_indent = offset + last_line_width + prefix.len() + infix.len();
296 let rhs_str = match rhs.rewrite(context, rhs_budget, rhs_indent) {
297 Some(result) => result,
298 None => return Err(Ordering::Less),
301 Ok(format!("{}{}{}{}{}", prefix, lhs_str, infix, rhs_str, suffix))
305 pub fn rewrite_array<'a, I>(expr_iter: I,
307 context: &RewriteContext,
311 where I: Iterator<Item = &'a ast::Expr>
313 let bracket_size = if context.config.spaces_within_square_brackets {
318 let offset = offset + bracket_size;
319 let inner_context = &RewriteContext { block_indent: offset, ..*context };
320 let max_item_width = try_opt!(width.checked_sub(bracket_size * 2));
321 let items = itemize_list(context.codemap,
326 |item| item.rewrite(inner_context, max_item_width, offset),
329 .collect::<Vec<_>>();
331 let has_long_item = try_opt!(items.iter()
332 .map(|li| li.item.as_ref().map(|s| s.len() > 10))
333 .fold(Some(false), |acc, x| acc.and_then(|y| x.map(|x| x || y))));
335 let tactic = if has_long_item || items.iter().any(ListItem::is_multiline) {
336 definitive_tactic(&items, ListTactic::HorizontalVertical, max_item_width)
338 DefinitiveListTactic::Mixed
341 let fmt = ListFormatting {
344 trailing_separator: SeparatorTactic::Never,
346 width: max_item_width,
347 ends_with_newline: false,
348 config: context.config,
350 let list_str = try_opt!(write_list(&items, &fmt));
352 Some(if context.config.spaces_within_square_brackets && list_str.len() > 0 {
353 format!("[ {} ]", list_str)
355 format!("[{}]", list_str)
359 // This functions is pretty messy because of the rules around closures and blocks:
361 // * if there is a return type, then there must be braces,
362 // * given a closure with braces, whether that is parsed to give an inner block
363 // or not depends on if there is a return type and if there are statements
365 // * if the first expression in the body ends with a block (i.e., is a
366 // statement without needing a semi-colon), then adding or removing braces
367 // can change whether it is treated as an expression or statement.
368 fn rewrite_closure(capture: ast::CaptureBy,
369 fn_decl: &ast::FnDecl,
372 context: &RewriteContext,
376 let mover = if capture == ast::CaptureBy::Value {
381 let offset = offset + mover.len();
383 // 4 = "|| {".len(), which is overconservative when the closure consists of
384 // a single expression.
385 let budget = try_opt!(width.checked_sub(4 + mover.len()));
387 let argument_offset = offset + 1;
388 let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
390 // 1 = space between arguments and return type.
391 let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
393 let arg_items = itemize_list(context.codemap,
394 fn_decl.inputs.iter(),
396 |arg| span_lo_for_arg(arg),
397 |arg| span_hi_for_arg(arg),
398 |arg| arg.rewrite(context, budget, argument_offset),
399 context.codemap.span_after(span, "|"),
401 let item_vec = arg_items.collect::<Vec<_>>();
402 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
403 let budget = match tactic {
404 DefinitiveListTactic::Horizontal => horizontal_budget,
408 let fmt = ListFormatting {
411 trailing_separator: SeparatorTactic::Never,
412 indent: argument_offset,
414 ends_with_newline: false,
415 config: context.config,
417 let list_str = try_opt!(write_list(&item_vec, &fmt));
418 let mut prefix = format!("{}|{}|", mover, list_str);
420 if !ret_str.is_empty() {
421 if prefix.contains('\n') {
423 prefix.push_str(&argument_offset.to_string(context.config));
427 prefix.push_str(&ret_str);
430 // 1 = space between `|...|` and body.
431 let extra_offset = extra_offset(&prefix, offset) + 1;
432 let budget = try_opt!(width.checked_sub(extra_offset));
433 let total_offset = offset + extra_offset;
435 if let ast::ExprKind::Block(ref block) = body.node {
436 // The body of the closure is a block.
437 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
438 return Some(format!("{} {{}}", prefix));
441 // Figure out if the block is necessary.
442 let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
443 block_contains_comment(block, context.codemap) ||
444 prefix.contains('\n');
446 if ret_str.is_empty() && !needs_block {
447 // lock.stmts.len() == 1
448 if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
449 if let Some(rw) = rewrite_closure_expr(expr,
460 // We need braces, but we might still prefer a one-liner.
461 let stmt = &block.stmts[0];
462 // 4 = braces and spaces.
463 let mut rewrite = stmt.rewrite(context, try_opt!(budget.checked_sub(4)), total_offset);
465 // Checks if rewrite succeeded and fits on a single line.
466 rewrite = and_one_line(rewrite);
468 if let Some(rewrite) = rewrite {
469 return Some(format!("{} {{ {} }}", prefix, rewrite));
473 // Either we require a block, or tried without and failed.
474 return rewrite_closure_block(&block, prefix, context, budget);
477 if let Some(rw) = rewrite_closure_expr(body, &prefix, context, budget, total_offset) {
481 // The closure originally had a non-block expression, but we can't fit on
482 // one line, so we'll insert a block.
483 let block = ast::Block {
484 stmts: vec![ast::Stmt {
485 id: ast::NodeId::new(0),
486 node: ast::StmtKind::Expr(ptr::P(body.clone())),
489 id: ast::NodeId::new(0),
490 rules: ast::BlockCheckMode::Default,
493 return rewrite_closure_block(&block, prefix, context, budget);
495 fn rewrite_closure_expr(expr: &ast::Expr,
497 context: &RewriteContext,
501 let mut rewrite = expr.rewrite(context, budget, offset);
502 if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
503 rewrite = and_one_line(rewrite);
505 rewrite.map(|rw| format!("{} {}", prefix, rw))
508 fn rewrite_closure_block(block: &ast::Block,
510 context: &RewriteContext,
513 // Start with visual indent, then fall back to block indent if the
515 let rewrite = try_opt!(block.rewrite(&context, budget, Indent::empty()));
517 let block_threshold = context.config.closure_block_indent_threshold;
518 if block_threshold < 0 || rewrite.matches('\n').count() <= block_threshold as usize {
519 return Some(format!("{} {}", prefix, rewrite));
522 // The body of the closure is big enough to be block indented, that
523 // means we must re-format.
524 let mut context = context.clone();
525 context.block_indent.alignment = 0;
526 let rewrite = try_opt!(block.rewrite(&context, budget, Indent::empty()));
527 Some(format!("{} {}", prefix, rewrite))
530 // // This is where we figure out whether to use braces or not.
531 // let mut had_braces = true;
532 // let mut inner_block = body;
534 // let mut trailing_expr = stmt_expr(&inner_block.stmts[inner_block.stmts.len() - 1]);
536 // // If there is an inner block and we can ignore it, do so.
537 // if body.stmts.len() == 1 && trailing_expr.is_some() {
538 // if let Some(ref inner) = stmt_block(&inner_block.stmts[0]) {
539 // inner_block = inner;
540 // trailing_expr = if inner_block.stmts.is_empty() {
543 // stmt_expr(&inner_block.stmts[inner_block.stmts.len() - 1])
545 // } else if !force_block {
546 // had_braces = false;
550 // let try_single_line = is_simple_block(inner_block, context.codemap) &&
551 // inner_block.rules == ast::BlockCheckMode::Default;
554 // if try_single_line && !force_block {
555 // let must_preserve_braces =
556 // trailing_expr.is_none() ||
557 // !classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(trailing_expr.unwrap()));
558 // if !(must_preserve_braces && had_braces) &&
559 // (must_preserve_braces || !prefix.contains('\n')) {
560 // // If we got here, then we can try to format without braces.
562 // let inner_expr = &inner_block.stmts[0];
563 // let mut rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
565 // if must_preserve_braces {
566 // // If we are here, then failure to rewrite is unacceptable.
567 // if rewrite.is_none() {
571 // // Checks if rewrite succeeded and fits on a single line.
572 // rewrite = and_one_line(rewrite);
575 // if let Some(rewrite) = rewrite {
576 // return Some(format!("{} {}", prefix, rewrite));
581 // // If we fell through the above block, then we need braces, but we might
582 // // still prefer a one-liner (we might also have fallen through because of
583 // // lack of space).
584 // if try_single_line && !prefix.contains('\n') {
585 // let inner_expr = &inner_block.stmts[0];
586 // // 4 = braces and spaces.
587 // let mut rewrite = inner_expr.rewrite(context,
588 // try_opt!(budget.checked_sub(4)),
589 // offset + extra_offset);
591 // // Checks if rewrite succeeded and fits on a single line.
592 // rewrite = and_one_line(rewrite);
594 // if let Some(rewrite) = rewrite {
595 // return Some(format!("{} {{ {} }}", prefix, rewrite));
599 // // We couldn't format the closure body as a single line expression; fall
600 // // back to block formatting.
601 // let mut context = context.clone();
602 // context.block_indent.alignment = 0;
603 // let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty()));
604 // Some(format!("{} {}", prefix, body_rewrite))
607 fn and_one_line(x: Option<String>) -> Option<String> {
608 x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
611 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
612 block_str.map(|block_str| if block_str.starts_with('{') && budget >= 2 &&
613 (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() ==
614 block_str.len() - 2) {
621 impl Rewrite for ast::Block {
622 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
623 // width is used only for the single line case: either the empty block `{}`,
624 // or an unsafe expression `unsafe { e }`.
626 let user_str = context.snippet(self.span);
627 if user_str == "{}" && width >= 2 {
628 return Some(user_str);
631 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
632 visitor.block_indent = context.block_indent;
634 let prefix = match self.rules {
635 ast::BlockCheckMode::Unsafe(..) => {
636 let snippet = context.snippet(self.span);
637 let open_pos = try_opt!(snippet.find_uncommented("{"));
638 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
640 // Extract comment between unsafe and block start.
641 let trimmed = &snippet[6..open_pos].trim();
643 let prefix = if !trimmed.is_empty() {
644 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
645 let budget = try_opt!(width.checked_sub(9));
646 format!("unsafe {} ",
647 try_opt!(rewrite_comment(trimmed,
656 if is_simple_block(self, context.codemap) && prefix.len() < width {
657 let expr_str = self.stmts[0].rewrite(context, width - prefix.len(), offset);
658 let expr_str = try_opt!(expr_str);
659 let result = format!("{}{{ {} }}", prefix, expr_str);
660 if result.len() <= width && !result.contains('\n') {
667 ast::BlockCheckMode::Default => {
668 visitor.last_pos = self.span.lo;
674 visitor.visit_block(self);
676 Some(format!("{}{}", prefix, visitor.buffer))
680 impl Rewrite for ast::Stmt {
681 fn rewrite(&self, context: &RewriteContext, _width: usize, offset: Indent) -> Option<String> {
682 let result = match self.node {
683 ast::StmtKind::Local(ref local) => {
684 local.rewrite(context, context.config.max_width, offset)
686 ast::StmtKind::Expr(ref ex) |
687 ast::StmtKind::Semi(ref ex) => {
688 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
692 ast::StmtKind::Expr(_) => ExprType::SubExpression,
693 ast::StmtKind::Semi(_) => ExprType::Statement,
697 context.config.max_width - offset.width() - suffix.len(),
701 ast::StmtKind::Mac(..) |
702 ast::StmtKind::Item(..) => None,
704 result.and_then(|res| recover_comment_removed(res, self.span, context, _width, offset))
708 // Abstraction over for, while and loop expressions
710 cond: Option<&'a ast::Expr>,
711 block: &'a ast::Block,
712 label: Option<ast::SpannedIdent>,
713 pat: Option<&'a ast::Pat>,
720 fn new_loop(block: &'a ast::Block, label: Option<ast::SpannedIdent>) -> Loop<'a> {
732 fn new_while(pat: Option<&'a ast::Pat>,
734 block: &'a ast::Block,
735 label: Option<ast::SpannedIdent>)
751 fn new_for(pat: &'a ast::Pat,
753 block: &'a ast::Block,
754 label: Option<ast::SpannedIdent>)
768 impl<'a> Rewrite for Loop<'a> {
769 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
770 let label_string = rewrite_label(self.label);
772 let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
773 let inner_offset = offset + self.keyword.len() + label_string.len();
775 let pat_expr_string = match self.cond {
777 try_opt!(rewrite_pat_expr(context,
785 None => String::new(),
788 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
789 let block_sep = match context.config.control_brace_style {
790 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
791 ControlBraceStyle::AlwaysSameLine => " ",
794 // This is used only for the empty block case: `{}`
795 let block_width = try_opt!(width.checked_sub(label_string.len() + self.keyword.len() +
796 extra_offset(&pat_expr_string, inner_offset) +
799 // FIXME: this drops any comment between "loop" and the block.
801 .rewrite(context, block_width, offset)
803 format!("{}{}{}{}{}",
813 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
815 Some(ident) => format!("{}: ", ident.node),
816 None => "".to_owned(),
820 fn extract_comment(span: Span,
821 context: &RewriteContext,
825 let comment_str = context.snippet(span);
826 if contains_comment(&comment_str) {
828 try_opt!(rewrite_comment(comment_str.trim(), false, width, offset, context.config));
829 Some(format!("\n{indent}{}\n{indent}",
831 indent = offset.to_string(context.config)))
837 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
838 // treated as an if-let-else expression.
839 fn rewrite_if_else(context: &RewriteContext,
842 if_block: &ast::Block,
843 else_block_opt: Option<&ast::Expr>,
845 pat: Option<&ast::Pat>,
848 allow_single_line: bool)
850 let (budget, indent) = if !allow_single_line {
851 // We are part of an if-elseif-else chain. Our constraints are tightened.
852 // 7 = "} else" .len()
853 (try_opt!(width.checked_sub(7)), offset + 7)
858 // 3 = "if ", 2 = " {"
859 let pat_penalty = match context.config.else_if_brace_style {
860 ElseIfBraceStyle::AlwaysNextLine => 3,
863 let pat_expr_string = try_opt!(rewrite_pat_expr(context,
868 try_opt!(budget.checked_sub(pat_penalty)),
871 // Try to format if-else on single line.
872 if expr_type == ExprType::SubExpression && allow_single_line &&
873 context.config.single_line_if_else_max_width > 0 {
874 let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
876 if trial.is_some() &&
877 trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width {
882 let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
884 let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
885 pat.map_or(cond.span.lo,
886 |_| context.codemap.span_before(span, "let")));
888 let between_if_cond_comment = extract_comment(between_if_cond, context, offset, width);
890 let after_cond_comment = extract_comment(mk_sp(cond.span.hi, if_block.span.lo),
895 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
896 let after_sep = match context.config.else_if_brace_style {
897 ElseIfBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
900 let mut result = format!("if{}{}{}{}",
901 between_if_cond_comment.as_ref().map_or(" ", |str| &**str),
903 after_cond_comment.as_ref().map_or(after_sep, |str| &**str),
906 if let Some(else_block) = else_block_opt {
907 let mut last_in_chain = false;
908 let rewrite = match else_block.node {
909 // If the else expression is another if-else expression, prevent it
910 // from being formatted on a single line.
911 // Note how we're passing the original width and offset, as the
912 // cost of "else" should not cascade.
913 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
914 rewrite_if_else(context,
918 next_else_block.as_ref().map(|e| &**e),
919 mk_sp(else_block.span.lo, span.hi),
925 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
926 rewrite_if_else(context,
930 next_else_block.as_ref().map(|e| &**e),
931 mk_sp(else_block.span.lo, span.hi),
938 last_in_chain = true;
939 else_block.rewrite(context, width, offset)
943 let between_if_else_block =
944 mk_sp(if_block.span.hi,
945 context.codemap.span_before(mk_sp(if_block.span.hi, else_block.span.lo), "else"));
946 let between_if_else_block_comment =
947 extract_comment(between_if_else_block, context, offset, width);
949 let after_else = mk_sp(context.codemap
950 .span_after(mk_sp(if_block.span.hi, else_block.span.lo),
953 let after_else_comment = extract_comment(after_else, context, offset, width);
955 let between_sep = match context.config.else_if_brace_style {
956 ElseIfBraceStyle::AlwaysNextLine |
957 ElseIfBraceStyle::ClosingNextLine => alt_block_sep.as_str(),
958 ElseIfBraceStyle::AlwaysSameLine => " ",
960 let after_sep = match context.config.else_if_brace_style {
961 ElseIfBraceStyle::AlwaysNextLine if last_in_chain => alt_block_sep.as_str(),
964 try_opt!(write!(&mut result,
966 between_if_else_block_comment.as_ref()
967 .map_or(between_sep, |str| &**str),
968 after_else_comment.as_ref().map_or(after_sep, |str| &**str))
970 result.push_str(&try_opt!(rewrite));
976 fn single_line_if_else(context: &RewriteContext,
978 if_node: &ast::Block,
979 else_block_opt: Option<&ast::Expr>,
982 let else_block = try_opt!(else_block_opt);
983 let fixed_cost = "if { } else { }".len();
985 if let ast::ExprKind::Block(ref else_node) = else_block.node {
986 if !is_simple_block(if_node, context.codemap) ||
987 !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
991 let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
992 let if_expr = &if_node.stmts[0];
993 let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
995 let new_width = try_opt!(new_width.checked_sub(if_str.len()));
996 let else_expr = &else_node.stmts[0];
997 let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
999 // FIXME: this check shouldn't be necessary. Rewrites should either fail
1000 // or wrap to a newline when the object does not fit the width.
1001 let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
1003 if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
1004 return Some(format!("if {} {{ {} }} else {{ {} }}",
1014 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1015 let snippet = codemap.span_to_snippet(block.span).unwrap();
1016 contains_comment(&snippet)
1019 // Checks that a block contains no statements, an expression and no comments.
1020 // FIXME: incorrectly returns false when comment is contained completely within
1022 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1023 block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1024 !block_contains_comment(block, codemap)
1027 /// Checks whether a block contains at most one statement or expression, and no comments.
1028 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1029 block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1032 /// Checks whether a block contains no statements, expressions, or comments.
1033 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1034 block.stmts.is_empty() && !block_contains_comment(block, codemap)
1037 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1039 ast::StmtKind::Expr(..) => true,
1044 fn is_unsafe_block(block: &ast::Block) -> bool {
1045 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1052 // inter-match-arm-comment-rules:
1053 // - all comments following a match arm before the start of the next arm
1054 // are about the second arm
1055 fn rewrite_match_arm_comment(context: &RewriteContext,
1059 arm_indent_str: &str)
1061 // The leading "," is not part of the arm-comment
1062 let missed_str = match missed_str.find_uncommented(",") {
1063 Some(n) => &missed_str[n + 1..],
1064 None => &missed_str[..],
1067 let mut result = String::new();
1068 // any text not preceeded by a newline is pushed unmodified to the block
1069 let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1070 result.push_str(&missed_str[..first_brk]);
1071 let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1073 let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
1074 if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1075 // Excessive vertical whitespace before comment should be preserved
1076 // TODO handle vertical whitespace better
1079 let missed_str = missed_str[first..].trim();
1080 if !missed_str.is_empty() {
1082 try_opt!(rewrite_comment(&missed_str, false, width, arm_indent, context.config));
1084 result.push_str(arm_indent_str);
1085 result.push_str(&comment);
1091 fn rewrite_match(context: &RewriteContext,
1098 if arms.is_empty() {
1103 let cond_budget = try_opt!(width.checked_sub(8));
1104 let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
1105 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
1106 let block_sep = match context.config.control_brace_style {
1107 ControlBraceStyle::AlwaysSameLine => " ",
1108 ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1110 let mut result = format!("match {}{}{{", cond_str, block_sep);
1112 let nested_context = context.nested_context();
1113 let arm_indent = nested_context.block_indent;
1114 let arm_indent_str = arm_indent.to_string(context.config);
1116 let open_brace_pos = context.codemap
1117 .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1119 for (i, arm) in arms.iter().enumerate() {
1120 // Make sure we get the stuff between arms.
1121 let missed_str = if i == 0 {
1122 context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1124 context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1126 let comment = try_opt!(rewrite_match_arm_comment(context,
1131 result.push_str(&comment);
1133 result.push_str(&arm_indent_str);
1135 let arm_str = arm.rewrite(&nested_context,
1136 context.config.max_width - arm_indent.width(),
1138 if let Some(ref arm_str) = arm_str {
1139 result.push_str(arm_str);
1141 // We couldn't format the arm, just reproduce the source.
1142 let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1143 result.push_str(&snippet);
1144 result.push_str(arm_comma(context.config, arm, &arm.body));
1147 // BytePos(1) = closing match brace.
1148 let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1149 let last_comment = context.snippet(last_span);
1150 let comment = try_opt!(rewrite_match_arm_comment(context,
1155 result.push_str(&comment);
1157 result.push_str(&context.block_indent.to_string(context.config));
1162 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1163 let &ast::Arm { ref attrs, ref pats, .. } = arm;
1164 if !attrs.is_empty() {
1165 return attrs[0].span.lo;
1171 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1175 fn arm_comma(config: &Config, arm: &ast::Arm, body: &ast::Expr) -> &'static str {
1176 if !config.match_wildcard_trailing_comma {
1177 if arm.pats.len() == 1 && arm.pats[0].node == ast::PatKind::Wild && arm.guard.is_none() {
1182 if config.match_block_trailing_comma {
1184 } else if let ast::ExprKind::Block(ref block) = body.node {
1185 if let ast::BlockCheckMode::Default = block.rules {
1196 impl Rewrite for ast::Arm {
1197 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1198 let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
1200 // FIXME this is all a bit grotty, would be nice to abstract out the
1201 // treatment of attributes.
1202 let attr_str = if !attrs.is_empty() {
1203 // We only use this visitor for the attributes, should we use it for
1205 let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1206 attr_visitor.block_indent = context.block_indent;
1207 attr_visitor.last_pos = attrs[0].span.lo;
1208 if attr_visitor.visit_attrs(attrs) {
1209 // Attributes included a skip instruction.
1212 attr_visitor.format_missing(pats[0].span.lo);
1213 attr_visitor.buffer.to_string()
1220 let pat_budget = try_opt!(width.checked_sub(5));
1221 let pat_strs = try_opt!(pats.iter()
1222 .map(|p| p.rewrite(context, pat_budget, offset))
1223 .collect::<Option<Vec<_>>>());
1225 let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1226 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1227 let fmt = ListFormatting {
1228 tactic: if all_simple {
1229 DefinitiveListTactic::Mixed
1231 DefinitiveListTactic::Vertical
1234 trailing_separator: SeparatorTactic::Never,
1237 ends_with_newline: false,
1238 config: context.config,
1240 let pats_str = try_opt!(write_list(items, &fmt));
1242 let budget = if pats_str.contains('\n') {
1243 context.config.max_width - offset.width()
1248 let guard_str = try_opt!(rewrite_guard(context,
1252 trimmed_last_line_width(&pats_str)));
1254 let pats_str = format!("{}{}", pats_str, guard_str);
1255 // Where the next text can start.
1256 let mut line_start = last_line_width(&pats_str);
1257 if !pats_str.contains('\n') {
1258 line_start += offset.width();
1261 let body = match body.node {
1262 ast::ExprKind::Block(ref block) if !is_unsafe_block(block) &&
1263 is_simple_block(block, context.codemap) &&
1264 context.config.wrap_match_arms => {
1265 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1274 let comma = arm_comma(&context.config, self, body);
1275 let alt_block_sep = String::from("\n") + &context.block_indent.to_string(context.config);
1277 // Let's try and get the arm body on the same line as the condition.
1279 if context.config.max_width > line_start + comma.len() + 4 {
1280 let budget = context.config.max_width - line_start - comma.len() - 4;
1281 let offset = Indent::new(offset.block_indent, line_start + 4 - offset.block_indent);
1282 let rewrite = nop_block_collapse(body.rewrite(context, budget, offset), budget);
1283 let is_block = if let ast::ExprKind::Block(..) = body.node {
1289 let block_sep = match context.config.control_brace_style {
1290 ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1294 Some(ref body_str) if !body_str.contains('\n') || !context.config.wrap_match_arms ||
1296 return Some(format!("{}{} =>{}{}{}",
1297 attr_str.trim_left(),
1307 // FIXME: we're doing a second rewrite of the expr; This may not be
1309 let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
1310 let indent = context.block_indent.block_indent(context.config);
1311 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1312 let next_line_body =
1313 try_opt!(nop_block_collapse(body.rewrite(inner_context, body_budget, indent),
1315 let indent_str = offset.block_indent(context.config).to_string(context.config);
1316 let (body_prefix, body_suffix) = if context.config.wrap_match_arms {
1317 if context.config.match_block_trailing_comma {
1326 let block_sep = match context.config.control_brace_style {
1327 ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1328 ControlBraceStyle::AlwaysSameLine => String::from(" ") + body_prefix + "\n",
1330 Some(format!("{}{} =>{}{}{}\n{}{}",
1331 attr_str.trim_left(),
1336 offset.to_string(context.config),
1341 // A pattern is simple if it is very short or it is short-ish and just a path.
1342 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1343 fn pat_is_simple(pat_str: &str) -> bool {
1344 pat_str.len() <= 16 ||
1345 (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1348 // The `if ...` guard on a match arm.
1349 fn rewrite_guard(context: &RewriteContext,
1350 guard: &Option<ptr::P<ast::Expr>>,
1353 // The amount of space used up on this line for the pattern in
1354 // the arm (excludes offset).
1355 pattern_width: usize)
1357 if let Some(ref guard) = *guard {
1358 // First try to fit the guard string on the same line as the pattern.
1359 // 4 = ` if `, 5 = ` => {`
1360 let overhead = pattern_width + 4 + 5;
1361 if overhead < width {
1362 let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
1363 if let Some(cond_str) = cond_str {
1364 return Some(format!(" if {}", cond_str));
1368 // Not enough space to put the guard after the pattern, try a newline.
1369 let overhead = offset.block_indent(context.config).width() + 4 + 5;
1370 if overhead < width {
1371 let cond_str = guard.rewrite(context,
1374 offset.block_indent(context.config) + 3);
1375 if let Some(cond_str) = cond_str {
1376 return Some(format!("\n{}if {}",
1377 offset.block_indent(context.config).to_string(context.config),
1388 fn rewrite_pat_expr(context: &RewriteContext,
1389 pat: Option<&ast::Pat>,
1392 // Connecting piece between pattern and expression,
1393 // *without* trailing space.
1398 let pat_offset = offset + matcher.len();
1399 let mut result = match pat {
1401 let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
1402 let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
1403 format!("{}{}{}", matcher, pat_string, connector)
1405 None => String::new(),
1408 // Consider only the last line of the pat string.
1409 let extra_offset = extra_offset(&result, offset);
1411 // The expression may (partionally) fit on the current line.
1412 if width > extra_offset + 1 {
1413 let spacer = if pat.is_some() { " " } else { "" };
1415 let expr_rewrite = expr.rewrite(context,
1416 try_opt!(width.checked_sub(extra_offset + spacer.len())),
1417 offset + extra_offset + spacer.len());
1419 if let Some(expr_string) = expr_rewrite {
1421 pat.and_then(|p| p.rewrite(context, context.config.max_width, Indent::empty()))
1422 .map(|s| pat_is_simple(&s));
1424 if pat.is_none() || pat_simple.unwrap_or(false) || !expr_string.contains('\n') {
1425 result.push_str(spacer);
1426 result.push_str(&expr_string);
1427 return Some(result);
1432 let nested = context.nested_context();
1434 // The expression won't fit on the current line, jump to next.
1436 result.push_str(&nested.block_indent.to_string(context.config));
1439 expr.rewrite(&nested,
1440 try_opt!(context.config.max_width.checked_sub(nested.block_indent.width())),
1441 nested.block_indent);
1442 result.push_str(&try_opt!(expr_rewrite));
1447 fn rewrite_string_lit(context: &RewriteContext,
1452 let string_lit = context.snippet(span);
1454 if !context.config.format_strings && !context.config.force_format_strings {
1455 return Some(string_lit);
1458 if !context.config.force_format_strings &&
1459 !string_requires_rewrite(context, span, &string_lit, width, offset) {
1460 return Some(string_lit);
1463 let fmt = StringFormat {
1471 config: context.config,
1474 // Remove the quote characters.
1475 let str_lit = &string_lit[1..string_lit.len() - 1];
1477 rewrite_string(str_lit, &fmt)
1480 fn string_requires_rewrite(context: &RewriteContext,
1486 if context.codemap.lookup_char_pos(span.lo).col.0 != offset.width() {
1490 for (i, line) in string.lines().enumerate() {
1492 if line.len() > width {
1496 if line.len() > width + offset.width() {
1505 pub fn rewrite_call<R>(context: &RewriteContext,
1507 args: &[ptr::P<ast::Expr>],
1514 let closure = |callee_max_width| {
1515 rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
1519 let max_width = try_opt!(width.checked_sub(2));
1520 binary_search(1, max_width, closure)
1523 fn rewrite_call_inner<R>(context: &RewriteContext,
1525 max_callee_width: usize,
1526 args: &[ptr::P<ast::Expr>],
1530 -> Result<String, Ordering>
1533 let callee = callee.borrow();
1534 // FIXME using byte lens instead of char lens (and probably all over the
1536 let callee_str = match callee.rewrite(context, max_callee_width, offset) {
1538 if !string.contains('\n') && string.len() > max_callee_width {
1539 panic!("{:?} {}", string, max_callee_width);
1544 None => return Err(Ordering::Greater),
1547 let span_lo = context.codemap.span_after(span, "(");
1548 let span = mk_sp(span_lo, span.hi);
1550 let extra_offset = extra_offset(&callee_str, offset);
1552 let remaining_width = match width.checked_sub(extra_offset + 2) {
1554 None => return Err(Ordering::Greater),
1556 let offset = offset + extra_offset + 1;
1557 let arg_count = args.len();
1558 let block_indent = if arg_count == 1 {
1559 context.block_indent
1563 let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1565 let items = itemize_list(context.codemap,
1568 |item| item.span.lo,
1569 |item| item.span.hi,
1570 |item| item.rewrite(inner_context, remaining_width, offset),
1573 let mut item_vec: Vec<_> = items.collect();
1575 // Try letting the last argument overflow to the next line with block
1576 // indentation. If its first line fits on one line with the other arguments,
1577 // we format the function arguments horizontally.
1578 let overflow_last = match args.last().map(|x| &x.node) {
1579 Some(&ast::ExprKind::Closure(..)) |
1580 Some(&ast::ExprKind::Block(..)) if arg_count > 1 => true,
1582 } && context.config.chains_overflow_last;
1584 let mut orig_last = None;
1585 let mut placeholder = None;
1587 // Replace the last item with its first line to see if it fits with
1590 let inner_context = &RewriteContext { block_indent: context.block_indent, ..*context };
1591 let rewrite = args.last().unwrap().rewrite(inner_context, remaining_width, offset);
1593 if let Some(rewrite) = rewrite {
1594 let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1595 placeholder = Some(rewrite);
1597 swap(&mut item_vec[arg_count - 1].item, &mut orig_last);
1598 item_vec[arg_count - 1].item = rewrite_first_line;
1602 let tactic = definitive_tactic(&item_vec,
1603 ListTactic::LimitedHorizontalVertical(context.config
1607 // Replace the stub with the full overflowing last argument if the rewrite
1608 // succeeded and its first line fits with the other arguments.
1609 match (overflow_last, tactic, placeholder) {
1610 (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1611 item_vec[arg_count - 1].item = placeholder;
1614 item_vec[arg_count - 1].item = orig_last;
1619 let fmt = ListFormatting {
1622 trailing_separator: SeparatorTactic::Never,
1625 ends_with_newline: false,
1626 config: context.config,
1629 let list_str = match write_list(&item_vec, &fmt) {
1631 None => return Err(Ordering::Less),
1634 Ok(if context.config.spaces_within_parens && list_str.len() > 0 {
1635 format!("{}( {} )", callee_str, list_str)
1637 format!("{}({})", callee_str, list_str)
1641 fn rewrite_paren(context: &RewriteContext,
1642 subexpr: &ast::Expr,
1646 debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1647 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1648 // paren on the same line as the subexpr.
1649 let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1650 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1652 subexpr_str.map(|s| if context.config.spaces_within_parens && s.len() > 0 {
1653 format!("( {} )", s)
1659 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1661 fields: &'a [ast::Field],
1662 base: Option<&'a ast::Expr>,
1667 debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1669 enum StructLitField<'a> {
1670 Regular(&'a ast::Field),
1671 Base(&'a ast::Expr),
1675 let path_budget = try_opt!(width.checked_sub(2));
1676 let path_str = try_opt!(rewrite_path(context, true, None, path, path_budget, offset));
1678 // Foo { a: Foo } - indent is +3, width is -5.
1679 let h_budget = width.checked_sub(path_str.len() + 5).unwrap_or(0);
1680 // The 1 taken from the v_budget is for the comma.
1681 let (indent, v_budget) = match context.config.struct_lit_style {
1682 StructLitStyle::Visual => (offset + path_str.len() + 3, h_budget),
1683 StructLitStyle::Block => {
1684 // If we are all on one line, then we'll ignore the indent, and we
1685 // have a smaller budget.
1686 let indent = context.block_indent.block_indent(context.config);
1687 let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1692 let field_iter = fields.into_iter()
1693 .map(StructLitField::Regular)
1694 .chain(base.into_iter().map(StructLitField::Base));
1696 let inner_context = &RewriteContext { block_indent: indent, ..*context };
1698 let items = itemize_list(context.codemap,
1701 |item| match *item {
1702 StructLitField::Regular(field) => field.span.lo,
1703 StructLitField::Base(expr) => {
1704 let last_field_hi = fields.last()
1705 .map_or(span.lo, |field| field.span.hi);
1707 context.snippet(mk_sp(last_field_hi, expr.span.lo));
1708 let pos = snippet.find_uncommented("..").unwrap();
1709 last_field_hi + BytePos(pos as u32)
1712 |item| match *item {
1713 StructLitField::Regular(field) => field.span.hi,
1714 StructLitField::Base(expr) => expr.span.hi,
1718 StructLitField::Regular(field) => {
1719 rewrite_field(inner_context,
1721 v_budget.checked_sub(1).unwrap_or(0),
1724 StructLitField::Base(expr) => {
1726 expr.rewrite(inner_context, try_opt!(v_budget.checked_sub(2)), indent + 2)
1727 .map(|s| format!("..{}", s))
1731 context.codemap.span_after(span, "{"),
1733 let item_vec = items.collect::<Vec<_>>();
1736 let mut prelim_tactic = match (context.config.struct_lit_style, fields.len()) {
1737 (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1738 _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1741 if prelim_tactic == ListTactic::HorizontalVertical && fields.len() > 1 {
1742 prelim_tactic = ListTactic::LimitedHorizontalVertical(context.config.struct_lit_width);
1745 definitive_tactic(&item_vec, prelim_tactic, h_budget)
1748 let budget = match tactic {
1749 DefinitiveListTactic::Horizontal => h_budget,
1753 let ends_with_newline = context.config.struct_lit_style != StructLitStyle::Visual &&
1754 tactic == DefinitiveListTactic::Vertical;
1756 let fmt = ListFormatting {
1759 trailing_separator: if base.is_some() {
1760 SeparatorTactic::Never
1762 context.config.struct_lit_trailing_comma
1766 ends_with_newline: ends_with_newline,
1767 config: context.config,
1769 let fields_str = try_opt!(write_list(&item_vec, &fmt));
1771 if fields_str.is_empty() {
1772 return Some(format!("{} {{}}", path_str));
1775 let format_on_newline = || {
1776 let inner_indent = context.block_indent
1777 .block_indent(context.config)
1778 .to_string(context.config);
1779 let outer_indent = context.block_indent.to_string(context.config);
1780 Some(format!("{} {{\n{}{}\n{}}}",
1787 match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1788 (StructLitStyle::Block, _) if fields_str.contains('\n') || fields_str.len() > h_budget => {
1791 (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1792 _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1795 // FIXME if context.config.struct_lit_style == Visual, but we run out
1796 // of space, we should fall back to BlockIndent.
1799 pub fn type_annotation_separator(config: &Config) -> &str {
1800 match (config.space_before_type_annotation, config.space_after_type_annotation_colon) {
1801 (true, true) => " : ",
1802 (true, false) => " :",
1803 (false, true) => ": ",
1804 (false, false) => ":",
1808 fn rewrite_field(context: &RewriteContext,
1813 let name = &field.ident.node.to_string();
1814 let separator = type_annotation_separator(context.config);
1815 let overhead = name.len() + separator.len();
1816 let expr = field.expr.rewrite(context,
1817 try_opt!(width.checked_sub(overhead)),
1821 Some(e) => Some(format!("{}{}{}", name, separator, e)),
1823 let expr_offset = offset.block_indent(context.config);
1824 let expr = field.expr.rewrite(context,
1825 try_opt!(context.config
1827 .checked_sub(expr_offset.width())),
1829 expr.map(|s| format!("{}:\n{}{}", name, expr_offset.to_string(&context.config), s))
1834 pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
1840 where I: ExactSizeIterator,
1841 <I as Iterator>::Item: Deref,
1842 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
1844 let indent = offset + 1;
1845 let aligned = RewriteContext { block_indent: indent, ..context.clone() };
1847 // In case of length 1, need a trailing comma
1848 if items.len() == 1 {
1850 let budget = try_opt!(width.checked_sub(3));
1853 .rewrite(&aligned, budget, indent)
1854 .map(|s| if context.config.spaces_within_parens {
1855 format!("( {}, )", s)
1861 let list_lo = context.codemap.span_after(span, "(");
1862 let budget = try_opt!(width.checked_sub(2));
1863 let items = itemize_list(context.codemap,
1866 |item| item.span().lo,
1867 |item| item.span().hi,
1868 |item| item.rewrite(&aligned, budget, indent),
1870 span.hi - BytePos(1));
1871 let list_str = try_opt!(format_item_list(items, budget, indent, context.config));
1873 if context.config.spaces_within_parens && list_str.len() > 0 {
1874 Some(format!("( {} )", list_str))
1876 Some(format!("({})", list_str))
1880 fn rewrite_binary_op(context: &RewriteContext,
1887 // FIXME: format comments between operands and operator
1889 let operator_str = context.snippet(op.span);
1891 // Get "full width" rhs and see if it fits on the current line. This
1892 // usually works fairly well since it tends to place operands of
1893 // operations with high precendence close together.
1894 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1896 // Second condition is needed in case of line break not caused by a
1897 // shortage of space, but by end-of-line comments, for example.
1898 // Note that this is non-conservative, but its just to see if it's even
1899 // worth trying to put everything on one line.
1900 if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1901 // 1 = space between lhs expr and operator
1902 if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1904 result.push_str(&operator_str);
1907 let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1909 if rhs_result.len() <= remaining_width {
1910 result.push_str(&rhs_result);
1911 return Some(result);
1914 if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1915 if rhs_result.len() <= remaining_width {
1916 result.push_str(&rhs_result);
1917 return Some(result);
1923 // We have to use multiple lines.
1925 // Re-evaluate the lhs because we have more space now:
1926 let budget = try_opt!(context.config
1928 .checked_sub(offset.width() + 1 + operator_str.len()));
1929 Some(format!("{} {}\n{}{}",
1930 try_opt!(lhs.rewrite(context, budget, offset)),
1932 offset.to_string(context.config),
1936 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
1942 rewrite.rewrite(context,
1943 try_opt!(width.checked_sub(prefix.len())),
1944 offset + prefix.len())
1945 .map(|r| format!("{}{}", prefix, r))
1948 // FIXME: this is probably not correct for multi-line Rewrites. we should
1949 // subtract suffix.len() from the last line budget, not the first!
1950 pub fn rewrite_unary_suffix<R: Rewrite>(context: &RewriteContext,
1956 rewrite.rewrite(context, try_opt!(width.checked_sub(suffix.len())), offset)
1963 fn rewrite_unary_op(context: &RewriteContext,
1969 // For some reason, an UnOp is not spanned like BinOp!
1970 let operator_str = match *op {
1971 ast::UnOp::Deref => "*",
1972 ast::UnOp::Not => "!",
1973 ast::UnOp::Neg => "-",
1975 rewrite_unary_prefix(context, operator_str, expr, width, offset)
1978 fn rewrite_assignment(context: &RewriteContext,
1981 op: Option<&ast::BinOp>,
1985 let operator_str = match op {
1986 Some(op) => context.snippet(op.span),
1987 None => "=".to_owned(),
1990 // 1 = space between lhs and operator.
1991 let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1992 let lhs_str = format!("{} {}",
1993 try_opt!(lhs.rewrite(context, max_width, offset)),
1996 rewrite_assign_rhs(context, lhs_str, rhs, width, offset)
1999 // The left hand side must contain everything up to, and including, the
2000 // assignment operator.
2001 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
2007 let mut result = lhs.into();
2008 let last_line_width = last_line_width(&result) -
2009 if result.contains('\n') {
2014 // 1 = space between operator and rhs.
2015 let max_width = try_opt!(width.checked_sub(last_line_width + 1));
2016 let rhs = ex.rewrite(context, max_width, offset + last_line_width + 1);
2018 fn count_line_breaks(src: &str) -> usize {
2019 src.chars().filter(|&x| x == '\n').count()
2023 Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2025 result.push_str(new_str);
2028 // Expression did not fit on the same line as the identifier or is
2029 // at least three lines big. Try splitting the line and see
2030 // if that works better.
2031 let new_offset = offset.block_indent(context.config);
2032 let max_width = try_opt!((width + offset.width()).checked_sub(new_offset.width()));
2033 let inner_context = context.nested_context();
2034 let new_rhs = ex.rewrite(&inner_context, max_width, new_offset);
2037 match (rhs, new_rhs) {
2038 (Some(ref orig_rhs), Some(ref replacement_rhs))
2039 if count_line_breaks(orig_rhs) >
2040 count_line_breaks(replacement_rhs) + 1 => {
2041 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
2042 result.push_str(replacement_rhs);
2044 (None, Some(ref final_rhs)) => {
2045 result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
2046 result.push_str(final_rhs);
2048 (None, None) => return None,
2049 (Some(ref orig_rhs), _) => {
2051 result.push_str(orig_rhs);
2060 fn rewrite_expr_addrof(context: &RewriteContext,
2061 mutability: ast::Mutability,
2066 let operator_str = match mutability {
2067 ast::Mutability::Immutable => "&",
2068 ast::Mutability::Mutable => "&mut ",
2070 rewrite_unary_prefix(context, operator_str, expr, width, offset)