]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Fix bug in rewrite_tup_lit
[rust.git] / src / expr.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 use rewrite::{Rewrite, RewriteContext};
12 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
13 use string::{StringFormat, rewrite_string};
14 use utils::{span_after, make_indent};
15
16 use syntax::{ast, ptr};
17 use syntax::codemap::{Pos, Span, BytePos};
18 use syntax::parse::token;
19 use syntax::print::pprust;
20
21 impl Rewrite for ast::Expr {
22     fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
23         match self.node {
24             ast::Expr_::ExprLit(ref l) => {
25                 match l.node {
26                     ast::Lit_::LitStr(ref is, _) => {
27                         rewrite_string_lit(context, &is, l.span, width, offset)
28                     }
29                     _ => context.codemap.span_to_snippet(self.span).ok()
30                 }
31             }
32             ast::Expr_::ExprCall(ref callee, ref args) => {
33                 rewrite_call(context, callee, args, self.span, width, offset)
34             }
35             ast::Expr_::ExprParen(ref subexpr) => {
36                 rewrite_paren(context, subexpr, width, offset)
37             }
38             ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
39                 rewrite_binary_op(context, op, lhs, rhs, width, offset)
40             }
41             ast::Expr_::ExprUnary(ref op, ref subexpr) => {
42                 rewrite_unary_op(context, op, subexpr, width, offset)
43             }
44             ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
45                 rewrite_struct_lit(context,
46                                    path,
47                                    fields,
48                                    base.as_ref().map(|e| &**e),
49                                    self.span,
50                                    width,
51                                    offset)
52             }
53             ast::Expr_::ExprTup(ref items) => {
54                 rewrite_tuple_lit(context, items, self.span, width, offset)
55             }
56             _ => context.codemap.span_to_snippet(self.span).ok()
57         }
58     }
59 }
60
61 fn rewrite_string_lit(context: &RewriteContext,
62                       s: &str,
63                       span: Span,
64                       width: usize,
65                       offset: usize)
66                       -> Option<String> {
67     // Check if there is anything to fix: we always try to fixup multi-line
68     // strings, or if the string is too long for the line.
69     let l_loc = context.codemap.lookup_char_pos(span.lo);
70     let r_loc = context.codemap.lookup_char_pos(span.hi);
71     if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
72         return context.codemap.span_to_snippet(span).ok();
73     }
74     let fmt = StringFormat { opener: "\"",
75                              closer: "\"",
76                              line_start: " ",
77                              line_end: "\\",
78                              width: width,
79                              offset: offset,
80                              trim_end: false, };
81
82     Some(rewrite_string(&s.escape_default(), &fmt))
83 }
84
85 fn rewrite_call(context: &RewriteContext,
86                 callee: &ast::Expr,
87                 args: &[ptr::P<ast::Expr>],
88                 span: Span,
89                 width: usize,
90                 offset: usize)
91                 -> Option<String> {
92     debug!("rewrite_call, width: {}, offset: {}", width, offset);
93
94     // TODO using byte lens instead of char lens (and probably all over the place too)
95     let callee_str = try_opt!(callee.rewrite(context, width, offset));
96     debug!("rewrite_call, callee_str: `{}`", callee_str);
97
98     if args.len() == 0 {
99         return Some(format!("{}()", callee_str));
100     }
101
102     // 2 is for parens.
103     let remaining_width = width - callee_str.len() - 2;
104     let offset = callee_str.len() + 1 + offset;
105
106     let items = itemize_list(context.codemap,
107                              Vec::new(),
108                              args.iter(),
109                              ",",
110                              ")",
111                              |item| item.span.lo,
112                              |item| item.span.hi,
113                              // Take old span when rewrite fails.
114                              |item| item.rewrite(context, remaining_width, offset)
115                                         .unwrap_or(context.codemap.span_to_snippet(item.span)
116                                                                   .unwrap()),
117                              callee.span.hi + BytePos(1),
118                              span.hi);
119
120     let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
121                                separator: ",",
122                                trailing_separator: SeparatorTactic::Never,
123                                indent: offset,
124                                h_width: remaining_width,
125                                v_width: remaining_width,
126                                ends_with_newline: true, };
127
128     Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
129 }
130
131 fn rewrite_paren(context: &RewriteContext,
132                  subexpr: &ast::Expr,
133                  width: usize,
134                  offset: usize)
135                  -> Option<String> {
136     debug!("rewrite_paren, width: {}, offset: {}", width, offset);
137     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
138     // paren on the same line as the subexpr
139     let subexpr_str = subexpr.rewrite(context, width-2, offset+1);
140     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
141     subexpr_str.map(|s| format!("({})", s))
142 }
143
144 fn rewrite_struct_lit<'a>(context: &RewriteContext,
145                           path: &ast::Path,
146                           fields: &'a [ast::Field],
147                           base: Option<&'a ast::Expr>,
148                           span: Span,
149                           width: usize,
150                           offset: usize)
151                           -> Option<String> {
152     debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
153     assert!(fields.len() > 0 || base.is_some());
154
155     enum StructLitField<'a> {
156         Regular(&'a ast::Field),
157         Base(&'a ast::Expr),
158     }
159
160     let path_str = pprust::path_to_string(path);
161     // Foo { a: Foo } - indent is +3, width is -5.
162     let indent = offset + path_str.len() + 3;
163     let budget = width - (path_str.len() + 5);
164
165     let field_iter = fields.into_iter().map(StructLitField::Regular)
166                            .chain(base.into_iter().map(StructLitField::Base));
167
168     let items = itemize_list(context.codemap,
169                              Vec::new(),
170                              field_iter,
171                              ",",
172                              "}",
173                              |item| {
174                                  match *item {
175                                      StructLitField::Regular(ref field) => field.span.lo,
176                                      // 2 = ..
177                                      StructLitField::Base(ref expr) => expr.span.lo - BytePos(2)
178                                  }
179                              },
180                              |item| {
181                                  match *item {
182                                      StructLitField::Regular(ref field) => field.span.hi,
183                                      StructLitField::Base(ref expr) => expr.span.hi
184                                  }
185                              },
186                              |item| {
187                                  match *item {
188                                      StructLitField::Regular(ref field) => {
189                                          rewrite_field(context, &field, budget, indent)
190                                             .unwrap_or(context.codemap.span_to_snippet(field.span)
191                                                                       .unwrap())
192                                      },
193                                      StructLitField::Base(ref expr) => {
194                                          // 2 = ..
195                                          expr.rewrite(context, budget - 2, indent + 2)
196                                              .map(|s| format!("..{}", s))
197                                              .unwrap_or(context.codemap.span_to_snippet(expr.span)
198                                                                        .unwrap())
199                                      }
200                                  }
201                              },
202                              span_after(span, "{", context.codemap),
203                              span.hi);
204
205     let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
206                                separator: ",",
207                                trailing_separator: if base.is_some() {
208             SeparatorTactic::Never
209         } else {
210             context.config.struct_lit_trailing_comma
211         },
212                                indent: indent,
213                                h_width: budget,
214                                v_width: budget,
215                                ends_with_newline: true, };
216     let fields_str = write_list(&items, &fmt);
217     Some(format!("{} {{ {} }}", path_str, fields_str))
218
219     // FIXME if the usual multi-line layout is too wide, we should fall back to
220     // Foo {
221     //     a: ...,
222     // }
223 }
224
225 fn rewrite_field(context: &RewriteContext,
226                  field: &ast::Field,
227                  width: usize,
228                  offset: usize)
229                  -> Option<String> {
230     let name = &token::get_ident(field.ident.node);
231     let overhead = name.len() + 2;
232     let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
233     expr.map(|s| format!("{}: {}", name, s))
234 }
235
236 fn rewrite_tuple_lit(context: &RewriteContext,
237                      items: &[ptr::P<ast::Expr>],
238                      span: Span,
239                      width: usize,
240                      offset: usize)
241                      -> Option<String> {
242     debug!("rewrite_tuple_lit: width: {}, offset: {}", width, offset);
243     let indent = offset + 1;
244     // In case of length 1, need a trailing comma
245     if items.len() == 1 {
246         // 3 = "(" + ",)"
247         return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
248     }
249
250     let items = itemize_list(context.codemap,
251                              Vec::new(),
252                              items.into_iter(),
253                              ",",
254                              ")",
255                              |item| item.span.lo,
256                              |item| item.span.hi,
257                              |item| item.rewrite(context,
258                                                  context.config.max_width - indent - 1,
259                                                  indent)
260                                         .unwrap_or(context.codemap.span_to_snippet(item.span)
261                                                                   .unwrap()),
262                              span.lo + BytePos(1), // Remove parens
263                              span.hi - BytePos(1));
264
265     let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
266                                separator: ",",
267                                trailing_separator: SeparatorTactic::Never,
268                                indent: indent,
269                                h_width: width - 2,
270                                v_width: width - 2,
271                                ends_with_newline: true, };
272
273     Some(format!("({})", write_list(&items, &fmt)))
274 }
275
276 fn rewrite_binary_op(context: &RewriteContext,
277                      op: &ast::BinOp,
278                      lhs: &ast::Expr,
279                      rhs: &ast::Expr,
280                      width: usize,
281                      offset: usize)
282                      -> Option<String> {
283     // FIXME: format comments between operands and operator
284
285     let operator_str = context.codemap.span_to_snippet(op.span).unwrap();
286
287     // 1 = space between lhs expr and operator
288     let mut result =
289         try_opt!(lhs.rewrite(context, context.config.max_width - offset - 1 - operator_str.len(), offset));
290
291     result.push(' ');
292     result.push_str(&operator_str);
293
294     let remaining_width = match result.rfind('\n') {
295         Some(idx) => (offset + width + idx).checked_sub(result.len()).unwrap_or(0),
296         None => width.checked_sub(result.len()).unwrap_or(0)
297     };
298
299     // Get "full width" rhs and see if it fits on the current line. This
300     // usually works fairly well since it tends to place operands of
301     // operations with high precendence close together.
302     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
303
304     // Second condition is needed in case of line break not caused by a
305     // shortage of space, but by end-of-line comments, for example.
306     if rhs_result.len() > remaining_width || rhs_result.contains('\n') {
307         result.push('\n');
308         result.push_str(&make_indent(offset));
309     } else {
310         result.push(' ');
311     };
312
313     result.push_str(&rhs_result);
314     Some(result)
315 }
316
317 fn rewrite_unary_op(context: &RewriteContext,
318                     op: &ast::UnOp,
319                     expr: &ast::Expr,
320                     width: usize,
321                     offset: usize)
322                     -> Option<String> {
323     // For some reason, an UnOp is not spanned like BinOp!
324     let operator_str = match *op {
325         ast::UnOp::UnUniq => "&",
326         ast::UnOp::UnDeref => "*",
327         ast::UnOp::UnNot => "!",
328         ast::UnOp::UnNeg => "-"
329     };
330
331     Some(format!("{}{}", operator_str, try_opt!(expr.rewrite(context, width - 1, offset))))
332 }