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 /// Formatting of chained expressions, i.e. expressions which are chained by
12 /// dots: struct and enum field access, method calls, and try shorthand (?).
14 /// Instead of walking these subexpressions one-by-one, as is our usual strategy
15 /// for expression formatting, we collect maximal sequences of these expressions
16 /// and handle them simultaneously.
18 /// Whenever possible, the entire chain is put on a single line. If that fails,
19 /// we put each subexpression on a separate, much like the (default) function
20 /// argument function argument strategy.
22 /// Depends on config options: `chain_indent` is the indent to use for
23 /// blocks in the parent/root/base of the chain (and the rest of the chain's
25 /// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 /// following values of `chain_indent`:
58 /// If the first item in the chain is a block expression, we align the dots with
80 use rewrite::{Rewrite, RewriteContext};
81 use utils::{wrap_str, first_line_width, last_line_width};
82 use expr::rewrite_call;
83 use config::BlockIndentStyle;
84 use macros::convert_try_mac;
87 use syntax::{ast, ptr};
88 use syntax::codemap::{mk_sp, Span};
90 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
91 debug!("rewrite_chain {:?}", shape);
92 let total_span = expr.span;
93 let (parent, subexpr_list) = make_subexpr_list(expr, context);
95 // Bail out if the chain is just try sugar, i.e., an expression followed by
96 // any number of `?`s.
97 if chain_only_try(&subexpr_list) {
98 return rewrite_try(&parent, subexpr_list.len(), context, shape);
101 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
102 let mut parent_shape = shape;
103 if is_block_expr(&parent, "\n") {
104 parent_shape = chain_indent(context, shape);
106 let parent_rewrite = try_opt!(parent.rewrite(context, parent_shape));
108 // Decide how to layout the rest of the chain. `extend` is true if we can
109 // put the first non-parent item on the same line as the parent.
110 let (nested_shape, extend) = if !parent_rewrite.contains('\n') && is_continuable(&parent) {
111 let nested_shape = if let ast::ExprKind::Try(..) = subexpr_list.last().unwrap().node {
112 parent_shape.block_indent(context.config.tab_spaces)
114 chain_indent(context, shape.add_offset(parent_rewrite.len()))
117 } else if is_block_expr(&parent, &parent_rewrite) {
118 // The parent is a block, so align the rest of the chain with the closing
120 (parent_shape, false)
121 } else if parent_rewrite.contains('\n') {
122 (chain_indent(context,
123 parent_shape.block_indent(context.config.tab_spaces)),
126 (chain_indent_newline(context, shape.add_offset(parent_rewrite.len())), false)
129 let max_width = try_opt!((shape.width + shape.indent.width() + shape.offset)
130 .checked_sub(nested_shape.indent.width() +
131 nested_shape.offset));
133 let other_child_shape = Shape { width: max_width, ..nested_shape };
134 let first_child_shape = if extend {
135 let mut shape = try_opt!(parent_shape.shrink_left(last_line_width(&parent_rewrite)));
136 match context.config.chain_indent {
137 BlockIndentStyle::Visual => other_child_shape,
138 BlockIndentStyle::Inherit => shape,
139 BlockIndentStyle::Tabbed => {
140 shape.offset = shape.offset.checked_sub(context.config.tab_spaces).unwrap_or(0);
141 shape.indent.block_indent += context.config.tab_spaces;
148 debug!("child_shapes {:?} {:?}",
152 let child_shape_iter =
153 Some(first_child_shape).into_iter().chain(::std::iter::repeat(other_child_shape)
154 .take(subexpr_list.len() - 1));
155 let iter = subexpr_list.iter().rev().zip(child_shape_iter);
157 try_opt!(iter.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
158 .collect::<Option<Vec<_>>>());
160 // Total of all items excluding the last.
161 let almost_total = rewrites[..rewrites.len() - 1]
163 .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
165 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
166 // Look at the source code. Unless all chain elements start on the same
167 // line, we won't consider putting them on a single line either.
168 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
169 let first_span = context.snippet(subexpr_list[1].span);
170 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
172 first_span.chars().chain(last_iter).any(|c| c == '\n')
177 let mut fits_single_line = !veto_single_line && almost_total <= shape.width;
178 if fits_single_line {
179 let len = rewrites.len();
180 let (init, last) = rewrites.split_at_mut(len - 1);
181 fits_single_line = init.iter().all(|s| !s.contains('\n'));
183 if fits_single_line {
184 fits_single_line = match expr.node {
185 ref e @ ast::ExprKind::MethodCall(..) => {
186 rewrite_method_call_with_overflow(e,
193 _ => !last[0].contains('\n'),
198 let connector = if fits_single_line && !parent_rewrite.contains('\n') {
199 // Yay, we can put everything on one line.
203 format!("\n{}", nested_shape.indent.to_string(context.config))
206 let first_connector = if extend || subexpr_list.is_empty() {
208 } else if let ast::ExprKind::Try(_) = subexpr_list[0].node {
214 wrap_str(format!("{}{}{}",
217 join_rewrites(&rewrites, &subexpr_list, &connector)),
218 context.config.max_width,
222 // True if the chain is only `?`s.
223 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
224 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
231 pub fn rewrite_try(expr: &ast::Expr,
233 context: &RewriteContext,
236 let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
239 iter::repeat("?").take(try_count).collect::<String>()))
242 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
243 let mut rewrite_iter = rewrites.iter();
244 let mut result = rewrite_iter.next().unwrap().clone();
245 let mut subexpr_iter = subexps.iter().rev();
248 for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
250 ast::ExprKind::Try(_) => (),
251 _ => result.push_str(connector),
253 result.push_str(&rewrite[..]);
259 // States whether an expression's last line exclusively consists of closing
260 // parens, braces, and brackets in its idiomatic formatting.
261 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
263 ast::ExprKind::Struct(..) |
264 ast::ExprKind::While(..) |
265 ast::ExprKind::WhileLet(..) |
266 ast::ExprKind::If(..) |
267 ast::ExprKind::IfLet(..) |
268 ast::ExprKind::Block(..) |
269 ast::ExprKind::Loop(..) |
270 ast::ExprKind::ForLoop(..) |
271 ast::ExprKind::Match(..) => repr.contains('\n'),
272 ast::ExprKind::Paren(ref expr) |
273 ast::ExprKind::Binary(_, _, ref expr) |
274 ast::ExprKind::Index(_, ref expr) |
275 ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
280 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
281 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
282 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
283 let mut subexpr_list = vec![expr.clone()];
285 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
286 subexpr_list.push(subexpr.clone());
289 let parent = subexpr_list.pop().unwrap();
290 (parent, subexpr_list)
293 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
294 match context.config.chain_indent {
295 BlockIndentStyle::Visual => shape.visual_indent(0),
296 BlockIndentStyle::Inherit => shape.block_indent(0),
297 BlockIndentStyle::Tabbed => shape.block_indent(context.config.tab_spaces),
301 // Ignores visual indenting because this function should be called where it is
302 // not possible to use visual indentation because we are starting on a newline.
303 fn chain_indent_newline(context: &RewriteContext, shape: Shape) -> Shape {
304 match context.config.chain_indent {
305 BlockIndentStyle::Inherit => shape.block_indent(0),
306 BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
307 shape.block_indent(context.config.tab_spaces)
312 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
316 context: &RewriteContext,
319 if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
320 let shape = match shape.shrink_left(almost_total) {
322 None => return false,
324 let mut last_rewrite = rewrite_method_call(method_name.node,
331 if let Some(ref mut s) = last_rewrite {
332 ::std::mem::swap(s, last);
342 // Returns the expression's subexpression, if it exists. When the subexpr
343 // is a try! macro, we'll convert it to shorthand when the option is set.
344 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
346 ast::ExprKind::MethodCall(_, _, ref expressions) => {
347 Some(convert_try(&expressions[0], context))
349 ast::ExprKind::TupField(ref subexpr, _) |
350 ast::ExprKind::Field(ref subexpr, _) |
351 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
356 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
358 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand => {
359 if let Some(subexpr) = convert_try_mac(mac, context) {
369 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
371 fn rewrite_chain_subexpr(expr: &ast::Expr,
373 context: &RewriteContext,
377 ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
378 rewrite_method_call(method_name.node, types, expressions, span, context, shape)
380 ast::ExprKind::Field(_, ref field) => {
381 let s = format!(".{}", field.node);
382 if s.len() <= shape.width {
388 ast::ExprKind::TupField(_, ref field) => {
389 let s = format!(".{}", field.node);
390 if s.len() <= shape.width {
396 ast::ExprKind::Try(_) => {
397 if shape.width >= 1 {
407 // Determines if we can continue formatting a given expression on the same line.
408 fn is_continuable(expr: &ast::Expr) -> bool {
410 ast::ExprKind::Path(..) => true,
415 fn rewrite_method_call(method_name: ast::Ident,
416 types: &[ptr::P<ast::Ty>],
417 args: &[ptr::P<ast::Expr>],
419 context: &RewriteContext,
422 let (lo, type_str) = if types.is_empty() {
423 (args[0].span.hi, String::new())
425 let type_list: Vec<_> = try_opt!(types.iter()
426 .map(|ty| ty.rewrite(context, shape))
429 let type_str = if context.config.spaces_within_angle_brackets && type_list.len() > 0 {
430 format!("::< {} >", type_list.join(", "))
432 format!("::<{}>", type_list.join(", "))
435 (types.last().unwrap().span.hi, type_str)
438 let callee_str = format!(".{}{}", method_name, type_str);
439 let span = mk_sp(lo, span.hi);
441 rewrite_call(context, &callee_str, &args[1..], span, shape)