]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Merge pull request #99 from marcusklaas/bool-expr
[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 {
75         opener: "\"",
76         closer: "\"",
77         line_start: " ",
78         line_end: "\\",
79         width: width,
80         offset: offset,
81         trim_end: false
82     };
83
84     Some(rewrite_string(&s.escape_default(), &fmt))
85 }
86
87 fn rewrite_call(context: &RewriteContext,
88                 callee: &ast::Expr,
89                 args: &[ptr::P<ast::Expr>],
90                 span: Span,
91                 width: usize,
92                 offset: usize)
93         -> Option<String> {
94     debug!("rewrite_call, width: {}, offset: {}", width, offset);
95
96     // TODO using byte lens instead of char lens (and probably all over the place too)
97     let callee_str = try_opt!(callee.rewrite(context, width, offset));
98     debug!("rewrite_call, callee_str: `{}`", callee_str);
99
100     if args.len() == 0 {
101         return Some(format!("{}()", callee_str));
102     }
103
104     // 2 is for parens.
105     let remaining_width = width - callee_str.len() - 2;
106     let offset = callee_str.len() + 1 + offset;
107
108     let items = itemize_list(context.codemap,
109                              Vec::new(),
110                              args.iter(),
111                              ",",
112                              ")",
113                              |item| item.span.lo,
114                              |item| item.span.hi,
115                              // Take old span when rewrite fails.
116                              |item| item.rewrite(context, remaining_width, offset)
117                                         .unwrap_or(context.codemap.span_to_snippet(item.span)
118                                                                   .unwrap()),
119                              callee.span.hi + BytePos(1),
120                              span.hi);
121
122     let fmt = ListFormatting {
123         tactic: ListTactic::HorizontalVertical,
124         separator: ",",
125         trailing_separator: SeparatorTactic::Never,
126         indent: offset,
127         h_width: remaining_width,
128         v_width: remaining_width,
129         ends_with_newline: true,
130     };
131
132     Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
133 }
134
135 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> 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 {
153     debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
154     assert!(fields.len() > 0 || base.is_some());
155
156     enum StructLitField<'a> {
157         Regular(&'a ast::Field),
158         Base(&'a ast::Expr)
159     }
160
161     let path_str = pprust::path_to_string(path);
162     // Foo { a: Foo } - indent is +3, width is -5.
163     let indent = offset + path_str.len() + 3;
164     let budget = width - (path_str.len() + 5);
165
166     let field_iter = fields.into_iter().map(StructLitField::Regular)
167                            .chain(base.into_iter().map(StructLitField::Base));
168
169     let items = itemize_list(context.codemap,
170                              Vec::new(),
171                              field_iter,
172                              ",",
173                              "}",
174                              |item| {
175                                  match *item {
176                                      StructLitField::Regular(ref field) => field.span.lo,
177                                      // 2 = ..
178                                      StructLitField::Base(ref expr) => expr.span.lo - BytePos(2)
179                                  }
180                              },
181                              |item| {
182                                  match *item {
183                                      StructLitField::Regular(ref field) => field.span.hi,
184                                      StructLitField::Base(ref expr) => expr.span.hi
185                                  }
186                              },
187                              |item| {
188                                  match *item {
189                                      StructLitField::Regular(ref field) => {
190                                          rewrite_field(context, &field, budget, indent)
191                                             .unwrap_or(context.codemap.span_to_snippet(field.span)
192                                                                       .unwrap())
193                                      },
194                                      StructLitField::Base(ref expr) => {
195                                          // 2 = ..
196                                          expr.rewrite(context, budget - 2, indent + 2)
197                                              .map(|s| format!("..{}", s))
198                                              .unwrap_or(context.codemap.span_to_snippet(expr.span)
199                                                                        .unwrap())
200                                      }
201                                  }
202                              },
203                              span_after(span, "{", context.codemap),
204                              span.hi);
205
206     let fmt = ListFormatting {
207         tactic: ListTactic::HorizontalVertical,
208         separator: ",",
209         trailing_separator: if base.is_some() {
210             SeparatorTactic::Never
211         } else {
212             context.config.struct_lit_trailing_comma
213         },
214         indent: indent,
215         h_width: budget,
216         v_width: budget,
217         ends_with_newline: true,
218     };
219     let fields_str = write_list(&items, &fmt);
220     Some(format!("{} {{ {} }}", path_str, fields_str))
221
222     // FIXME if the usual multi-line layout is too wide, we should fall back to
223     // Foo {
224     //     a: ...,
225     // }
226 }
227
228 fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
229     let name = &token::get_ident(field.ident.node);
230     let overhead = name.len() + 2;
231     let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
232     expr.map(|s| format!("{}: {}", name, s))
233 }
234
235 fn rewrite_tuple_lit(context: &RewriteContext,
236                      items: &[ptr::P<ast::Expr>],
237                      span: Span,
238                      width: usize,
239                      offset: usize)
240                      -> Option<String> {
241     let indent = offset + 1;
242
243     let items = itemize_list(context.codemap,
244                              Vec::new(),
245                              items.into_iter(),
246                              ",",
247                              ")",
248                              |item| item.span.lo,
249                              |item| item.span.hi,
250                              |item| item.rewrite(context,
251                                                  context.config.max_width - indent - 2,
252                                                  indent)
253                                         .unwrap_or(context.codemap.span_to_snippet(item.span)
254                                                                   .unwrap()),
255                              span.lo + BytePos(1), // Remove parens
256                              span.hi - BytePos(1));
257
258     // In case of length 1, need a trailing comma
259     let trailing_separator_tactic = if items.len() == 1 {
260         SeparatorTactic::Always
261     } else {
262         SeparatorTactic::Never
263     };
264
265     let fmt = ListFormatting {
266         tactic: ListTactic::HorizontalVertical,
267         separator: ",",
268         trailing_separator: trailing_separator_tactic,
269         indent: indent,
270         h_width: width - 2,
271         v_width: width - 2,
272         ends_with_newline: true,
273     };
274
275     Some(format!("({})", write_list(&items, &fmt)))
276 }
277
278 fn rewrite_binary_op(context: &RewriteContext,
279                      op: &ast::BinOp,
280                      lhs: &ast::Expr,
281                      rhs: &ast::Expr,
282                      width: usize,
283                      offset: usize)
284                      -> Option<String> {
285     // FIXME: format comments between operands and operator
286
287     let operator_str = context.codemap.span_to_snippet(op.span).unwrap();
288
289     // 1 = space between lhs expr and operator
290     let mut result = try_opt!(lhs.rewrite(context, width - 1 - operator_str.len(), offset));
291
292     result.push(' ');
293     result.push_str(&operator_str);
294
295     let remaining_width = match result.rfind('\n') {
296         Some(idx) => (context.config.max_width + idx).checked_sub(result.len()).unwrap_or(0),
297         None => width.checked_sub(result.len()).unwrap_or(0)
298     };
299
300     // Get "full width" rhs and see if it fits on the current line. This
301     // usually works fairly well since it tends to place operands of
302     // operations with high precendence close together.
303     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
304
305     if rhs_result.len() > remaining_width {
306         result.push('\n');
307         result.push_str(&make_indent(offset));
308     } else {
309         result.push(' ');
310     };
311
312     result.push_str(&rhs_result);
313     Some(result)
314 }
315
316 fn rewrite_unary_op(context: &RewriteContext,
317                     op: &ast::UnOp,
318                     expr: &ast::Expr,
319                     width: usize,
320                     offset: usize)
321                     -> Option<String> {
322     // For some reason, an UnOp is not spanned like BinOp!
323     let operator_str = match *op {
324         ast::UnOp::UnUniq => "&",
325         ast::UnOp::UnDeref => "*",
326         ast::UnOp::UnNot => "!",
327         ast::UnOp::UnNeg => "-"
328     };
329
330     Some(format!("{}{}", operator_str, try_opt!(expr.rewrite(context, width - 1, offset))))
331 }