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 rewrite::{Rewrite, RewriteContext};
12 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
13 use string::{StringFormat, rewrite_string};
14 use utils::{span_after, make_indent};
16 use syntax::{ast, ptr};
17 use syntax::codemap::{Pos, Span, BytePos};
18 use syntax::parse::token;
19 use syntax::print::pprust;
21 impl Rewrite for ast::Expr {
22 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
24 ast::Expr_::ExprLit(ref l) => {
26 ast::Lit_::LitStr(ref is, _) => {
27 rewrite_string_lit(context, &is, l.span, width, offset)
29 _ => context.codemap.span_to_snippet(self.span).ok()
32 ast::Expr_::ExprCall(ref callee, ref args) => {
33 rewrite_call(context, callee, args, self.span, width, offset)
35 ast::Expr_::ExprParen(ref subexpr) => {
36 rewrite_paren(context, subexpr, width, offset)
38 ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
39 rewrite_binary_op(context, op, lhs, rhs, width, offset)
41 ast::Expr_::ExprUnary(ref op, ref subexpr) => {
42 rewrite_unary_op(context, op, subexpr, width, offset)
44 ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
45 rewrite_struct_lit(context,
48 base.as_ref().map(|e| &**e),
53 ast::Expr_::ExprTup(ref items) => {
54 rewrite_tuple_lit(context, items, self.span, width, offset)
56 _ => context.codemap.span_to_snippet(self.span).ok()
61 fn rewrite_string_lit(context: &RewriteContext,
67 // Check if there is anything to fix: we always try to fixup multi-line
68 // strings, or if the string is too long for the line.
69 let l_loc = context.codemap.lookup_char_pos(span.lo);
70 let r_loc = context.codemap.lookup_char_pos(span.hi);
71 if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
72 return context.codemap.span_to_snippet(span).ok();
74 let fmt = StringFormat { opener: "\"",
82 Some(rewrite_string(&s.escape_default(), &fmt))
85 fn rewrite_call(context: &RewriteContext,
87 args: &[ptr::P<ast::Expr>],
92 debug!("rewrite_call, width: {}, offset: {}", width, offset);
94 // TODO using byte lens instead of char lens (and probably all over the place too)
95 let callee_str = try_opt!(callee.rewrite(context, width, offset));
96 debug!("rewrite_call, callee_str: `{}`", callee_str);
99 return Some(format!("{}()", callee_str));
103 let remaining_width = width - callee_str.len() - 2;
104 let offset = callee_str.len() + 1 + offset;
106 let items = itemize_list(context.codemap,
113 // Take old span when rewrite fails.
114 |item| item.rewrite(context, remaining_width, offset)
115 .unwrap_or(context.codemap.span_to_snippet(item.span)
117 callee.span.hi + BytePos(1),
120 let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
122 trailing_separator: SeparatorTactic::Never,
124 h_width: remaining_width,
125 v_width: remaining_width,
126 ends_with_newline: true, };
128 Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
131 fn rewrite_paren(context: &RewriteContext,
136 debug!("rewrite_paren, width: {}, offset: {}", width, offset);
137 // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
138 // paren on the same line as the subexpr
139 let subexpr_str = subexpr.rewrite(context, width-2, offset+1);
140 debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
141 subexpr_str.map(|s| format!("({})", s))
144 fn rewrite_struct_lit<'a>(context: &RewriteContext,
146 fields: &'a [ast::Field],
147 base: Option<&'a ast::Expr>,
152 debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
153 assert!(fields.len() > 0 || base.is_some());
155 enum StructLitField<'a> {
156 Regular(&'a ast::Field),
160 let path_str = pprust::path_to_string(path);
161 // Foo { a: Foo } - indent is +3, width is -5.
162 let indent = offset + path_str.len() + 3;
163 let budget = width - (path_str.len() + 5);
165 let field_iter = fields.into_iter().map(StructLitField::Regular)
166 .chain(base.into_iter().map(StructLitField::Base));
168 let items = itemize_list(context.codemap,
175 StructLitField::Regular(ref field) => field.span.lo,
177 StructLitField::Base(ref expr) => expr.span.lo - BytePos(2)
182 StructLitField::Regular(ref field) => field.span.hi,
183 StructLitField::Base(ref expr) => expr.span.hi
188 StructLitField::Regular(ref field) => {
189 rewrite_field(context, &field, budget, indent)
190 .unwrap_or(context.codemap.span_to_snippet(field.span)
193 StructLitField::Base(ref expr) => {
195 expr.rewrite(context, budget - 2, indent + 2)
196 .map(|s| format!("..{}", s))
197 .unwrap_or(context.codemap.span_to_snippet(expr.span)
202 span_after(span, "{", context.codemap),
205 let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
207 trailing_separator: if base.is_some() {
208 SeparatorTactic::Never
210 context.config.struct_lit_trailing_comma
215 ends_with_newline: true, };
216 let fields_str = write_list(&items, &fmt);
217 Some(format!("{} {{ {} }}", path_str, fields_str))
219 // FIXME if the usual multi-line layout is too wide, we should fall back to
225 fn rewrite_field(context: &RewriteContext,
230 let name = &token::get_ident(field.ident.node);
231 let overhead = name.len() + 2;
232 let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
233 expr.map(|s| format!("{}: {}", name, s))
236 fn rewrite_tuple_lit(context: &RewriteContext,
237 items: &[ptr::P<ast::Expr>],
242 debug!("rewrite_tuple_lit: width: {}, offset: {}", width, offset);
243 let indent = offset + 1;
244 // In case of length 1, need a trailing comma
245 if items.len() == 1 {
247 return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
250 let items = itemize_list(context.codemap,
257 |item| item.rewrite(context,
258 context.config.max_width - indent - 1,
260 .unwrap_or(context.codemap.span_to_snippet(item.span)
262 span.lo + BytePos(1), // Remove parens
263 span.hi - BytePos(1));
265 let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
267 trailing_separator: SeparatorTactic::Never,
271 ends_with_newline: true, };
273 Some(format!("({})", write_list(&items, &fmt)))
276 fn rewrite_binary_op(context: &RewriteContext,
283 // FIXME: format comments between operands and operator
285 let operator_str = context.codemap.span_to_snippet(op.span).unwrap();
287 // 1 = space between lhs expr and operator
289 try_opt!(lhs.rewrite(context, context.config.max_width - offset - 1 - operator_str.len(), offset));
292 result.push_str(&operator_str);
294 let remaining_width = match result.rfind('\n') {
295 Some(idx) => (offset + width + idx).checked_sub(result.len()).unwrap_or(0),
296 None => width.checked_sub(result.len()).unwrap_or(0)
299 // Get "full width" rhs and see if it fits on the current line. This
300 // usually works fairly well since it tends to place operands of
301 // operations with high precendence close together.
302 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
304 // Second condition is needed in case of line break not caused by a
305 // shortage of space, but by end-of-line comments, for example.
306 if rhs_result.len() > remaining_width || rhs_result.contains('\n') {
308 result.push_str(&make_indent(offset));
313 result.push_str(&rhs_result);
317 fn rewrite_unary_op(context: &RewriteContext,
323 // For some reason, an UnOp is not spanned like BinOp!
324 let operator_str = match *op {
325 ast::UnOp::UnUniq => "&",
326 ast::UnOp::UnDeref => "*",
327 ast::UnOp::UnNot => "!",
328 ast::UnOp::UnNeg => "-"
331 Some(format!("{}{}", operator_str, try_opt!(expr.rewrite(context, width - 1, offset))))