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 {
84 Some(rewrite_string(&s.escape_default(), &fmt))
87 fn rewrite_call(context: &RewriteContext,
89 args: &[ptr::P<ast::Expr>],
94 debug!("rewrite_call, width: {}, offset: {}", width, offset);
96 // TODO using byte lens instead of char lens (and probably all over the place too)
97 let callee_str = try_opt!(callee.rewrite(context, width, offset));
98 debug!("rewrite_call, callee_str: `{}`", callee_str);
101 return Some(format!("{}()", callee_str));
105 let remaining_width = width - callee_str.len() - 2;
106 let offset = callee_str.len() + 1 + offset;
108 let items = itemize_list(context.codemap,
115 // Take old span when rewrite fails.
116 |item| item.rewrite(context, remaining_width, offset)
117 .unwrap_or(context.codemap.span_to_snippet(item.span)
119 callee.span.hi + BytePos(1),
122 let fmt = ListFormatting {
123 tactic: ListTactic::HorizontalVertical,
125 trailing_separator: SeparatorTactic::Never,
127 h_width: remaining_width,
128 v_width: remaining_width,
129 ends_with_newline: true,
132 Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
135 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
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>,
153 debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
154 assert!(fields.len() > 0 || base.is_some());
156 enum StructLitField<'a> {
157 Regular(&'a ast::Field),
161 let path_str = pprust::path_to_string(path);
162 // Foo { a: Foo } - indent is +3, width is -5.
163 let indent = offset + path_str.len() + 3;
164 let budget = width - (path_str.len() + 5);
166 let field_iter = fields.into_iter().map(StructLitField::Regular)
167 .chain(base.into_iter().map(StructLitField::Base));
169 let items = itemize_list(context.codemap,
176 StructLitField::Regular(ref field) => field.span.lo,
178 StructLitField::Base(ref expr) => expr.span.lo - BytePos(2)
183 StructLitField::Regular(ref field) => field.span.hi,
184 StructLitField::Base(ref expr) => expr.span.hi
189 StructLitField::Regular(ref field) => {
190 rewrite_field(context, &field, budget, indent)
191 .unwrap_or(context.codemap.span_to_snippet(field.span)
194 StructLitField::Base(ref expr) => {
196 expr.rewrite(context, budget - 2, indent + 2)
197 .map(|s| format!("..{}", s))
198 .unwrap_or(context.codemap.span_to_snippet(expr.span)
203 span_after(span, "{", context.codemap),
206 let fmt = ListFormatting {
207 tactic: ListTactic::HorizontalVertical,
209 trailing_separator: if base.is_some() {
210 SeparatorTactic::Never
212 context.config.struct_lit_trailing_comma
217 ends_with_newline: true,
219 let fields_str = write_list(&items, &fmt);
220 Some(format!("{} {{ {} }}", path_str, fields_str))
222 // FIXME if the usual multi-line layout is too wide, we should fall back to
228 fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
229 let name = &token::get_ident(field.ident.node);
230 let overhead = name.len() + 2;
231 let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
232 expr.map(|s| format!("{}: {}", name, s))
235 fn rewrite_tuple_lit(context: &RewriteContext,
236 items: &[ptr::P<ast::Expr>],
241 let indent = offset + 1;
243 let items = itemize_list(context.codemap,
250 |item| item.rewrite(context,
251 context.config.max_width - indent - 2,
253 .unwrap_or(context.codemap.span_to_snippet(item.span)
255 span.lo + BytePos(1), // Remove parens
256 span.hi - BytePos(1));
258 // In case of length 1, need a trailing comma
259 let trailing_separator_tactic = if items.len() == 1 {
260 SeparatorTactic::Always
262 SeparatorTactic::Never
265 let fmt = ListFormatting {
266 tactic: ListTactic::HorizontalVertical,
268 trailing_separator: trailing_separator_tactic,
272 ends_with_newline: true,
275 Some(format!("({})", write_list(&items, &fmt)))
278 fn rewrite_binary_op(context: &RewriteContext,
285 // FIXME: format comments between operands and operator
287 let operator_str = context.codemap.span_to_snippet(op.span).unwrap();
289 // 1 = space between lhs expr and operator
290 let mut result = try_opt!(lhs.rewrite(context, width - 1 - operator_str.len(), offset));
293 result.push_str(&operator_str);
295 let remaining_width = match result.rfind('\n') {
296 Some(idx) => (context.config.max_width + idx).checked_sub(result.len()).unwrap_or(0),
297 None => width.checked_sub(result.len()).unwrap_or(0)
300 // Get "full width" rhs and see if it fits on the current line. This
301 // usually works fairly well since it tends to place operands of
302 // operations with high precendence close together.
303 let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
305 if rhs_result.len() > remaining_width {
307 result.push_str(&make_indent(offset));
312 result.push_str(&rhs_result);
316 fn rewrite_unary_op(context: &RewriteContext,
322 // For some reason, an UnOp is not spanned like BinOp!
323 let operator_str = match *op {
324 ast::UnOp::UnUniq => "&",
325 ast::UnOp::UnDeref => "*",
326 ast::UnOp::UnNot => "!",
327 ast::UnOp::UnNeg => "-"
330 Some(format!("{}{}", operator_str, try_opt!(expr.rewrite(context, width - 1, offset))))