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