Merge pull request #3067 from topecongiro/refactor-toexpr

Add println!-like heuristic to the fail attribute
This commit is contained in:
Nick Cameron 2018-10-08 12:38:33 +13:00 committed by GitHub
commit d0c6a6d642
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 371 additions and 335 deletions

View File

@ -35,20 +35,12 @@ matrix:
- env: INTEGRATION=stdsimd
- env: INTEGRATION=tempdir
allow_failures:
# Needs `edition = "2018"` in rustfmt.toml
- env: INTEGRATION=chalk
# Fails tests, don't know why
- env: INTEGRATION=crater
# Doesn't build
- env: INTEGRATION=futures-rs
# Doesn't build - seems to be because of an option
- env: INTEGRATION=packed_simd
# Weird bug I can't reproduce: #2969
- env: INTEGRATION=rand
# Test failure
- env: INTEGRATION=rust-clippy
# Build failure
- env: INTEGRATION=rust-semverver
script:
- |

View File

@ -15,12 +15,12 @@ use config::lists::*;
use config::IndentStyle;
use expr::rewrite_literal;
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
use overflow;
use rewrite::{Rewrite, RewriteContext};
use shape::Shape;
use types::{rewrite_path, PathContext};
use utils::{count_newlines, mk_sp};
use std::borrow::Cow;
use syntax::ast;
use syntax::source_map::{BytePos, Span, DUMMY_SP};
@ -216,56 +216,21 @@ impl Rewrite for ast::MetaItem {
}
ast::MetaItemKind::List(ref list) => {
let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
let has_comma = ::expr::span_ends_with_comma(context, self.span);
let trailing_comma = if has_comma { "," } else { "" };
let combine = list.len() == 1 && match list[0].node {
ast::NestedMetaItemKind::Literal(..) => false,
ast::NestedMetaItemKind::MetaItem(ref inner_meta_item) => {
match inner_meta_item.node {
ast::MetaItemKind::List(..) => rewrite_path(
context,
PathContext::Type,
None,
&inner_meta_item.ident,
shape,
)
.map_or(false, |s| s.len() + path.len() + 2 <= shape.width),
_ => false,
}
}
};
let argument_shape = argument_shape(
path.len() + 1,
2 + trailing_comma.len(),
combine,
shape,
let has_trailing_comma = ::expr::span_ends_with_comma(context, self.span);
overflow::rewrite_with_parens(
context,
)?;
let item_str = format_arg_list(
&path,
list.iter(),
|nested_meta_item| nested_meta_item.span.lo(),
|nested_meta_item| nested_meta_item.span.hi(),
|nested_meta_item| nested_meta_item.rewrite(context, argument_shape),
// 1 = "]"
shape.sub_width(1)?,
self.span,
context,
argument_shape,
// 3 = "()" and "]"
shape
.offset_left(path.len())?
.sub_width(3 + trailing_comma.len())?,
Some(context.config.width_heuristics().fn_call_width),
combine,
)?;
let indent = if item_str.starts_with('\n') {
shape.indent.to_string_with_newline(context.config)
} else {
Cow::Borrowed("")
};
format!("{}({}{}{})", path, item_str, trailing_comma, indent)
context.config.width_heuristics().fn_call_width,
Some(if has_trailing_comma {
SeparatorTactic::Always
} else {
SeparatorTactic::Never
}),
)?
}
ast::MetaItemKind::NameValue(ref literal) => {
let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;

View File

@ -13,9 +13,10 @@ use syntax::parse::classify;
use syntax::source_map::Span;
use syntax::{ast, ptr};
use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond, ToExpr};
use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
use items::{span_hi_for_arg, span_lo_for_arg};
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
use overflow::OverflowableItem;
use rewrite::{Rewrite, RewriteContext};
use shape::Shape;
use source_map::SpanUtils;
@ -358,18 +359,12 @@ pub fn rewrite_last_closure(
}
/// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
pub fn args_have_many_closure<T>(args: &[&T]) -> bool
where
T: ToExpr,
{
pub fn args_have_many_closure(args: &[OverflowableItem]) -> bool {
args.iter()
.filter(|arg| {
arg.to_expr()
.map(|e| match e.node {
ast::ExprKind::Closure(..) => true,
_ => false,
})
.unwrap_or(false)
.filter_map(|arg| arg.to_expr())
.filter(|expr| match expr.node {
ast::ExprKind::Closure(..) => true,
_ => false,
})
.count()
> 1

View File

@ -27,17 +27,17 @@ use lists::{
definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
};
use macros::{rewrite_macro, MacroArg, MacroPosition};
use macros::{rewrite_macro, MacroPosition};
use matches::rewrite_match;
use overflow;
use overflow::{self, IntoOverflowableItem, OverflowableItem};
use pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
use patterns::{can_be_overflowed_pat, is_short_pattern, TuplePatField};
use patterns::is_short_pattern;
use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape};
use source_map::{LineRangeUtils, SpanUtils};
use spanned::Spanned;
use string::{rewrite_string, StringFormat};
use types::{can_be_overflowed_type, rewrite_path, PathContext};
use types::{rewrite_path, PathContext};
use utils::{
colon_spaces, contains_skip, count_newlines, first_line_ends_with, first_line_width,
inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
@ -73,7 +73,7 @@ pub fn format_expr(
let expr_rw = match expr.node {
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
"",
&ptr_vec_to_ref_vec(expr_vec),
expr_vec.iter(),
expr.span,
context,
shape,
@ -110,7 +110,7 @@ pub fn format_expr(
shape,
),
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, &ptr_vec_to_ref_vec(items), expr.span, shape)
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
}
ast::ExprKind::If(..)
| ast::ExprKind::IfLet(..)
@ -391,11 +391,11 @@ pub fn format_expr(
})
}
pub fn rewrite_array<T: Rewrite + Spanned + ToExpr>(
name: &str,
exprs: &[&T],
pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
name: &'a str,
exprs: impl Iterator<Item = &'a T>,
span: Span,
context: &RewriteContext,
context: &'a RewriteContext,
shape: Shape,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<DelimToken>,
@ -1259,54 +1259,6 @@ fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Opt
)
}
/// In case special-case style is required, returns an offset from which we start horizontal layout.
pub fn maybe_get_args_offset<T: ToExpr>(callee_str: &str, args: &[&T]) -> Option<(bool, usize)> {
if let Some(&(_, num_args_before)) = SPECIAL_MACRO_WHITELIST
.iter()
.find(|&&(s, _)| s == callee_str)
{
let all_simple = args.len() > num_args_before && is_every_expr_simple(args);
Some((all_simple, num_args_before))
} else {
None
}
}
/// A list of `format!`-like macros, that take a long format string and a list of arguments to
/// format.
///
/// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
/// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
/// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
// format! like macros
// From the Rust Standard Library.
("eprint!", 0),
("eprintln!", 0),
("format!", 0),
("format_args!", 0),
("print!", 0),
("println!", 0),
("panic!", 0),
("unreachable!", 0),
// From the `log` crate.
("debug!", 0),
("error!", 0),
("info!", 0),
("warn!", 0),
// write! like macros
("assert!", 1),
("debug_assert!", 1),
("write!", 1),
("writeln!", 1),
// assert_eq! like macros
("assert_eq!", 2),
("assert_ne!", 2),
("debug_assert_eq!", 2),
("debug_assert_ne!", 2),
];
fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<SeparatorTactic> {
if context.inside_macro() {
if span_ends_with_comma(context, span) {
@ -1329,7 +1281,7 @@ pub fn rewrite_call(
overflow::rewrite_with_parens(
context,
callee,
&ptr_vec_to_ref_vec(args),
args.iter(),
shape,
span,
context.config.width_heuristics().fn_call_width,
@ -1337,7 +1289,7 @@ pub fn rewrite_call(
)
}
fn is_simple_expr(expr: &ast::Expr) -> bool {
pub fn is_simple_expr(expr: &ast::Expr) -> bool {
match expr.node {
ast::ExprKind::Lit(..) => true,
ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
@ -1355,10 +1307,8 @@ fn is_simple_expr(expr: &ast::Expr) -> bool {
}
}
pub fn is_every_expr_simple<T: ToExpr>(lists: &[&T]) -> bool {
lists
.iter()
.all(|arg| arg.to_expr().map_or(false, is_simple_expr))
pub fn is_every_expr_simple(lists: &[OverflowableItem]) -> bool {
lists.iter().all(OverflowableItem::is_simple)
}
pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
@ -1720,19 +1670,16 @@ pub fn rewrite_field(
}
}
fn rewrite_tuple_in_visual_indent_style<'a, T>(
fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &RewriteContext,
items: &[&T],
mut items: impl Iterator<Item = &'a T>,
span: Span,
shape: Shape,
) -> Option<String>
where
T: Rewrite + Spanned + ToExpr + 'a,
{
let mut items = items.iter();
is_singleton_tuple: bool,
) -> Option<String> {
// In case of length 1, need a trailing comma
debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
if items.len() == 1 {
if is_singleton_tuple {
// 3 = "(" + ",)"
let nested_shape = shape.sub_width(3)?.visual_indent(1);
return items
@ -1771,15 +1718,13 @@ where
Some(format!("({})", list_str))
}
pub fn rewrite_tuple<'a, T>(
context: &RewriteContext,
items: &[&T],
pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext,
items: impl Iterator<Item = &'a T>,
span: Span,
shape: Shape,
) -> Option<String>
where
T: Rewrite + Spanned + ToExpr + 'a,
{
is_singleton_tuple: bool,
) -> Option<String> {
debug!("rewrite_tuple {:?}", shape);
if context.use_block_indent() {
// We use the same rule as function calls for rewriting tuples.
@ -1789,7 +1734,7 @@ where
} else {
Some(SeparatorTactic::Never)
}
} else if items.len() == 1 {
} else if is_singleton_tuple {
Some(SeparatorTactic::Always)
} else {
None
@ -1804,7 +1749,7 @@ where
force_tactic,
)
} else {
rewrite_tuple_in_visual_indent_style(context, items, span, shape)
rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
}
}
@ -1995,79 +1940,6 @@ fn rewrite_expr_addrof(
rewrite_unary_prefix(context, operator_str, expr, shape)
}
pub trait ToExpr {
fn to_expr(&self) -> Option<&ast::Expr>;
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
}
impl ToExpr for ast::Expr {
fn to_expr(&self) -> Option<&ast::Expr> {
Some(self)
}
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
can_be_overflowed_expr(context, self, len)
}
}
impl ToExpr for ast::Ty {
fn to_expr(&self) -> Option<&ast::Expr> {
None
}
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
can_be_overflowed_type(context, self, len)
}
}
impl<'a> ToExpr for TuplePatField<'a> {
fn to_expr(&self) -> Option<&ast::Expr> {
None
}
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
can_be_overflowed_pat(context, self, len)
}
}
impl<'a> ToExpr for ast::StructField {
fn to_expr(&self) -> Option<&ast::Expr> {
None
}
fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
false
}
}
impl<'a> ToExpr for MacroArg {
fn to_expr(&self) -> Option<&ast::Expr> {
match *self {
MacroArg::Expr(ref expr) => Some(expr),
_ => None,
}
}
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
match *self {
MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
MacroArg::Pat(..) => false,
MacroArg::Item(..) => len == 1,
}
}
}
impl ToExpr for ast::GenericParam {
fn to_expr(&self) -> Option<&ast::Expr> {
None
}
fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
false
}
}
pub fn is_method_call(expr: &ast::Expr) -> bool {
match expr.node {
ast::ExprKind::MethodCall(..) => true,

View File

@ -1391,11 +1391,10 @@ fn format_tuple_struct(
format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
} else {
let shape = Shape::indented(offset, context.config).sub_width(1)?;
let fields = &fields.iter().collect::<Vec<_>>();
result = overflow::rewrite_with_parens(
context,
&result,
fields,
fields.iter(),
shape,
span,
context.config.width_heuristics().fn_call_width,
@ -2492,7 +2491,7 @@ fn rewrite_generics(
return Some(ident.to_owned());
}
let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>();
let params = generics.params.iter();
overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
}

View File

@ -100,8 +100,7 @@ pub enum ErrorKind {
#[fail(
display = "line formatted, but exceeded maximum width \
(maximum: {} (see `max_width` option), found: {})",
_0,
_1
_0, _1
)]
LineOverflow(usize, usize),
/// Line ends in whitespace.

View File

@ -278,7 +278,7 @@ pub fn rewrite_macro_inner(
overflow::rewrite_with_parens(
context,
&macro_name,
&arg_vec.iter().map(|e| &*e).collect::<Vec<_>>(),
arg_vec.iter(),
shape,
mac.span,
context.config.width_heuristics().fn_call_width,
@ -334,11 +334,9 @@ pub fn rewrite_macro_inner(
force_trailing_comma = Some(SeparatorTactic::Vertical);
};
}
// Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>();
let rewrite = rewrite_array(
macro_name,
arg_vec,
arg_vec.iter(),
mac.span,
context,
shape,

View File

@ -9,38 +9,248 @@
// except according to those terms.
//! Rewrite a list some items with overflow.
// FIXME: Replace `ToExpr` with some enum.
use config::lists::*;
use syntax::ast;
use syntax::parse::token::DelimToken;
use syntax::source_map::Span;
use syntax::{ast, ptr};
use closures;
use expr::{is_every_expr_simple, is_method_call, is_nested_call, maybe_get_args_offset, ToExpr};
use expr::{
can_be_overflowed_expr, is_every_expr_simple, is_method_call, is_nested_call, is_simple_expr,
};
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
use macros::MacroArg;
use patterns::{can_be_overflowed_pat, TuplePatField};
use rewrite::{Rewrite, RewriteContext};
use shape::Shape;
use source_map::SpanUtils;
use spanned::Spanned;
use types::{can_be_overflowed_type, SegmentParam};
use utils::{count_newlines, extra_offset, first_line_width, last_line_width, mk_sp};
use std::cmp::min;
const SHORT_ITEM_THRESHOLD: usize = 10;
pub fn rewrite_with_parens<T>(
context: &RewriteContext,
ident: &str,
items: &[&T],
/// A list of `format!`-like macros, that take a long format string and a list of arguments to
/// format.
///
/// Organized as a list of `(&str, usize)` tuples, giving the name of the macro and the number of
/// arguments before the format string (none for `format!("format", ...)`, one for `assert!(result,
/// "format", ...)`, two for `assert_eq!(left, right, "format", ...)`).
const SPECIAL_MACRO_WHITELIST: &[(&str, usize)] = &[
// format! like macros
// From the Rust Standard Library.
("eprint!", 0),
("eprintln!", 0),
("format!", 0),
("format_args!", 0),
("print!", 0),
("println!", 0),
("panic!", 0),
("unreachable!", 0),
// From the `log` crate.
("debug!", 0),
("error!", 0),
("info!", 0),
("warn!", 0),
// write! like macros
("assert!", 1),
("debug_assert!", 1),
("write!", 1),
("writeln!", 1),
// assert_eq! like macros
("assert_eq!", 2),
("assert_ne!", 2),
("debug_assert_eq!", 2),
("debug_assert_ne!", 2),
];
const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[
// From the `failure` crate.
("fail", 0),
];
#[derive(Debug)]
pub enum OverflowableItem<'a> {
Expr(&'a ast::Expr),
GenericParam(&'a ast::GenericParam),
MacroArg(&'a MacroArg),
NestedMetaItem(&'a ast::NestedMetaItem),
SegmentParam(&'a SegmentParam<'a>),
StructField(&'a ast::StructField),
TuplePatField(&'a TuplePatField<'a>),
Ty(&'a ast::Ty),
}
impl<'a> Rewrite for OverflowableItem<'a> {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
self.map(|item| item.rewrite(context, shape))
}
}
impl<'a> Spanned for OverflowableItem<'a> {
fn span(&self) -> Span {
self.map(|item| item.span())
}
}
impl<'a> OverflowableItem<'a> {
pub fn map<F, T>(&self, f: F) -> T
where
F: Fn(&IntoOverflowableItem<'a>) -> T,
{
match self {
OverflowableItem::Expr(expr) => f(*expr),
OverflowableItem::GenericParam(gp) => f(*gp),
OverflowableItem::MacroArg(macro_arg) => f(*macro_arg),
OverflowableItem::NestedMetaItem(nmi) => f(*nmi),
OverflowableItem::SegmentParam(sp) => f(*sp),
OverflowableItem::StructField(sf) => f(*sf),
OverflowableItem::TuplePatField(pat) => f(*pat),
OverflowableItem::Ty(ty) => f(*ty),
}
}
pub fn is_simple(&self) -> bool {
match self {
OverflowableItem::Expr(expr) => is_simple_expr(expr),
OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr),
OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item.node {
ast::NestedMetaItemKind::Literal(..) => true,
ast::NestedMetaItemKind::MetaItem(ref meta_item) => match meta_item.node {
ast::MetaItemKind::Word => true,
_ => false,
},
},
_ => false,
}
}
pub fn is_expr(&self) -> bool {
match self {
OverflowableItem::Expr(..) => true,
OverflowableItem::MacroArg(MacroArg::Expr(..)) => true,
_ => false,
}
}
pub fn is_nested_call(&self) -> bool {
match self {
OverflowableItem::Expr(expr) => is_nested_call(expr),
OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr),
_ => false,
}
}
pub fn to_expr(&self) -> Option<&'a ast::Expr> {
match self {
OverflowableItem::Expr(expr) => Some(expr),
OverflowableItem::MacroArg(macro_arg) => match macro_arg {
MacroArg::Expr(ref expr) => Some(expr),
_ => None,
},
_ => None,
}
}
pub fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
match self {
OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len),
OverflowableItem::MacroArg(macro_arg) => match macro_arg {
MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
MacroArg::Pat(..) => false,
MacroArg::Item(..) => len == 1,
},
OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => {
match nested_meta_item.node {
ast::NestedMetaItemKind::Literal(..) => false,
ast::NestedMetaItemKind::MetaItem(..) => true,
}
}
OverflowableItem::SegmentParam(seg) => match seg {
SegmentParam::Type(ty) => can_be_overflowed_type(context, ty, len),
_ => false,
},
OverflowableItem::TuplePatField(pat) => can_be_overflowed_pat(context, pat, len),
OverflowableItem::Ty(ty) => can_be_overflowed_type(context, ty, len),
_ => false,
}
}
fn whitelist(&self) -> &'static [(&'static str, usize)] {
match self {
OverflowableItem::MacroArg(..) => SPECIAL_MACRO_WHITELIST,
OverflowableItem::NestedMetaItem(..) => SPECIAL_ATTR_WHITELIST,
_ => &[],
}
}
}
pub trait IntoOverflowableItem<'a>: Rewrite + Spanned {
fn into_overflowable_item(&'a self) -> OverflowableItem<'a>;
}
impl<'a, T: 'a + IntoOverflowableItem<'a>> IntoOverflowableItem<'a> for ptr::P<T> {
fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
(**self).into_overflowable_item()
}
}
macro impl_into_overflowable_item_for_ast_node {
($($ast_node:ident),*) => {
$(
impl<'a> IntoOverflowableItem<'a> for ast::$ast_node {
fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
OverflowableItem::$ast_node(self)
}
}
)*
}
}
macro impl_into_overflowable_item_for_rustfmt_types {
([$($ty:ident),*], [$($ty_with_lifetime:ident),*]) => {
$(
impl<'a> IntoOverflowableItem<'a> for $ty {
fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
OverflowableItem::$ty(self)
}
}
)*
$(
impl<'a> IntoOverflowableItem<'a> for $ty_with_lifetime<'a> {
fn into_overflowable_item(&'a self) -> OverflowableItem<'a> {
OverflowableItem::$ty_with_lifetime(self)
}
}
)*
}
}
impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty);
impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]);
pub fn into_overflowable_list<'a, T>(
iter: impl Iterator<Item = &'a T>,
) -> impl Iterator<Item = OverflowableItem<'a>>
where
T: 'a + IntoOverflowableItem<'a>,
{
iter.map(|x| IntoOverflowableItem::into_overflowable_item(x))
}
pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext,
ident: &'a str,
items: impl Iterator<Item = &'a T>,
shape: Shape,
span: Span,
item_max_width: usize,
force_separator_tactic: Option<SeparatorTactic>,
) -> Option<String>
where
T: Rewrite + ToExpr + Spanned,
{
) -> Option<String> {
Context::new(
context,
items,
@ -56,16 +266,13 @@ where
.rewrite(shape)
}
pub fn rewrite_with_angle_brackets<T>(
context: &RewriteContext,
ident: &str,
items: &[&T],
pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext,
ident: &'a str,
items: impl Iterator<Item = &'a T>,
shape: Shape,
span: Span,
) -> Option<String>
where
T: Rewrite + ToExpr + Spanned,
{
) -> Option<String> {
Context::new(
context,
items,
@ -81,18 +288,15 @@ where
.rewrite(shape)
}
pub fn rewrite_with_square_brackets<T>(
context: &RewriteContext,
name: &str,
items: &[&T],
pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext,
name: &'a str,
items: impl Iterator<Item = &'a T>,
shape: Shape,
span: Span,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<DelimToken>,
) -> Option<String>
where
T: Rewrite + ToExpr + Spanned,
{
) -> Option<String> {
let (lhs, rhs) = match delim_token {
Some(DelimToken::Paren) => ("(", ")"),
Some(DelimToken::Brace) => ("{", "}"),
@ -113,9 +317,9 @@ where
.rewrite(shape)
}
struct Context<'a, T: 'a> {
struct Context<'a> {
context: &'a RewriteContext<'a>,
items: &'a [&'a T],
items: Vec<OverflowableItem<'a>>,
ident: &'a str,
prefix: &'static str,
suffix: &'static str,
@ -128,10 +332,10 @@ struct Context<'a, T: 'a> {
custom_delims: Option<(&'a str, &'a str)>,
}
impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
pub fn new(
impl<'a> Context<'a> {
pub fn new<T: 'a + IntoOverflowableItem<'a>>(
context: &'a RewriteContext,
items: &'a [&'a T],
items: impl Iterator<Item = &'a T>,
ident: &'a str,
shape: Shape,
span: Span,
@ -140,7 +344,7 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
item_max_width: usize,
force_separator_tactic: Option<SeparatorTactic>,
custom_delims: Option<(&'a str, &'a str)>,
) -> Context<'a, T> {
) -> Context<'a> {
let used_width = extra_offset(ident, shape);
// 1 = `()`
let one_line_width = shape.width.saturating_sub(used_width + 2);
@ -153,7 +357,7 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
let nested_shape = shape_from_indent_style(context, shape, used_width + 2, used_width + 1);
Context {
context,
items,
items: into_overflowable_list(items).collect(),
ident,
one_line_shape,
nested_shape,
@ -167,7 +371,7 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
}
}
fn last_item(&self) -> Option<&&T> {
fn last_item(&self) -> Option<&OverflowableItem> {
self.items.last()
}
@ -185,23 +389,24 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
shape: Shape,
) -> Option<String> {
let last_item = self.last_item()?;
let rewrite = if let Some(expr) = last_item.to_expr() {
match expr.node {
// When overflowing the closure which consists of a single control flow expression,
// force to use block if its condition uses multi line.
ast::ExprKind::Closure(..) => {
// If the argument consists of multiple closures, we do not overflow
// the last closure.
if closures::args_have_many_closure(self.items) {
None
} else {
closures::rewrite_last_closure(self.context, expr, shape)
let rewrite = match last_item {
OverflowableItem::Expr(ref expr) => {
match expr.node {
// When overflowing the closure which consists of a single control flow
// expression, force to use block if its condition uses multi line.
ast::ExprKind::Closure(..) => {
// If the argument consists of multiple closures, we do not overflow
// the last closure.
if closures::args_have_many_closure(&self.items) {
None
} else {
closures::rewrite_last_closure(self.context, expr, shape)
}
}
_ => expr.rewrite(self.context, shape),
}
_ => expr.rewrite(self.context, shape),
}
} else {
last_item.rewrite(self.context, shape)
item @ _ => item.rewrite(self.context, shape),
};
if let Some(rewrite) = rewrite {
@ -225,23 +430,24 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
fn try_overflow_last_item(&self, list_items: &mut Vec<ListItem>) -> DefinitiveListTactic {
// 1 = "("
let combine_arg_with_callee = self.items.len() == 1
&& self.items[0].to_expr().is_some()
&& self.items[0].is_expr()
&& self.ident.len() < self.context.config.tab_spaces();
let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, self.items);
let overflow_last = combine_arg_with_callee || can_be_overflowed(self.context, &self.items);
// Replace the last item with its first line to see if it fits with
// first arguments.
let placeholder = if overflow_last {
let old_value = *self.context.force_one_line_chain.borrow();
if !combine_arg_with_callee {
if let Some(ref expr) = self.last_item().and_then(|item| item.to_expr()) {
if is_method_call(expr) {
self.context.force_one_line_chain.replace(true);
}
match self.last_item() {
Some(OverflowableItem::Expr(expr))
if !combine_arg_with_callee && is_method_call(expr) =>
{
self.context.force_one_line_chain.replace(true);
}
_ => (),
}
let result = last_item_shape(
self.items,
&self.items,
list_items,
self.one_line_shape,
self.item_max_width,
@ -316,7 +522,7 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
if tactic == DefinitiveListTactic::Vertical {
if let Some((all_simple, num_args_before)) =
maybe_get_args_offset(self.ident, self.items)
maybe_get_args_offset(self.ident, &self.items)
{
let one_line = all_simple
&& definitive_tactic(
@ -335,7 +541,7 @@ impl<'a, T: 'a + Rewrite + ToExpr + Spanned> Context<'a, T> {
if one_line {
tactic = DefinitiveListTactic::SpecialMacro(num_args_before);
};
} else if is_every_expr_simple(self.items) && no_long_items(list_items) {
} else if is_every_expr_simple(&self.items) && no_long_items(list_items) {
tactic = DefinitiveListTactic::Mixed;
}
}
@ -465,31 +671,20 @@ fn need_block_indent(s: &str, shape: Shape) -> bool {
})
}
fn can_be_overflowed<'a, T>(context: &RewriteContext, items: &[&T]) -> bool
where
T: Rewrite + Spanned + ToExpr + 'a,
{
fn can_be_overflowed<'a>(context: &RewriteContext, items: &[OverflowableItem]) -> bool {
items
.last()
.map_or(false, |x| x.can_be_overflowed(context, items.len()))
}
/// Returns a shape for the last argument which is going to be overflowed.
fn last_item_shape<T>(
lists: &[&T],
fn last_item_shape(
lists: &[OverflowableItem],
items: &[ListItem],
shape: Shape,
args_max_width: usize,
) -> Option<Shape>
where
T: Rewrite + Spanned + ToExpr,
{
let is_nested_call = lists
.iter()
.next()
.and_then(|item| item.to_expr())
.map_or(false, is_nested_call);
if items.len() == 1 && !is_nested_call {
) -> Option<Shape> {
if items.len() == 1 && !lists.get(0)?.is_nested_call() {
return Some(shape);
}
let offset = items.iter().rev().skip(1).fold(0, |acc, i| {
@ -528,3 +723,21 @@ fn no_long_items(list: &[ListItem]) -> bool {
list.iter()
.all(|item| item.inner_as_ref().len() <= SHORT_ITEM_THRESHOLD)
}
/// In case special-case style is required, returns an offset from which we start horizontal layout.
pub fn maybe_get_args_offset(callee_str: &str, args: &[OverflowableItem]) -> Option<(bool, usize)> {
if let Some(&(_, num_args_before)) = args
.get(0)?
.whitelist()
.iter()
.find(|&&(s, _)| s == callee_str)
{
let all_simple = args.len() > num_args_before
&& is_every_expr_simple(&args[0..num_args_before])
&& is_every_expr_simple(&args[num_args_before + 1..]);
Some((all_simple, num_args_before))
} else {
None
}
}

View File

@ -264,6 +264,7 @@ impl Rewrite for FieldPat {
}
}
#[derive(Debug)]
pub enum TuplePatField<'a> {
Pat(&'a ptr::P<ast::Pat>),
Dotdot(Span),
@ -359,12 +360,11 @@ fn rewrite_tuple_pat(
// add comma if `(x,)`
let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none() && !condensed;
let path_str = path_str.unwrap_or_default();
let pat_ref_vec = pat_vec.iter().collect::<Vec<_>>();
overflow::rewrite_with_parens(
&context,
&path_str,
&pat_ref_vec,
pat_vec.iter(),
shape,
span,
context.config.max_width(),

View File

@ -11,6 +11,7 @@
// A generic trait to abstract the rewriting of an element (of the AST).
use syntax::parse::ParseSess;
use syntax::ptr;
use syntax::source_map::{SourceMap, Span};
use config::{Config, IndentStyle};
@ -25,6 +26,12 @@ pub trait Rewrite {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
}
impl<T: Rewrite> Rewrite for ptr::P<T> {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
(**self).rewrite(context, shape)
}
}
#[derive(Clone)]
pub struct RewriteContext<'a> {
pub parse_session: &'a ParseSess,

View File

@ -8,8 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ast;
use syntax::source_map::Span;
use syntax::{
ast, ptr,
source_map::{self, Span},
};
use macros::MacroArg;
use utils::{mk_sp, outer_attributes};
@ -21,6 +23,18 @@ pub trait Spanned {
fn span(&self) -> Span;
}
impl<T: Spanned> Spanned for ptr::P<T> {
fn span(&self) -> Span {
(**self).span()
}
}
impl<T> Spanned for source_map::Spanned<T> {
fn span(&self) -> Span {
self.span
}
}
macro_rules! span_with_attrs_lo_hi {
($this:ident, $lo:expr, $hi:expr) => {{
let attrs = outer_attributes(&$this.attrs);

View File

@ -17,7 +17,7 @@ use syntax::source_map::{self, BytePos, Span};
use syntax::symbol::keywords;
use config::{IndentStyle, TypeDensity};
use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, ToExpr};
use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix};
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
use macros::{rewrite_macro, MacroPosition};
use overflow;
@ -141,7 +141,7 @@ where
}
#[derive(Debug)]
enum SegmentParam<'a> {
pub enum SegmentParam<'a> {
LifeTime(&'a ast::Lifetime),
Type(&'a ast::Ty),
Binding(&'a ast::TypeBinding),
@ -166,19 +166,6 @@ impl<'a> Spanned for SegmentParam<'a> {
}
}
impl<'a> ToExpr for SegmentParam<'a> {
fn to_expr(&self) -> Option<&ast::Expr> {
None
}
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
match *self {
SegmentParam::Type(ty) => ty.can_be_overflowed(context, len),
_ => false,
}
}
}
impl<'a> Rewrite for SegmentParam<'a> {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match *self {
@ -252,7 +239,7 @@ fn rewrite_segment(
let generics_str = overflow::rewrite_with_angle_brackets(
context,
"",
&param_list.iter().map(|e| &*e).collect::<Vec<_>>(),
param_list.iter(),
shape,
mk_sp(*span_lo, span_hi),
)?;
@ -664,12 +651,9 @@ impl Rewrite for ast::Ty {
ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
.map(|ty_str| format!("[{}]", ty_str))
}
ast::TyKind::Tup(ref items) => rewrite_tuple(
context,
&::utils::ptr_vec_to_ref_vec(items),
self.span,
shape,
),
ast::TyKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
}
ast::TyKind::Path(ref q_self, ref path) => {
rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
}

View File

@ -256,9 +256,7 @@ pub enum QlError {
// (kind, input, expected)
#[fail(
display = "Could not find {}: Found: {}, expected: {:?}",
0,
1,
2
0, 1, 2
)]
ResolveError(&'static str, String, Option<String>),
}