Skip to content

Refactor format against types and generics #1717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 26 additions & 19 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,16 +703,17 @@ fn format_impl_ref_and_type(
Some(ref tr) => tr.path.span.lo,
None => self_ty.span.lo,
};
let shape = generics_shape_from_config(
let shape = try_opt!(generics_shape_from_config(
context.config,
Shape::indented(offset + last_line_width(&result), context.config),
0,
);
));
let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
let generics_str = try_opt!(rewrite_generics_inner(
context,
generics,
shape,
shape.width,
one_line_budget,
mk_sp(lo, hi),
));

Expand Down Expand Up @@ -925,7 +926,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
let trait_bound_str = try_opt!(rewrite_trait_bounds(
context,
type_param_bounds,
Shape::legacy(context.config.max_width(), offset),
Shape::indented(offset, context.config),
));
// If the trait, generics, and trait bound cannot fit on the same line,
// put the trait bounds on an indented new line
Expand Down Expand Up @@ -1591,7 +1592,7 @@ pub fn rewrite_associated_type(
let prefix = format!("type {}", ident);

let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
let shape = Shape::legacy(context.config.max_width(), indent);
let shape = Shape::indented(indent, context.config);
let bounds: &[_] = ty_param_bounds;
let bound_str = try_opt!(
bounds
Expand Down Expand Up @@ -1900,7 +1901,8 @@ fn rewrite_fn_base(

if context.config.fn_args_layout() == IndentStyle::Block {
arg_indent = indent.block_indent(context.config);
multi_line_budget = context.config.max_width() - arg_indent.width();
// 1 = ","
multi_line_budget = context.config.max_width() - (arg_indent.width() + 1);
}

debug!(
Expand Down Expand Up @@ -2388,9 +2390,11 @@ fn rewrite_generics(
shape: Shape,
span: Span,
) -> Option<String> {
let shape = generics_shape_from_config(context.config, shape, 0);
rewrite_generics_inner(context, generics, shape, shape.width, span)
.or_else(|| rewrite_generics_inner(context, generics, shape, 0, span))
let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
let one_line_width = try_opt!(shape.width.checked_sub(2));
rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
rewrite_generics_inner(context, generics, g_shape, 0, span)
})
}

fn rewrite_generics_inner(
Expand Down Expand Up @@ -2437,14 +2441,17 @@ fn rewrite_generics_inner(
format_generics_item_list(context, items, shape, one_line_width)
}

pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Shape {
Shape {
// 2 = `<>`
width: shape.width.checked_sub(offset + 2).unwrap_or(0),
..match config.generics_indent() {
IndentStyle::Visual => shape.visual_indent(1 + offset),
IndentStyle::Block => shape.block().block_indent(config.tab_spaces()),
}
pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
match config.generics_indent() {
IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
IndentStyle::Block => {
// 1 = ","
shape
.block()
.block_indent(config.tab_spaces())
.with_max_width(config)
.sub_width(1)
}
}
}

Expand Down Expand Up @@ -2533,7 +2540,7 @@ fn rewrite_where_clause_rfc_style(
snuggle: bool,
span_end: Option<BytePos>,
) -> Option<String> {
let block_shape = shape.block();
let block_shape = shape.block().with_max_width(context.config);

let starting_newline = if snuggle {
" ".to_owned()
Expand All @@ -2555,7 +2562,7 @@ fn rewrite_where_clause_rfc_style(
terminator,
|pred| span_for_where_pred(pred).lo,
|pred| span_for_where_pred(pred).hi,
|pred| pred.rewrite(context, shape),
|pred| pred.rewrite(context, block_shape),
span_start,
span_end,
);
Expand Down
12 changes: 0 additions & 12 deletions src/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,18 +68,6 @@ pub struct ListFormatting<'a> {
pub config: &'a Config,
}

pub fn format_fn_args<I>(items: I, shape: Shape, config: &Config) -> Option<String>
where
I: Iterator<Item = ListItem>,
{
list_helper(
items,
shape,
config,
ListTactic::LimitedHorizontalVertical(config.fn_call_width()),
)
}

pub fn format_item_list<I>(items: I, shape: Shape, config: &Config) -> Option<String>
where
I: Iterator<Item = ListItem>,
Expand Down
96 changes: 68 additions & 28 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ use syntax::symbol::keywords;
use {Shape, Spanned};
use codemap::SpanUtils;
use items::{format_generics_item_list, generics_shape_from_config};
use lists::{itemize_list, format_fn_args};
use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
definitive_tactic};
use rewrite::{Rewrite, RewriteContext};
use utils::{extra_offset, format_mutability, colon_spaces, wrap_str, mk_sp, last_line_width};
use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
use config::{Style, TypeDensity};
use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple, wrap_args_with_parens};
use config::{IndentStyle, Style, TypeDensity};

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PathContext {
Expand Down Expand Up @@ -224,8 +225,12 @@ fn rewrite_segment(
""
};

let generics_shape =
generics_shape_from_config(context.config, shape, separator.len());
let generics_shape = try_opt!(generics_shape_from_config(
context.config,
shape,
separator.len(),
));
let one_line_width = try_opt!(shape.width.checked_sub(separator.len() + 2));
let items = itemize_list(
context.codemap,
param_list.into_iter(),
Expand All @@ -240,7 +245,7 @@ fn rewrite_segment(
context,
items,
generics_shape,
generics_shape.width,
one_line_width,
));

// Update position of last bracket.
Expand Down Expand Up @@ -305,7 +310,16 @@ where
// 2 for ()
let budget = try_opt!(shape.width.checked_sub(2));
// 1 for (
let offset = shape.indent + 1;
let offset = match context.config.fn_args_layout() {
IndentStyle::Block => {
shape
.block()
.block_indent(context.config.tab_spaces())
.indent
}
IndentStyle::Visual => shape.indent + 1,
};
let list_shape = Shape::legacy(budget, offset);
let list_lo = context.codemap.span_after(span, "(");
let items = itemize_list(
context.codemap,
Expand All @@ -324,39 +338,64 @@ where
ArgumentKind::Variadic(start) => start + BytePos(3),
},
|arg| match *arg {
ArgumentKind::Regular(ref ty) => ty.rewrite(context, Shape::legacy(budget, offset)),
ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
ArgumentKind::Variadic(_) => Some("...".to_owned()),
},
list_lo,
span.hi,
);

let list_str = try_opt!(format_fn_args(
items,
Shape::legacy(budget, offset),
context.config,
));
let item_vec: Vec<_> = items.collect();

let tactic = definitive_tactic(&*item_vec, ListTactic::HorizontalVertical, budget);

let fmt = ListFormatting {
tactic: tactic,
separator: ",",
trailing_separator: if !context.use_block_indent() || variadic {
SeparatorTactic::Never
} else {
context.config.trailing_comma()
},
shape: list_shape,
ends_with_newline: false,
config: context.config,
};

let list_str = try_opt!(write_list(&item_vec, &fmt));

let ty_shape = match context.config.fn_args_layout() {
IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
IndentStyle::Visual => try_opt!(shape.block_left(4)),
};
let output = match *output {
FunctionRetTy::Ty(ref ty) => {
let budget = try_opt!(shape.width.checked_sub(4));
let type_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, offset + 4)));
let type_str = try_opt!(ty.rewrite(context, ty_shape));
format!(" -> {}", type_str)
}
FunctionRetTy::Default(..) => String::new(),
};

let infix = if !output.is_empty() && output.len() + list_str.len() > shape.width {
format!("\n{}", (offset - 1).to_string(context.config))
let shape = try_opt!(shape.sub_width(output.len()));
let extendable = !list_str.contains('\n') || list_str.is_empty();
let args = wrap_args_with_parens(
context,
&list_str,
extendable,
shape,
Shape::indented(offset, context.config),
);
if last_line_width(&args) + output.len() > shape.width {
Some(format!(
"{}\n{}{}",
args,
offset.to_string(context.config),
output.trim_left()
))
} else {
String::new()
};
Some(format!("{}{}", args, output))
}

Some(if context.config.spaces_within_parens() {
format!("( {} ){}{}", list_str, infix, output)
} else {
format!("({}){}{}", list_str, infix, output)
})
}

fn type_bound_colon(context: &RewriteContext) -> &'static str {
Expand Down Expand Up @@ -422,7 +461,9 @@ impl Rewrite for ast::WherePredicate {
.map(|ty_bound| ty_bound.rewrite(context, ty_shape))
.collect()
);
let bounds_str = join_bounds(context, ty_shape, &bounds);
let overhead = type_str.len() + colon.len();
let bounds_str =
join_bounds(context, try_opt!(ty_shape.sub_width(overhead)), &bounds);

format!("{}{}{}", type_str, colon, bounds_str)
}
Expand Down Expand Up @@ -760,16 +801,15 @@ fn rewrite_bare_fn(

result.push_str("fn");

let budget = try_opt!(shape.width.checked_sub(result.len()));
let indent = shape.indent + result.len();
let func_ty_shape = try_opt!(shape.offset_left(result.len()));

let rewrite = try_opt!(format_function_type(
bare_fn.decl.inputs.iter(),
&bare_fn.decl.output,
bare_fn.decl.variadic,
span,
context,
Shape::legacy(budget, indent),
func_ty_shape,
));

result.push_str(&rewrite);
Expand Down
14 changes: 14 additions & 0 deletions tests/source/big-impl-rfc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,17 @@ impl<
> {
fn foo() {}
}

// #1689
impl<M, S, F, X> SubSelectDirect<M, S, F, X>
where
M: select::Selector,
S: event::Stream,
F: for<'t> FnMut(transform::Api<
't,
Stream<ContentStream<S>>,
>)
-> transform::Api<'t, X>,
X: event::Stream,
{
}
4 changes: 4 additions & 0 deletions tests/source/type_alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ pub type Exactly100CharstoEqualWhereTest<T, U, PARAMET> where T: Clone + Ord + E
pub type Exactly101CharstoEqualWhereTest<T, U, PARAMETE> where T: Clone + Ord + Eq + SomeOtherTrait = Option<T>;

type RegisterPlugin = unsafe fn(pt: *const c_char, plugin: *mut c_void, data: *mut CallbackData);

// #1683
pub type Between<Lhs, Rhs> = super::operators::Between<Lhs, super::operators::And<AsExpr<Rhs, Lhs>, AsExpr<Rhs, Lhs>>>;
pub type NotBetween<Lhs, Rhs> = super::operators::NotBetween<Lhs, super::operators::And<AsExpr<Rhs, Lhs>, AsExpr<Rhs, Lhs>>>;
11 changes: 11 additions & 0 deletions tests/target/big-impl-rfc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,14 @@ impl<
> {
fn foo() {}
}

// #1689
impl<M, S, F, X> SubSelectDirect<M, S, F, X>
where
M: select::Selector,
S: event::Stream,
F: for<'t> FnMut(transform::Api<'t, Stream<ContentStream<S>>>)
-> transform::Api<'t, X>,
X: event::Stream,
{
}
17 changes: 10 additions & 7 deletions tests/target/extern_not_explicit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ extern {

extern fn sup() {}

type funky_func = extern fn(unsafe extern "rust-call" fn(*const JSJitInfo,
*mut JSContext,
HandleObject,
*mut libc::c_void,
u32,
*mut JSVal)
-> u8);
type funky_func = extern fn(
unsafe extern "rust-call" fn(
*const JSJitInfo,
*mut JSContext,
HandleObject,
*mut libc::c_void,
u32,
*mut JSVal,
) -> u8,
);
Loading