1
Fork 0
rust/src/expr.rs

275 lines
11 KiB
Rust
Raw Normal View History

2015-04-21 21:01:19 +12:00
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2015-06-16 17:29:05 +02:00
use rewrite::{Rewrite, RewriteContext};
2015-06-24 01:11:29 +02:00
use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
2015-06-23 15:58:58 +02:00
use string::{StringFormat, rewrite_string};
2015-06-24 01:11:29 +02:00
use utils::span_after;
2015-04-21 21:01:19 +12:00
use syntax::{ast, ptr};
2015-06-23 15:58:58 +02:00
use syntax::codemap::{Pos, Span, BytePos};
2015-05-25 19:11:53 +12:00
use syntax::parse::token;
use syntax::print::pprust;
2015-04-21 21:01:19 +12:00
2015-06-16 17:29:05 +02:00
impl Rewrite for ast::Expr {
fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
match self.node {
ast::Expr_::ExprLit(ref l) => {
match l.node {
ast::Lit_::LitStr(ref is, _) => {
let result = rewrite_string_lit(context, &is, l.span, width, offset);
debug!("string lit: `{:?}`", result);
return result;
}
_ => {}
}
}
ast::Expr_::ExprCall(ref callee, ref args) => {
2015-06-23 15:58:58 +02:00
return rewrite_call(context, callee, args, self.span, width, offset);
2015-06-16 17:29:05 +02:00
}
ast::Expr_::ExprParen(ref subexpr) => {
return rewrite_paren(context, subexpr, width, offset);
}
ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
2015-06-24 01:11:29 +02:00
return rewrite_struct_lit(context,
path,
fields,
base.as_ref().map(|e| &**e),
self.span,
width,
offset);
2015-06-16 17:29:05 +02:00
}
ast::Expr_::ExprTup(ref items) => {
2015-06-23 15:58:58 +02:00
return rewrite_tuple_lit(context, items, self.span, width, offset);
2015-06-16 17:29:05 +02:00
}
_ => {}
2015-04-21 21:01:19 +12:00
}
2015-06-16 17:29:05 +02:00
context.codemap.span_to_snippet(self.span).ok()
}
}
2015-04-21 21:01:19 +12:00
2015-06-23 15:58:58 +02:00
fn rewrite_string_lit(context: &RewriteContext,
s: &str,
span: Span,
width: usize,
offset: usize)
-> Option<String> {
2015-06-16 17:29:05 +02:00
// Check if there is anything to fix: we always try to fixup multi-line
// strings, or if the string is too long for the line.
let l_loc = context.codemap.lookup_char_pos(span.lo);
let r_loc = context.codemap.lookup_char_pos(span.hi);
if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
2015-06-16 17:29:05 +02:00
return context.codemap.span_to_snippet(span).ok();
}
2015-06-23 15:58:58 +02:00
let fmt = StringFormat {
opener: "\"",
closer: "\"",
line_start: " ",
line_end: "\\",
width: width,
offset: offset,
trim_end: false
};
2015-04-21 21:01:19 +12:00
2015-06-23 15:58:58 +02:00
Some(rewrite_string(&s.escape_default(), &fmt))
2015-06-16 17:29:05 +02:00
}
fn rewrite_call(context: &RewriteContext,
callee: &ast::Expr,
args: &[ptr::P<ast::Expr>],
2015-06-23 15:58:58 +02:00
span: Span,
width: usize,
offset: usize)
2015-06-23 15:58:58 +02:00
-> Option<String> {
2015-06-16 17:29:05 +02:00
debug!("rewrite_call, width: {}, offset: {}", width, offset);
2015-04-21 21:01:19 +12:00
2015-06-16 17:29:05 +02:00
// TODO using byte lens instead of char lens (and probably all over the place too)
let callee_str = try_opt!(callee.rewrite(context, width, offset));
2015-06-23 15:58:58 +02:00
debug!("rewrite_call, callee_str: `{}`", callee_str);
if args.len() == 0 {
return Some(format!("{}()", callee_str));
}
2015-06-16 17:29:05 +02:00
// 2 is for parens.
let remaining_width = width - callee_str.len() - 2;
let offset = callee_str.len() + 1 + offset;
2015-04-21 21:01:19 +12:00
2015-06-23 15:58:58 +02:00
let items = itemize_list(context.codemap,
Vec::new(),
args.iter(),
",",
")",
|item| item.span.lo,
|item| item.span.hi,
2015-06-24 01:11:29 +02:00
// Take old span when rewrite fails.
2015-06-23 15:58:58 +02:00
|item| item.rewrite(context, remaining_width, offset)
2015-06-24 01:11:29 +02:00
.unwrap_or(context.codemap.span_to_snippet(item.span)
.unwrap()),
2015-06-23 15:58:58 +02:00
callee.span.hi + BytePos(1),
span.hi);
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
2015-06-24 21:14:08 +02:00
ends_with_newline: true,
2015-06-16 17:29:05 +02:00
};
2015-04-21 21:01:19 +12:00
2015-06-23 15:58:58 +02:00
Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
2015-06-16 17:29:05 +02:00
}
2015-04-21 21:01:19 +12:00
2015-06-16 17:29:05 +02:00
fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
debug!("rewrite_paren, width: {}, offset: {}", width, offset);
// 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
// paren on the same line as the subexpr
let subexpr_str = subexpr.rewrite(context, width-2, offset+1);
debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
subexpr_str.map(|s| format!("({})", s))
}
2015-05-24 19:57:13 +02:00
2015-06-24 01:11:29 +02:00
fn rewrite_struct_lit<'a>(context: &RewriteContext,
path: &ast::Path,
fields: &'a [ast::Field],
base: Option<&'a ast::Expr>,
span: Span,
width: usize,
offset: usize)
2015-06-16 17:29:05 +02:00
-> Option<String>
{
debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
assert!(fields.len() > 0 || base.is_some());
2015-05-25 19:11:53 +12:00
2015-06-24 01:11:29 +02:00
enum StructLitField<'a> {
Regular(&'a ast::Field),
Base(&'a ast::Expr)
}
2015-06-16 17:29:05 +02:00
let path_str = pprust::path_to_string(path);
// Foo { a: Foo } - indent is +3, width is -5.
let indent = offset + path_str.len() + 3;
let budget = width - (path_str.len() + 5);
2015-05-25 19:11:53 +12:00
2015-06-24 01:11:29 +02:00
let field_iter = fields.into_iter().map(StructLitField::Regular)
.chain(base.into_iter().map(StructLitField::Base));
let items = itemize_list(context.codemap,
Vec::new(),
field_iter,
",",
"}",
|item| {
match *item {
StructLitField::Regular(ref field) => field.span.lo,
// 2 = ..
StructLitField::Base(ref expr) => expr.span.lo - BytePos(2)
}
},
|item| {
match *item {
StructLitField::Regular(ref field) => field.span.hi,
StructLitField::Base(ref expr) => expr.span.hi
}
},
|item| {
match *item {
StructLitField::Regular(ref field) => {
rewrite_field(context, &field, budget, indent)
.unwrap_or(context.codemap.span_to_snippet(field.span)
.unwrap())
},
StructLitField::Base(ref expr) => {
// 2 = ..
expr.rewrite(context, budget - 2, indent + 2)
.map(|s| format!("..{}", s))
.unwrap_or(context.codemap.span_to_snippet(expr.span)
.unwrap())
}
}
},
span_after(span, "{", context.codemap),
span.hi);
2015-06-16 17:29:05 +02:00
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: if base.is_some() {
SeparatorTactic::Never
} else {
context.config.struct_lit_trailing_comma
2015-06-16 17:29:05 +02:00
},
indent: indent,
h_width: budget,
v_width: budget,
2015-06-24 21:14:08 +02:00
ends_with_newline: true,
2015-06-16 17:29:05 +02:00
};
2015-06-24 01:11:29 +02:00
let fields_str = write_list(&items, &fmt);
2015-06-16 17:29:05 +02:00
Some(format!("{} {{ {} }}", path_str, fields_str))
2015-05-25 19:11:53 +12:00
2015-06-23 15:58:58 +02:00
// FIXME if the usual multi-line layout is too wide, we should fall back to
// Foo {
// a: ...,
// }
2015-06-16 17:29:05 +02:00
}
2015-05-25 19:11:53 +12:00
2015-06-16 17:29:05 +02:00
fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
let name = &token::get_ident(field.ident.node);
let overhead = name.len() + 2;
let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
expr.map(|s| format!("{}: {}", name, s))
}
2015-05-25 19:11:53 +12:00
fn rewrite_tuple_lit(context: &RewriteContext,
items: &[ptr::P<ast::Expr>],
2015-06-23 15:58:58 +02:00
span: Span,
width: usize,
offset: usize)
2015-06-16 17:29:05 +02:00
-> Option<String> {
2015-06-23 15:58:58 +02:00
let indent = offset + 1;
let items = itemize_list(context.codemap,
Vec::new(),
items.into_iter(),
",",
")",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context,
context.config.max_width - indent - 2,
indent)
2015-06-24 01:11:29 +02:00
.unwrap_or(context.codemap.span_to_snippet(item.span)
.unwrap()),
2015-06-23 15:58:58 +02:00
span.lo + BytePos(1), // Remove parens
span.hi - BytePos(1));
// In case of length 1, need a trailing comma
let trailing_separator_tactic = if items.len() == 1 {
SeparatorTactic::Always
} else {
SeparatorTactic::Never
};
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: trailing_separator_tactic,
indent: indent,
h_width: width - 2,
v_width: width - 2,
2015-06-24 21:14:08 +02:00
ends_with_newline: true,
2015-06-23 15:58:58 +02:00
};
Some(format!("({})", write_list(&items, &fmt)))
}