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