1 // Copyright 2018 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.
14 use config::IndentStyle;
15 use rewrite::{Rewrite, RewriteContext};
17 use utils::{first_line_width, is_single_line, last_line_width, trimmed_last_line_width, wrap_str};
19 /// Sigils that decorate a binop pair.
20 #[derive(new, Clone, Copy)]
21 pub(crate) struct PairParts<'a> {
27 impl<'a> PairParts<'a> {
28 pub(crate) fn infix(infix: &'a str) -> PairParts<'a> {
37 // Flattens a tree of pairs into a list and tries to rewrite them all at once.
38 // FIXME would be nice to reuse the lists API for this, but because each separator
39 // can be different, we can't.
40 pub(crate) fn rewrite_all_pairs(
43 context: &RewriteContext,
45 // First we try formatting on one line.
46 if let Some(list) = expr.flatten(context, false) {
47 if let Some(r) = rewrite_pairs_one_line(&list, shape, context) {
52 // We can't format on line, so try many. When we flatten here we make sure
53 // to only flatten pairs with the same operator, that way we don't
54 // necessarily need one line per sub-expression, but we don't do anything
55 // too funny wrt precedence.
56 expr.flatten(context, true)
57 .and_then(|list| rewrite_pairs_multiline(list, shape, context))
60 // This may return a multi-line result since we allow the last expression to go
61 // multiline in a 'single line' formatting.
62 fn rewrite_pairs_one_line<T: Rewrite>(
65 context: &RewriteContext,
67 assert!(list.list.len() >= 2, "Not a pair?");
69 let mut result = String::new();
70 let base_shape = shape.block();
72 for (e, s) in list.list.iter().zip(list.separators.iter()) {
73 let cur_shape = base_shape.offset_left(last_line_width(&result))?;
74 let rewrite = e.rewrite(context, cur_shape)?;
76 if !is_single_line(&rewrite) || result.len() > shape.width {
80 result.push_str(&rewrite);
86 let last = list.list.last().unwrap();
87 let cur_shape = base_shape.offset_left(last_line_width(&result))?;
88 let rewrite = last.rewrite(context, cur_shape)?;
89 result.push_str(&rewrite);
91 if first_line_width(&result) > shape.width {
95 // Check the last expression in the list. We let this expression go over
96 // multiple lines, but we check that if this is necessary, then we can't
97 // do better using multi-line formatting.
98 if !is_single_line(&result) {
99 let multiline_shape = shape.offset_left(list.separators.last().unwrap().len() + 1)?;
100 let multiline_list: PairList<T> = PairList {
103 separator_place: list.separator_place,
105 // Format as if we were multi-line.
106 if let Some(rewrite) = rewrite_pairs_multiline(multiline_list, multiline_shape, context) {
107 // Also, don't let expressions surrounded by parens go multi-line,
108 // this looks really bad.
109 if rewrite.starts_with('(') || is_single_line(&rewrite) {
115 wrap_str(result, context.config.max_width(), shape)
118 fn rewrite_pairs_multiline<T: Rewrite>(
121 context: &RewriteContext,
122 ) -> Option<String> {
123 let rhs_offset = shape.rhs_overhead(&context.config);
124 let nested_shape = (match context.config.indent_style() {
125 IndentStyle::Visual => shape.visual_indent(0),
126 IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
127 }).with_max_width(&context.config)
128 .sub_width(rhs_offset)?;
130 let indent_str = nested_shape.indent.to_string_with_newline(context.config);
131 let mut result = String::new();
133 let rewrite = list.list[0].rewrite(context, shape)?;
134 result.push_str(&rewrite);
136 for (e, s) in list.list[1..].iter().zip(list.separators.iter()) {
137 // The following test checks if we should keep two subexprs on the same
138 // line. We do this if not doing so would create an orphan and there is
139 // enough space to do so.
140 let offset = if result.contains('\n') {
145 if last_line_width(&result) + offset <= nested_shape.used_width() {
146 // We must snuggle the next line onto the previous line to avoid an orphan.
147 if let Some(line_shape) =
148 shape.offset_left(s.len() + 2 + trimmed_last_line_width(&result))
150 if let Some(rewrite) = e.rewrite(context, line_shape) {
154 result.push_str(&rewrite);
160 let nested_overhead = s.len() + 1;
161 let line_shape = match context.config.binop_separator() {
162 SeparatorPlace::Back => {
165 result.push_str(&indent_str);
166 nested_shape.sub_width(nested_overhead)?
168 SeparatorPlace::Front => {
169 result.push_str(&indent_str);
172 nested_shape.offset_left(nested_overhead)?
176 let rewrite = e.rewrite(context, line_shape)?;
177 result.push_str(&rewrite);
182 // Rewrites a single pair.
183 pub(crate) fn rewrite_pair<LHS, RHS>(
187 context: &RewriteContext,
189 separator_place: SeparatorPlace,
195 let tab_spaces = context.config.tab_spaces();
196 let lhs_overhead = match separator_place {
197 SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
198 SeparatorPlace::Front => shape.used_width(),
200 let lhs_shape = Shape {
201 width: context.budget(lhs_overhead),
205 .rewrite(context, lhs_shape)
206 .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
208 // Try to put both lhs and rhs on the same line.
209 let rhs_orig_result = shape
210 .offset_left(last_line_width(&lhs_result) + pp.infix.len())
211 .and_then(|s| s.sub_width(pp.suffix.len()))
212 .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
213 if let Some(ref rhs_result) = rhs_orig_result {
214 // If the length of the lhs is equal to or shorter than the tab width or
215 // the rhs looks like block expression, we put the rhs on the same
216 // line with the lhs even if the rhs is multi-lined.
217 let allow_same_line = lhs_result.len() <= tab_spaces || rhs_result
220 .map(|first_line| first_line.ends_with('{'))
222 if !rhs_result.contains('\n') || allow_same_line {
223 let one_line_width = last_line_width(&lhs_result)
225 + first_line_width(rhs_result)
227 if one_line_width <= shape.width {
230 lhs_result, pp.infix, rhs_result, pp.suffix
236 // We have to use multiple lines.
237 // Re-evaluate the rhs because we have more space now:
238 let mut rhs_shape = match context.config.indent_style() {
239 IndentStyle::Visual => shape
240 .sub_width(pp.suffix.len() + pp.prefix.len())?
241 .visual_indent(pp.prefix.len()),
242 IndentStyle::Block => {
243 // Try to calculate the initial constraint on the right hand side.
244 let rhs_overhead = shape.rhs_overhead(context.config);
245 Shape::indented(shape.indent.block_indent(context.config), context.config)
246 .sub_width(rhs_overhead)?
249 let infix = match separator_place {
250 SeparatorPlace::Back => pp.infix.trim_right(),
251 SeparatorPlace::Front => pp.infix.trim_left(),
253 if separator_place == SeparatorPlace::Front {
254 rhs_shape = rhs_shape.offset_left(infix.len())?;
256 let rhs_result = rhs.rewrite(context, rhs_shape)?;
257 let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
258 let infix_with_sep = match separator_place {
259 SeparatorPlace::Back => format!("{}{}", infix, indent_str),
260 SeparatorPlace::Front => format!("{}{}", indent_str, infix),
264 lhs_result, infix_with_sep, rhs_result, pp.suffix
268 // A pair which forms a tree and can be flattened (e.g., binops).
269 trait FlattenPair: Rewrite + Sized {
270 // If `_same_op` is `true`, then we only combine binops with the same
271 // operator into the list. E.g,, if the source is `a * b + c`, if `_same_op`
272 // is true, we make `[(a * b), c]` if `_same_op` is false, we make
274 fn flatten(&self, _context: &RewriteContext, _same_op: bool) -> Option<PairList<Self>> {
279 struct PairList<'a, 'b, T: Rewrite + 'b> {
281 separators: Vec<&'a str>,
282 separator_place: SeparatorPlace,
285 impl FlattenPair for ast::Expr {
286 fn flatten(&self, context: &RewriteContext, same_op: bool) -> Option<PairList<ast::Expr>> {
287 let top_op = match self.node {
288 ast::ExprKind::Binary(op, _, _) => op.node,
292 // Turn a tree of binop expressions into a list using a depth-first,
293 // in-order traversal.
294 let mut stack = vec![];
295 let mut list = vec![];
296 let mut separators = vec![];
300 ast::ExprKind::Binary(op, ref lhs, _) if !same_op || op.node == top_op => {
306 if let Some(pop) = stack.pop() {
308 ast::ExprKind::Binary(op, _, ref rhs) => {
309 separators.push(op.node.to_string());
321 assert_eq!(list.len() - 1, separators.len());
325 separator_place: context.config.binop_separator(),
330 impl FlattenPair for ast::Ty {}
331 impl FlattenPair for ast::Pat {}