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.
11 use visitor::FmtVisitor;
13 use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
15 use syntax::{ast, ptr};
16 use syntax::codemap::{Pos, Span};
17 use syntax::parse::token;
18 use syntax::print::pprust;
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
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);
34 // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
36 let s = s.escape_default();
38 let offset = offset + 1;
39 let indent = make_indent(offset);
42 let mut cur_start = 0;
43 let mut result = String::with_capacity(round_up_to_power_of_two(s.len()));
46 let max_chars = if cur_start == 0 {
48 width - 2 // 2 = " + \
50 config!(max_width) - offset - 1 // 1 = either \ or ;
53 let mut cur_end = cur_start + max_chars;
55 if cur_end >= s.len() {
56 result.push_str(&s[cur_start..]);
60 // Make sure we're on a char boundary.
61 cur_end = next_char(&s, cur_end);
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);
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);
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);
81 result.push_str(&s[cur_start..cur_end]);
82 result.push_str("\\\n");
83 result.push_str(indent);
92 fn rewrite_call(&mut self,
94 args: &[ptr::P<ast::Expr>],
99 debug!("rewrite_call, width: {}, offset: {}", width, offset);
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);
105 let remaining_width = width - callee_str.len() - 2;
106 let offset = callee_str.len() + 1 + offset;
107 let arg_count = args.len();
109 let args_str = if arg_count > 0 {
110 let args: Vec<_> = args.iter().map(|e| (self.rewrite_expr(e,
112 offset), String::new())).collect();
113 let fmt = ListFormatting {
114 tactic: ListTactic::HorizontalVertical,
116 trailing_separator: SeparatorTactic::Never,
118 h_width: remaining_width,
119 v_width: remaining_width,
121 write_list(&args, &fmt)
126 format!("{}({})", callee_str, args_str)
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)
138 fn rewrite_struct_lit(&mut self,
140 fields: &[ast::Field],
141 base: Option<&ast::Expr>,
146 debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
147 assert!(fields.len() > 0 || base.is_some());
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);
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)))
162 let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
163 let fmt = ListFormatting {
164 tactic: ListTactic::HorizontalVertical,
166 trailing_separator: if base.is_some() {
167 SeparatorTactic::Never
169 config!(struct_lit_trailing_comma)
175 let fields_str = write_list(&field_strs, &fmt);
176 format!("{} {{ {} }}", path_str, fields_str)
178 // FIXME if the usual multi-line layout is too wide, we should fall back to
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)
191 fn rewrite_tuple_lit(&mut self, items: &[ptr::P<ast::Expr>], width: usize, offset: usize)
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));
199 // Only last line has width-1 as budget, other may take max_width
200 let item_strs: Vec<_> =
203 .map(|(i, item)| self.rewrite_expr(
205 // last line : given width (minus "("+")"), other lines : max_width
207 if i == items.len() - 1 { width - 2 } else { config!(max_width) - indent - 2 },
210 let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
213 ListTactic::HorizontalVertical
215 // FIXME handle comments
216 let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
217 let fmt = ListFormatting {
220 trailing_separator: SeparatorTactic::Never,
225 let item_str = write_list(&item_strs, &fmt);
226 format!("({})", item_str)
230 pub fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
232 ast::Expr_::ExprLit(ref l) => {
234 ast::Lit_::LitStr(ref is, _) => {
235 let result = self.rewrite_string_lit(&is, l.span, width, offset);
236 debug!("string lit: `{}`", result);
242 ast::Expr_::ExprCall(ref callee, ref args) => {
243 return self.rewrite_call(callee, args, width, offset);
245 ast::Expr_::ExprParen(ref subexpr) => {
246 return self.rewrite_paren(subexpr, width, offset);
248 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
249 return self.rewrite_struct_lit(path,
251 base.as_ref().map(|e| &**e),
255 ast::Expr_::ExprTup(ref items) => {
256 return self.rewrite_tuple_lit(items, width, offset);
261 self.snippet(expr.span)