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`:
50 //! If the first item in the chain is a block expression, we align the dots with
68 use config::IndentStyle;
69 use expr::rewrite_call;
70 use macros::convert_try_mac;
71 use rewrite::{Rewrite, RewriteContext};
75 first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
82 use syntax::codemap::Span;
83 use syntax::{ast, ptr};
85 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
86 debug!("rewrite_chain {:?}", shape);
87 let total_span = expr.span;
88 let (parent, subexpr_list) = make_subexpr_list(expr, context);
90 // Bail out if the chain is just try sugar, i.e., an expression followed by
91 // any number of `?`s.
92 if chain_only_try(&subexpr_list) {
93 return rewrite_try(&parent, subexpr_list.len(), context, shape);
95 let suffix_try_num = subexpr_list.iter().take_while(|e| is_try(e)).count();
96 let prefix_try_num = subexpr_list.iter().rev().take_while(|e| is_try(e)).count();
98 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
99 let parent_shape = if is_block_expr(context, &parent, "\n") {
100 match context.config.indent_style() {
101 IndentStyle::Block => shape,
102 IndentStyle::Visual => shape.visual_indent(0),
107 let parent_rewrite = parent
108 .rewrite(context, parent_shape)
109 .map(|parent_rw| parent_rw + &"?".repeat(prefix_try_num))?;
110 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
111 let is_small_parent = shape.offset + parent_rewrite.len() <= context.config.tab_spaces();
112 let parent_is_block = is_block_expr(context, &parent, &parent_rewrite);
114 // Decide how to layout the rest of the chain. `extend` is true if we can
115 // put the first non-parent item on the same line as the parent.
116 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
117 match context.config.indent_style() {
118 IndentStyle::Block => {
119 // TODO this is naive since if the first child is on the same line
120 // as the parent, then we should look at that, instead of the parent.
121 // Can we make the parent the first two things then?
122 let shape = if parent_is_block {
125 chain_indent(context, shape.add_offset(parent_rewrite.len()))
127 (shape, is_small_parent)
129 // TODO is this right?
130 IndentStyle::Visual => (chain_indent(context, shape.add_offset(parent_rewrite.len())), true),
132 } else if parent_is_block {
133 match context.config.indent_style() {
134 // Try to put the first child on the same line with parent's last line
135 IndentStyle::Block => (parent_shape, true),
136 // The parent is a block, so align the rest of the chain with the closing
138 IndentStyle::Visual => (parent_shape, false),
142 chain_indent(context, shape.add_offset(parent_rewrite.len())),
147 let other_child_shape = nested_shape.with_max_width(context.config);
149 let first_child_shape = if extend {
150 match context.config.indent_style() {
151 IndentStyle::Block => {
152 let offset = trimmed_last_line_width(&parent_rewrite) + prefix_try_num;
154 parent_shape.offset_left(offset)?
157 .block_indent(context.config.tab_spaces())
158 .offset_left(offset)?
161 IndentStyle::Visual => {
162 let overhead = last_line_width(&parent_rewrite);
163 parent_shape.offset_left(overhead)?
170 "child_shapes {:?} {:?}",
171 first_child_shape, other_child_shape
174 let subexpr_num = subexpr_list.len();
175 let last_subexpr = &subexpr_list[suffix_try_num];
176 let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
178 let mut rewrites: Vec<String> = Vec::with_capacity(subexpr_list.len());
179 let mut is_block_like = Vec::with_capacity(subexpr_list.len());
180 is_block_like.push(true);
181 for (i, expr) in subexpr_list.iter().skip(1).rev().enumerate() {
182 // TODO should only use first_child_shape if expr is block like
183 let shape = if *is_block_like.last().unwrap() && !(extend && i == 0) {
184 // TODO change the name of the shapes
189 let rewrite = rewrite_chain_subexpr(expr, total_span, context, shape)?;
190 is_block_like.push(is_block_expr(context, expr, &rewrite));
191 rewrites.push(rewrite);
194 // Total of all items excluding the last.
195 let extend_last_subexpr = if is_small_parent {
196 rewrites.len() == 1 && last_line_extendable(&rewrites[0])
198 rewrites.is_empty() && last_line_extendable(&parent_rewrite)
200 let almost_total = if extend_last_subexpr {
201 last_line_width(&parent_rewrite)
203 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
205 let one_line_budget = if rewrites.is_empty() {
208 min(shape.width, context.config.width_heuristics().chain_width)
210 let all_in_one_line = !parent_rewrite_contains_newline
211 && rewrites.iter().all(|s| !s.contains('\n'))
212 && almost_total < one_line_budget;
213 let last_shape = if is_block_like[rewrites.len()] {
217 }.sub_width(shape.rhs_overhead(context.config) + suffix_try_num)?;
219 // Rewrite the last child. The last child of a chain requires special treatment. We need to
220 // know whether 'overflowing' the last child make a better formatting:
222 // A chain with overflowing the last child:
224 // parent.child1.child2.last_child(
231 // A chain without overflowing the last child (in vertical layout):
236 // .last_child(a, b, c)
239 // In particular, overflowing is effective when the last child is a method with a multi-lined
240 // block-like argument (e.g. closure):
242 // parent.child1.child2.last_child(|a, b, c| {
243 // let x = foo(a, b, c);
244 // let y = bar(a, b, c);
252 // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
253 // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
254 let rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, last_shape);
255 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
256 // First we try to 'overflow' the last child and see if it looks better than using
258 parent_shape.offset_left(almost_total).map(|shape| {
259 if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
260 // We allow overflowing here only if both of the following conditions match:
261 // 1. The entire chain fits in a single line except the last child.
262 // 2. `last_child_str.lines().count() >= 5`.
263 let line_count = rw.lines().count();
264 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
265 if fits_single_line && line_count >= 5 {
268 // We could not know whether overflowing is better than using vertical layout,
269 // just by looking at the overflowed rewrite. Now we rewrite the last child
270 // on its own line, and compare two rewrites to choose which is better.
271 match rewrite_last() {
272 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
273 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
274 (Some(rw), fits_single_line)
276 new_rw @ Some(..) => (new_rw, false),
277 _ => (Some(rw), fits_single_line),
281 (rewrite_last(), false)
285 (rewrite_last(), false)
287 rewrites.push(last_subexpr_str?);
288 // We should never look at this, since we only look at the block-ness of the
289 // previous item in the chain.
290 is_block_like.push(false);
292 let connector = if fits_single_line && !parent_rewrite_contains_newline {
293 // Yay, we can put everything on one line.
297 if *context.force_one_line_chain.borrow() {
300 nested_shape.indent.to_string_with_newline(context.config)
303 let first_connector = if is_small_parent
305 || last_line_extendable(&parent_rewrite)
306 || context.config.indent_style() == IndentStyle::Visual
313 let result = if is_small_parent && rewrites.len() > 1 {
314 let second_connector = if fits_single_line
315 || rewrites[1] == "?"
316 || last_line_extendable(&rewrites[0])
317 || context.config.indent_style() == IndentStyle::Visual
329 join_rewrites(&rewrites[1..], &is_block_like[2..], &connector),
336 join_rewrites(&rewrites, &is_block_like[1..], &connector),
339 let result = format!("{}{}", result, "?".repeat(suffix_try_num));
340 if context.config.indent_style() == IndentStyle::Visual {
341 wrap_str(result, context.config.max_width(), shape)
347 // True if the chain is only `?`s.
348 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
349 exprs.iter().all(|e| {
350 if let ast::ExprKind::Try(_) = e.node {
361 context: &RewriteContext,
363 ) -> Option<String> {
364 let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
365 Some(format!("{}{}", sub_expr, "?".repeat(try_count)))
368 fn join_rewrites(rewrites: &[String], is_block_like: &[bool], connector: &str) -> String {
369 let mut rewrite_iter = rewrites.iter();
370 let mut result = rewrite_iter.next().unwrap().clone();
372 for (rewrite, prev_is_block_like) in rewrite_iter.zip(is_block_like.iter()) {
373 if rewrite != "?" && !prev_is_block_like {
374 result.push_str(connector);
376 result.push_str(&rewrite);
382 // States whether an expression's last line exclusively consists of closing
383 // parens, braces, and brackets in its idiomatic formatting.
384 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
386 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
387 context.use_block_indent() && repr.contains('\n')
389 ast::ExprKind::Struct(..)
390 | ast::ExprKind::While(..)
391 | ast::ExprKind::WhileLet(..)
392 | ast::ExprKind::If(..)
393 | ast::ExprKind::IfLet(..)
394 | ast::ExprKind::Block(..)
395 | ast::ExprKind::Loop(..)
396 | ast::ExprKind::ForLoop(..)
397 | ast::ExprKind::Match(..) => repr.contains('\n'),
398 ast::ExprKind::Paren(ref expr)
399 | ast::ExprKind::Binary(_, _, ref expr)
400 | ast::ExprKind::Index(_, ref expr)
401 | ast::ExprKind::Unary(_, ref expr)
402 | ast::ExprKind::Closure(_, _, _, _, ref expr, _) => is_block_expr(context, expr, repr),
403 ast::ExprKind::MethodCall(_, ref exprs) => {
404 is_block_expr(context, exprs.last().unwrap(), repr)
410 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
411 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
412 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
413 let mut subexpr_list = vec![expr.clone()];
415 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
416 subexpr_list.push(subexpr.clone());
419 let parent = subexpr_list.pop().unwrap();
420 (parent, subexpr_list)
423 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
424 match context.config.indent_style() {
425 IndentStyle::Visual => shape.visual_indent(0),
426 IndentStyle::Block => shape
427 .block_indent(context.config.tab_spaces())
428 .with_max_width(context.config),
432 // Returns the expression's subexpression, if it exists. When the subexpr
433 // is a try! macro, we'll convert it to shorthand when the option is set.
434 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
436 ast::ExprKind::MethodCall(_, ref expressions) => {
437 Some(convert_try(&expressions[0], context))
439 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
440 Some(convert_try(subexpr, context))
446 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
448 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
449 if let Some(subexpr) = convert_try_mac(mac, context) {
459 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
461 fn rewrite_chain_subexpr(
464 context: &RewriteContext,
466 ) -> Option<String> {
467 let rewrite_element = |expr_str: String| {
468 if expr_str.len() <= shape.width {
476 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
477 let types = match segment.args {
478 Some(ref params) => match **params {
479 ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
484 rewrite_method_call(segment.ident, types, expressions, span, context, shape)
486 ast::ExprKind::Field(ref nested, ref field) => {
487 let space = if is_tup_field_access(expr) && is_tup_field_access(nested) {
492 rewrite_element(format!("{}.{}", space, field.name))
494 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
499 fn is_tup_field_access(expr: &ast::Expr) -> bool {
501 ast::ExprKind::Field(_, ref field) => {
502 field.name.to_string().chars().all(|c| c.is_digit(10))
508 // Determines if we can continue formatting a given expression on the same line.
509 fn is_continuable(expr: &ast::Expr) -> bool {
511 ast::ExprKind::Path(..) => true,
516 fn is_try(expr: &ast::Expr) -> bool {
518 ast::ExprKind::Try(..) => true,
523 fn rewrite_method_call(
524 method_name: ast::Ident,
525 types: &[ast::GenericArg],
526 args: &[ptr::P<ast::Expr>],
528 context: &RewriteContext,
530 ) -> Option<String> {
531 let (lo, type_str) = if types.is_empty() {
532 (args[0].span.hi(), String::new())
534 let type_list = types
536 .map(|ty| ty.rewrite(context, shape))
537 .collect::<Option<Vec<_>>>()?;
539 let type_str = format!("::<{}>", type_list.join(", "));
541 (types.last().unwrap().span().hi(), type_str)
544 let callee_str = format!(".{}{}", method_name, type_str);
545 let span = mk_sp(lo, span.hi());
547 rewrite_call(context, &callee_str, &args[1..], span, shape)