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`:
47 /// If the first item in the chain is a block expression, we align the dots with
63 use config::IndentStyle;
64 use expr::rewrite_call;
65 use macros::convert_try_mac;
66 use rewrite::{Rewrite, RewriteContext};
67 use utils::{first_line_width, last_line_extendable, last_line_width, mk_sp,
68 trimmed_last_line_width, wrap_str};
72 use syntax::{ast, ptr};
73 use syntax::codemap::Span;
75 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
76 debug!("rewrite_chain {:?}", shape);
77 let total_span = expr.span;
78 let (parent, subexpr_list) = make_subexpr_list(expr, context);
80 // Bail out if the chain is just try sugar, i.e., an expression followed by
81 // any number of `?`s.
82 if chain_only_try(&subexpr_list) {
83 return rewrite_try(&parent, subexpr_list.len(), context, shape);
85 let suffix_try_num = subexpr_list.iter().take_while(|e| is_try(e)).count();
86 let prefix_try_num = subexpr_list.iter().rev().take_while(|e| is_try(e)).count();
88 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
89 let parent_shape = if is_block_expr(context, &parent, "\n") {
90 match context.config.chain_indent() {
91 IndentStyle::Visual => shape.visual_indent(0),
92 IndentStyle::Block => shape,
97 let parent_rewrite = parent
98 .rewrite(context, parent_shape)
99 .map(|parent_rw| parent_rw + &repeat_try(prefix_try_num))?;
100 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
101 let is_small_parent = parent_rewrite.len() <= context.config.tab_spaces();
103 // Decide how to layout the rest of the chain. `extend` is true if we can
104 // put the first non-parent item on the same line as the parent.
105 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
107 chain_indent(context, shape.add_offset(parent_rewrite.len())),
108 context.config.chain_indent() == IndentStyle::Visual || is_small_parent,
110 } else if is_block_expr(context, &parent, &parent_rewrite) {
111 match context.config.chain_indent() {
112 // Try to put the first child on the same line with parent's last line
113 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
114 // The parent is a block, so align the rest of the chain with the closing
116 IndentStyle::Visual => (parent_shape, false),
120 chain_indent(context, shape.add_offset(parent_rewrite.len())),
125 let other_child_shape = nested_shape.with_max_width(context.config);
127 let first_child_shape = if extend {
128 let overhead = last_line_width(&parent_rewrite);
129 let offset = trimmed_last_line_width(&parent_rewrite);
130 match context.config.chain_indent() {
131 IndentStyle::Visual => parent_shape.offset_left(overhead)?,
132 IndentStyle::Block => parent_shape.block().offset_left(offset)?,
138 "child_shapes {:?} {:?}",
143 let child_shape_iter = Some(first_child_shape)
145 .chain(iter::repeat(other_child_shape));
146 let subexpr_num = subexpr_list.len();
147 let last_subexpr = &subexpr_list[suffix_try_num];
148 let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
149 let iter = subexpr_list.iter().skip(1).rev().zip(child_shape_iter);
150 let mut rewrites = iter.map(|(e, shape)| {
151 rewrite_chain_subexpr(e, total_span, context, shape)
152 }).collect::<Option<Vec<_>>>()?;
154 // Total of all items excluding the last.
155 let extend_last_subexr = last_line_extendable(&parent_rewrite) && rewrites.is_empty();
156 let almost_total = if extend_last_subexr {
157 last_line_width(&parent_rewrite)
159 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
161 let one_line_budget = if rewrites.is_empty() && !context.config.chain_split_single_child() {
164 min(shape.width, context.config.chain_one_line_max())
166 let all_in_one_line = !parent_rewrite_contains_newline
167 && rewrites.iter().all(|s| !s.contains('\n'))
168 && almost_total < one_line_budget;
169 let last_shape = match context.config.chain_indent() {
170 IndentStyle::Visual => other_child_shape.sub_width(shape.rhs_overhead(context.config))?,
171 IndentStyle::Block => other_child_shape,
173 let last_shape = last_shape.sub_width(suffix_try_num)?;
175 // Rewrite the last child. The last child of a chain requires special treatment. We need to
176 // know whether 'overflowing' the last child make a better formatting:
178 // A chain with overflowing the last child:
180 // parent.child1.child2.last_child(
187 // A chain without overflowing the last child (in vertical layout):
192 // .last_child(a, b, c)
195 // In particular, overflowing is effective when the last child is a method with a multi-lined
196 // block-like argument (e.g. closure):
198 // parent.child1.chlid2.last_child(|a, b, c| {
199 // let x = foo(a, b, c);
200 // let y = bar(a, b, c);
208 // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
209 // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
210 let rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, last_shape);
211 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexr {
212 // First we try to 'overflow' the last child and see if it looks better than using
214 parent_shape.offset_left(almost_total).map(|shape| {
215 if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
216 // We allow overflowing here only if both of the following conditions match:
217 // 1. The entire chain fits in a single line expect the last child.
218 // 2. `last_chlid_str.lines().count() >= 5`.
219 let line_count = rw.lines().count();
220 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
221 if fits_single_line && line_count >= 5 {
224 // We could not know whether overflowing is better than using vertical layout,
225 // just by looking at the overflowed rewrite. Now we rewrite the last child
226 // on its own line, and compare two rewrites to choose which is better.
227 match rewrite_last() {
228 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
229 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
230 (Some(rw), fits_single_line)
232 new_rw @ Some(..) => (new_rw, false),
233 _ => (Some(rw), fits_single_line),
237 (rewrite_last(), false)
241 (rewrite_last(), false)
243 rewrites.push(last_subexpr_str?);
245 let connector = if fits_single_line && !parent_rewrite_contains_newline {
246 // Yay, we can put everything on one line.
250 if context.force_one_line_chain {
253 format!("\n{}", nested_shape.indent.to_string(context.config))
256 let first_connector = if is_small_parent || fits_single_line
257 || last_line_extendable(&parent_rewrite)
258 || context.config.chain_indent() == IndentStyle::Visual
265 let result = if is_small_parent && rewrites.len() > 1 {
266 let second_connector = if fits_single_line || rewrites[1] == "?"
267 || last_line_extendable(&rewrites[0])
268 || context.config.chain_indent() == IndentStyle::Visual
280 join_rewrites(&rewrites[1..], &connector)
287 join_rewrites(&rewrites, &connector)
290 let result = format!("{}{}", result, repeat_try(suffix_try_num));
291 if context.config.chain_indent() == IndentStyle::Visual {
292 wrap_str(result, context.config.max_width(), shape)
298 // True if the chain is only `?`s.
299 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
300 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
307 // Try to rewrite and replace the last non-try child. Return `true` if
308 // replacing succeeds.
309 fn repeat_try(try_count: usize) -> String {
310 iter::repeat("?").take(try_count).collect::<String>()
316 context: &RewriteContext,
318 ) -> Option<String> {
319 let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
320 Some(format!("{}{}", sub_expr, repeat_try(try_count)))
323 fn join_rewrites(rewrites: &[String], connector: &str) -> String {
324 let mut rewrite_iter = rewrites.iter();
325 let mut result = rewrite_iter.next().unwrap().clone();
327 for rewrite in rewrite_iter {
329 result.push_str(connector);
331 result.push_str(&rewrite[..]);
337 // States whether an expression's last line exclusively consists of closing
338 // parens, braces, and brackets in its idiomatic formatting.
339 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
341 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
342 context.use_block_indent() && repr.contains('\n')
344 ast::ExprKind::Struct(..) |
345 ast::ExprKind::While(..) |
346 ast::ExprKind::WhileLet(..) |
347 ast::ExprKind::If(..) |
348 ast::ExprKind::IfLet(..) |
349 ast::ExprKind::Block(..) |
350 ast::ExprKind::Loop(..) |
351 ast::ExprKind::ForLoop(..) |
352 ast::ExprKind::Match(..) => repr.contains('\n'),
353 ast::ExprKind::Paren(ref expr) |
354 ast::ExprKind::Binary(_, _, ref expr) |
355 ast::ExprKind::Index(_, ref expr) |
356 ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
361 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
362 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
363 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
364 let mut subexpr_list = vec![expr.clone()];
366 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
367 subexpr_list.push(subexpr.clone());
370 let parent = subexpr_list.pop().unwrap();
371 (parent, subexpr_list)
374 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
375 match context.config.chain_indent() {
376 IndentStyle::Visual => shape.visual_indent(0),
377 IndentStyle::Block => shape
378 .block_indent(context.config.tab_spaces())
379 .with_max_width(context.config),
383 // Returns the expression's subexpression, if it exists. When the subexpr
384 // is a try! macro, we'll convert it to shorthand when the option is set.
385 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
387 ast::ExprKind::MethodCall(_, ref expressions) => {
388 Some(convert_try(&expressions[0], context))
390 ast::ExprKind::TupField(ref subexpr, _) |
391 ast::ExprKind::Field(ref subexpr, _) |
392 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
397 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
399 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
400 if let Some(subexpr) = convert_try_mac(mac, context) {
410 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
412 fn rewrite_chain_subexpr(
415 context: &RewriteContext,
417 ) -> Option<String> {
418 let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
425 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
426 let types = match segment.parameters {
427 Some(ref params) => match **params {
428 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
433 rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
435 ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
436 ast::ExprKind::TupField(ref expr, ref field) => {
437 let space = match expr.node {
438 ast::ExprKind::TupField(..) => " ",
441 rewrite_element(format!("{}.{}", space, field.node))
443 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
448 // Determines if we can continue formatting a given expression on the same line.
449 fn is_continuable(expr: &ast::Expr) -> bool {
451 ast::ExprKind::Path(..) => true,
456 fn is_try(expr: &ast::Expr) -> bool {
458 ast::ExprKind::Try(..) => true,
463 fn rewrite_method_call(
464 method_name: ast::Ident,
465 types: &[ptr::P<ast::Ty>],
466 args: &[ptr::P<ast::Expr>],
468 context: &RewriteContext,
470 ) -> Option<String> {
471 let (lo, type_str) = if types.is_empty() {
472 (args[0].span.hi(), String::new())
474 let type_list = types
476 .map(|ty| ty.rewrite(context, shape))
477 .collect::<Option<Vec<_>>>()?;
479 let type_str = if context.config.spaces_within_angle_brackets() && !type_list.is_empty() {
480 format!("::< {} >", type_list.join(", "))
482 format!("::<{}>", type_list.join(", "))
485 (types.last().unwrap().span.hi(), type_str)
488 let callee_str = format!(".{}{}", method_name, type_str);
489 let span = mk_sp(lo, span.hi());
491 rewrite_call(context, &callee_str, &args[1..], span, shape)