]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Use FromIterator implementation for Option
[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 utils::*;
12 use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
13 use rewrite::{Rewrite, RewriteContext};
14
15 use syntax::{ast, ptr};
16 use syntax::codemap::{Pos, Span};
17 use syntax::parse::token;
18 use syntax::print::pprust;
19
20 use MIN_STRING;
21
22 impl Rewrite for ast::Expr {
23     fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
24         match self.node {
25             ast::Expr_::ExprLit(ref l) => {
26                 match l.node {
27                     ast::Lit_::LitStr(ref is, _) => {
28                         let result = rewrite_string_lit(context, &is, l.span, width, offset);
29                         debug!("string lit: `{:?}`", result);
30                         return result;
31                     }
32                     _ => {}
33                 }
34             }
35             ast::Expr_::ExprCall(ref callee, ref args) => {
36                 return rewrite_call(context, callee, args, width, offset);
37             }
38             ast::Expr_::ExprParen(ref subexpr) => {
39                 return rewrite_paren(context, subexpr, width, offset);
40             }
41             ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
42                 return rewrite_struct_lit(context, path,
43                                                fields,
44                                                base.as_ref().map(|e| &**e),
45                                                width,
46                                                offset);
47             }
48             ast::Expr_::ExprTup(ref items) => {
49                 return rewrite_tuple_lit(context, items, width, offset);
50             }
51             _ => {}
52         }
53
54         context.codemap.span_to_snippet(self.span).ok()
55     }
56 }
57
58 fn rewrite_string_lit(context: &RewriteContext, s: &str, span: Span, width: usize, offset: usize) -> Option<String> {
59     // FIXME I bet this stomps unicode escapes in the source string
60
61     // Check if there is anything to fix: we always try to fixup multi-line
62     // strings, or if the string is too long for the line.
63     let l_loc = context.codemap.lookup_char_pos(span.lo);
64     let r_loc = context.codemap.lookup_char_pos(span.hi);
65     if l_loc.line == r_loc.line && r_loc.col.to_usize() <= config!(max_width) {
66         return context.codemap.span_to_snippet(span).ok();
67     }
68
69     // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
70
71     let s = s.escape_default();
72
73     let offset = offset + 1;
74     let indent = make_indent(offset);
75     let indent = &indent;
76
77     let mut cur_start = 0;
78     let mut result = String::with_capacity(round_up_to_power_of_two(s.len()));
79     result.push('"');
80     loop {
81         let max_chars = if cur_start == 0 {
82             // First line.
83             width - 2 // 2 = " + \
84         } else {
85             config!(max_width) - offset - 1 // 1 = either \ or ;
86         };
87
88         let mut cur_end = cur_start + max_chars;
89
90         if cur_end >= s.len() {
91             result.push_str(&s[cur_start..]);
92             break;
93         }
94
95         // Make sure we're on a char boundary.
96         cur_end = next_char(&s, cur_end);
97
98         // Push cur_end left until we reach whitespace
99         while !s.char_at(cur_end-1).is_whitespace() {
100             cur_end = prev_char(&s, cur_end);
101
102             if cur_end - cur_start < MIN_STRING {
103                 // We can't break at whitespace, fall back to splitting
104                 // anywhere that doesn't break an escape sequence
105                 cur_end = next_char(&s, cur_start + max_chars);
106                 while s.char_at(prev_char(&s, cur_end)) == '\\' {
107                     cur_end = prev_char(&s, cur_end);
108                 }
109                 break;
110             }
111         }
112         // Make sure there is no whitespace to the right of the break.
113         while cur_end < s.len() && s.char_at(cur_end).is_whitespace() {
114             cur_end = next_char(&s, cur_end+1);
115         }
116         result.push_str(&s[cur_start..cur_end]);
117         result.push_str("\\\n");
118         result.push_str(indent);
119
120         cur_start = cur_end;
121     }
122     result.push('"');
123
124     Some(result)
125 }
126
127 fn rewrite_call(context: &RewriteContext,
128                 callee: &ast::Expr,
129                 args: &[ptr::P<ast::Expr>],
130                 width: usize,
131                 offset: usize)
132         -> Option<String>
133 {
134     debug!("rewrite_call, width: {}, offset: {}", width, offset);
135
136     // TODO using byte lens instead of char lens (and probably all over the place too)
137     let callee_str = try_opt!(callee.rewrite(context, width, offset));
138     debug!("rewrite_call, callee_str: `{:?}`", callee_str);
139     // 2 is for parens.
140     let remaining_width = width - callee_str.len() - 2;
141     let offset = callee_str.len() + 1 + offset;
142     let arg_count = args.len();
143
144     let args_str = if arg_count > 0 {
145         let args_rewritten: Vec<_> =
146             try_opt!(args.iter()
147                          .map(|arg| arg.rewrite(context, remaining_width, offset)
148                                        .map(|arg_str| (arg_str, String::new())))
149                          .collect());
150         let fmt = ListFormatting {
151             tactic: ListTactic::HorizontalVertical,
152             separator: ",",
153             trailing_separator: SeparatorTactic::Never,
154             indent: offset,
155             h_width: remaining_width,
156             v_width: remaining_width,
157         };
158         write_list(&args_rewritten, &fmt)
159     } else {
160         String::new()
161     };
162
163     Some(format!("{}({})", callee_str, args_str))
164 }
165
166 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
167     debug!("rewrite_paren, width: {}, offset: {}", width, offset);
168     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
169     // paren on the same line as the subexpr
170     let subexpr_str = subexpr.rewrite(context, width-2, offset+1);
171     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
172     subexpr_str.map(|s| format!("({})", s))
173 }
174
175 fn rewrite_struct_lit(context: &RewriteContext,
176                       path: &ast::Path,
177                       fields: &[ast::Field],
178                       base: Option<&ast::Expr>,
179                       width: usize,
180                       offset: usize)
181         -> Option<String>
182 {
183     debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
184     assert!(fields.len() > 0 || base.is_some());
185
186     let path_str = pprust::path_to_string(path);
187     // Foo { a: Foo } - indent is +3, width is -5.
188     let indent = offset + path_str.len() + 3;
189     let budget = width - (path_str.len() + 5);
190
191     let field_strs: Vec<_> =
192         try_opt!(fields.iter()
193                        .map(|field| rewrite_field(context, field, budget, indent))
194                        .chain(base.iter()
195                                   .map(|expr| expr.rewrite(context,
196                                                            // 2 = ".."
197                                                            budget - 2,
198                                                            indent + 2)
199                                                   .map(|s| format!("..{}", s))))
200                        .collect());
201     // FIXME comments
202     let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
203     let fmt = ListFormatting {
204         tactic: ListTactic::HorizontalVertical,
205         separator: ",",
206         trailing_separator: if base.is_some() {
207             SeparatorTactic::Never
208         } else {
209             config!(struct_lit_trailing_comma)
210         },
211         indent: indent,
212         h_width: budget,
213         v_width: budget,
214     };
215     let fields_str = write_list(&field_strs, &fmt);
216     Some(format!("{} {{ {} }}", path_str, fields_str))
217
218         // FIXME if the usual multi-line layout is too wide, we should fall back to
219         // Foo {
220         //     a: ...,
221         // }
222 }
223
224 fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
225     let name = &token::get_ident(field.ident.node);
226     let overhead = name.len() + 2;
227     let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
228     expr.map(|s| format!("{}: {}", name, s))
229 }
230
231 fn rewrite_tuple_lit(context: &RewriteContext,
232                      items: &[ptr::P<ast::Expr>],
233                      width: usize,
234                      offset: usize)
235     -> Option<String> {
236         // opening paren
237         let indent = offset + 1;
238         // In case of length 1, need a trailing comma
239         if items.len() == 1 {
240             return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
241         }
242         // Only last line has width-1 as budget, other may take max_width
243         let item_strs: Vec<_> =
244             try_opt!(items.iter()
245                           .enumerate()
246                           .map(|(i, item)| {
247                               let rem_width = if i == items.len() - 1 {
248                                   width - 2
249                               } else {
250                                   config!(max_width) - indent - 2
251                               };
252                               item.rewrite(context, rem_width, indent)
253                           })
254                           .collect());
255         let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
256             ListTactic::Vertical
257         } else {
258             ListTactic::HorizontalVertical
259         };
260         // FIXME handle comments
261         let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
262         let fmt = ListFormatting {
263             tactic: tactics,
264             separator: ",",
265             trailing_separator: SeparatorTactic::Never,
266             indent: indent,
267             h_width: width - 2,
268             v_width: width - 2,
269         };
270         let item_str = write_list(&item_strs, &fmt);
271         Some(format!("({})", item_str))
272     }