]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Merge pull request #309 from marcusklaas/array-literals
[rust.git] / src / chains.rs
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.
4 //
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.
10
11 // Formatting of chained expressions, i.e. expressions which are chained by
12 // dots: struct and enum field access and method calls.
13 //
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.
17 //
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.
21
22 use rewrite::{Rewrite, RewriteContext};
23 use utils::{first_line_width, make_indent};
24 use expr::rewrite_call;
25
26 use syntax::{ast, ptr};
27 use syntax::codemap::{mk_sp, Span};
28 use syntax::print::pprust;
29
30 pub fn rewrite_chain(mut expr: &ast::Expr,
31                      context: &RewriteContext,
32                      width: usize,
33                      offset: usize)
34                      -> Option<String> {
35     let total_span = expr.span;
36     let mut subexpr_list = vec![expr];
37
38     while let Some(subexpr) = pop_expr_chain(expr) {
39         subexpr_list.push(subexpr);
40         expr = subexpr;
41     }
42
43     let parent = subexpr_list.pop().unwrap();
44     let parent_rewrite = try_opt!(expr.rewrite(context, width, offset));
45     let (extra_indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
46                                     parent_rewrite.len() <= context.config.tab_spaces {
47         (parent_rewrite.len(), true)
48     } else {
49         (context.config.tab_spaces, false)
50     };
51     let indent = offset + extra_indent;
52
53     let max_width = try_opt!(width.checked_sub(extra_indent));
54     let mut rewrites = try_opt!(subexpr_list.iter()
55                                             .rev()
56                                             .map(|e| {
57                                                 rewrite_chain_expr(e,
58                                                                    total_span,
59                                                                    context,
60                                                                    max_width,
61                                                                    indent)
62                                             })
63                                             .collect::<Option<Vec<_>>>());
64
65     // Total of all items excluding the last.
66     let almost_total = rewrites.split_last()
67                                .unwrap()
68                                .1
69                                .iter()
70                                .fold(0, |a, b| a + first_line_width(b)) +
71                        parent_rewrite.len();
72     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
73     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
74         // Look at the source code. Unless all chain elements start on the same
75         // line, we won't consider putting them on a single line either.
76         let first_line_no = context.codemap.lookup_char_pos(subexpr_list[0].span.lo).line;
77
78         subexpr_list[1..]
79             .iter()
80             .any(|ex| context.codemap.lookup_char_pos(ex.span.hi).line != first_line_no)
81     } else {
82         false
83     };
84
85     let fits_single_line = !veto_single_line &&
86                            match subexpr_list[0].node {
87         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
88             if context.config.chains_overflow_last => {
89             let (last, init) = rewrites.split_last_mut().unwrap();
90
91             if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
92                 let last_rewrite = width.checked_sub(almost_total)
93                                         .and_then(|inner_width| {
94                                             rewrite_method_call(method_name.node,
95                                                                 types,
96                                                                 expressions,
97                                                                 total_span,
98                                                                 context,
99                                                                 inner_width,
100                                                                 offset + almost_total)
101                                         });
102                 match last_rewrite {
103                     Some(mut string) => {
104                         ::std::mem::swap(&mut string, last);
105                         true
106                     }
107                     None => false,
108                 }
109             } else {
110                 false
111             }
112         }
113         _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
114     };
115
116     let connector = if fits_single_line {
117         String::new()
118     } else {
119         format!("\n{}", make_indent(indent))
120     };
121
122     let first_connector = if extend {
123         ""
124     } else {
125         &connector[..]
126     };
127
128     Some(format!("{}{}{}", parent_rewrite, first_connector, rewrites.join(&connector)))
129 }
130
131 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
132     match expr.node {
133         ast::Expr_::ExprMethodCall(_, _, ref expressions) => {
134             Some(&expressions[0])
135         }
136         ast::Expr_::ExprTupField(ref subexpr, _) |
137         ast::Expr_::ExprField(ref subexpr, _) => {
138             Some(subexpr)
139         }
140         _ => None,
141     }
142 }
143
144 fn rewrite_chain_expr(expr: &ast::Expr,
145                       span: Span,
146                       context: &RewriteContext,
147                       width: usize,
148                       offset: usize)
149                       -> Option<String> {
150     match expr.node {
151         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
152             let inner = &RewriteContext {
153                 block_indent: offset,
154                 ..*context
155             };
156             rewrite_method_call(method_name.node, types, expressions, span, inner, width, offset)
157         }
158         ast::Expr_::ExprField(_, ref field) => {
159             Some(format!(".{}", field.node))
160         }
161         ast::Expr_::ExprTupField(_, ref field) => {
162             Some(format!(".{}", field.node))
163         }
164         _ => unreachable!(),
165     }
166 }
167
168 // Determines we can continue formatting a given expression on the same line.
169 fn is_continuable(expr: &ast::Expr) -> bool {
170     match expr.node {
171         ast::Expr_::ExprPath(..) => true,
172         _ => false,
173     }
174 }
175
176 fn rewrite_method_call(method_name: ast::Ident,
177                        types: &[ptr::P<ast::Ty>],
178                        args: &[ptr::P<ast::Expr>],
179                        span: Span,
180                        context: &RewriteContext,
181                        width: usize,
182                        offset: usize)
183                        -> Option<String> {
184     let type_str = if types.is_empty() {
185         String::new()
186     } else {
187         let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
188         format!("::<{}>", type_list.join(", "))
189     };
190
191     let callee_str = format!(".{}{}", method_name, type_str);
192     let span = mk_sp(args[0].span.hi, span.hi);
193
194     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
195 }