]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Add a try_opt! macro for ease of work with Rewrite
[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 mut args_rewritten = Vec::with_capacity(args.len());
146         for arg in args.iter() {
147             args_rewritten.push((try_opt!(arg.rewrite(context, remaining_width, offset)),
148                                  String::new()));
149         }
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 mut field_strs = Vec::with_capacity(fields.len());
192     for field in fields.iter() {
193         field_strs.push(try_opt!(rewrite_field(context, field, budget, indent)));
194     }
195     if let Some(expr) = base {
196         // Another 2 on the width/indent for the ..
197         field_strs.push(format!("..{}", try_opt!(expr.rewrite(context, budget - 2, indent + 2))));
198     }
199
200     // FIXME comments
201     let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
202     let fmt = ListFormatting {
203         tactic: ListTactic::HorizontalVertical,
204         separator: ",",
205         trailing_separator: if base.is_some() {
206             SeparatorTactic::Never
207         } else {
208             config!(struct_lit_trailing_comma)
209         },
210         indent: indent,
211         h_width: budget,
212         v_width: budget,
213     };
214     let fields_str = write_list(&field_strs, &fmt);
215     Some(format!("{} {{ {} }}", path_str, fields_str))
216
217         // FIXME if the usual multi-line layout is too wide, we should fall back to
218         // Foo {
219         //     a: ...,
220         // }
221 }
222
223 fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
224     let name = &token::get_ident(field.ident.node);
225     let overhead = name.len() + 2;
226     let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
227     expr.map(|s| format!("{}: {}", name, s))
228 }
229
230 fn rewrite_tuple_lit(context: &RewriteContext,
231                      items: &[ptr::P<ast::Expr>],
232                      width: usize,
233                      offset: usize)
234     -> Option<String> {
235         // opening paren
236         let indent = offset + 1;
237         // In case of length 1, need a trailing comma
238         if items.len() == 1 {
239             return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
240         }
241         // Only last line has width-1 as budget, other may take max_width
242         let mut item_strs = Vec::with_capacity(items.len());
243         for (i, item) in items.iter().enumerate() {
244             let rem_width = if i == items.len() - 1 {
245                 width - 2
246             } else {
247                 config!(max_width) - indent - 2
248             };
249             item_strs.push(try_opt!(item.rewrite(context, rem_width, indent)));
250         }
251         let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
252             ListTactic::Vertical
253         } else {
254             ListTactic::HorizontalVertical
255         };
256         // FIXME handle comments
257         let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
258         let fmt = ListFormatting {
259             tactic: tactics,
260             separator: ",",
261             trailing_separator: SeparatorTactic::Never,
262             indent: indent,
263             h_width: width - 2,
264             v_width: width - 2,
265         };
266         let item_str = write_list(&item_strs, &fmt);
267         Some(format!("({})", item_str))
268     }