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.
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.
12 use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
13 use rewrite::{Rewrite, RewriteContext};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{Pos, Span};
17 use syntax::parse::token;
18 use syntax::print::pprust;
22 impl Rewrite for ast::Expr {
23 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
25 ast::Expr_::ExprLit(ref l) => {
27 ast::Lit_::LitStr(ref is, _) => {
28 let result = rewrite_string_lit(context, &is, l.span, width, offset);
29 debug!("string lit: `{:?}`", result);
35 ast::Expr_::ExprCall(ref callee, ref args) => {
36 return rewrite_call(context, callee, args, width, offset);
38 ast::Expr_::ExprParen(ref subexpr) => {
39 return rewrite_paren(context, subexpr, width, offset);
41 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
42 return rewrite_struct_lit(context, path,
44 base.as_ref().map(|e| &**e),
48 ast::Expr_::ExprTup(ref items) => {
49 return rewrite_tuple_lit(context, items, width, offset);
54 context.codemap.span_to_snippet(self.span).ok()
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
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();
69 // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
71 let s = s.escape_default();
73 let offset = offset + 1;
74 let indent = make_indent(offset);
77 let mut cur_start = 0;
78 let mut result = String::with_capacity(round_up_to_power_of_two(s.len()));
81 let max_chars = if cur_start == 0 {
83 width - 2 // 2 = " + \
85 config!(max_width) - offset - 1 // 1 = either \ or ;
88 let mut cur_end = cur_start + max_chars;
90 if cur_end >= s.len() {
91 result.push_str(&s[cur_start..]);
95 // Make sure we're on a char boundary.
96 cur_end = next_char(&s, cur_end);
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);
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);
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);
116 result.push_str(&s[cur_start..cur_end]);
117 result.push_str("\\\n");
118 result.push_str(indent);
127 fn rewrite_call(context: &RewriteContext,
129 args: &[ptr::P<ast::Expr>],
134 debug!("rewrite_call, width: {}, offset: {}", width, offset);
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);
140 let remaining_width = width - callee_str.len() - 2;
141 let offset = callee_str.len() + 1 + offset;
142 let arg_count = args.len();
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)),
150 let fmt = ListFormatting {
151 tactic: ListTactic::HorizontalVertical,
153 trailing_separator: SeparatorTactic::Never,
155 h_width: remaining_width,
156 v_width: remaining_width,
158 write_list(&args_rewritten, &fmt)
163 Some(format!("{}({})", callee_str, args_str))
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))
175 fn rewrite_struct_lit(context: &RewriteContext,
177 fields: &[ast::Field],
178 base: Option<&ast::Expr>,
183 debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
184 assert!(fields.len() > 0 || base.is_some());
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);
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)));
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))));
201 let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
202 let fmt = ListFormatting {
203 tactic: ListTactic::HorizontalVertical,
205 trailing_separator: if base.is_some() {
206 SeparatorTactic::Never
208 config!(struct_lit_trailing_comma)
214 let fields_str = write_list(&field_strs, &fmt);
215 Some(format!("{} {{ {} }}", path_str, fields_str))
217 // FIXME if the usual multi-line layout is too wide, we should fall back to
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))
230 fn rewrite_tuple_lit(context: &RewriteContext,
231 items: &[ptr::P<ast::Expr>],
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));
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 {
247 config!(max_width) - indent - 2
249 item_strs.push(try_opt!(item.rewrite(context, rem_width, indent)));
251 let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
254 ListTactic::HorizontalVertical
256 // FIXME handle comments
257 let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
258 let fmt = ListFormatting {
261 trailing_separator: SeparatorTactic::Never,
266 let item_str = write_list(&item_strs, &fmt);
267 Some(format!("({})", item_str))