Fix compile errors from breaking changes in libsyntax

cc https://github.com/rust-lang/rust/pull/48149.
This commit is contained in:
topecongiro 2018-06-25 15:24:00 +09:00
parent ceda3679cc
commit e5e1e0cea8
7 changed files with 121 additions and 114 deletions

View File

@ -70,6 +70,7 @@ use expr::rewrite_call;
use macros::convert_try_mac; use macros::convert_try_mac;
use rewrite::{Rewrite, RewriteContext}; use rewrite::{Rewrite, RewriteContext};
use shape::Shape; use shape::Shape;
use spanned::Spanned;
use utils::{ use utils::{
first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width, first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
wrap_str, wrap_str,
@ -436,9 +437,9 @@ fn rewrite_chain_subexpr(
match expr.node { match expr.node {
ast::ExprKind::MethodCall(ref segment, ref expressions) => { ast::ExprKind::MethodCall(ref segment, ref expressions) => {
let types = match segment.parameters { let types = match segment.args {
Some(ref params) => match **params { Some(ref params) => match **params {
ast::PathParameters::AngleBracketed(ref data) => &data.types[..], ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
_ => &[], _ => &[],
}, },
_ => &[], _ => &[],
@ -484,7 +485,7 @@ fn is_try(expr: &ast::Expr) -> bool {
fn rewrite_method_call( fn rewrite_method_call(
method_name: ast::Ident, method_name: ast::Ident,
types: &[ptr::P<ast::Ty>], types: &[ast::GenericArg],
args: &[ptr::P<ast::Expr>], args: &[ptr::P<ast::Expr>],
span: Span, span: Span,
context: &RewriteContext, context: &RewriteContext,
@ -500,7 +501,7 @@ fn rewrite_method_call(
let type_str = format!("::<{}>", type_list.join(", ")); let type_str = format!("::<{}>", type_list.join(", "));
(types.last().unwrap().span.hi(), type_str) (types.last().unwrap().span().hi(), type_str)
}; };
let callee_str = format!(".{}{}", method_name, type_str); let callee_str = format!(".{}{}", method_name, type_str);

View File

@ -2014,8 +2014,8 @@ fn rewrite_assignment(
pub enum RhsTactics { pub enum RhsTactics {
/// Use heuristics. /// Use heuristics.
Default, Default,
/// Put the rhs on the next line if it uses multiple line. /// Put the rhs on the next line if it uses multiple line, without extra indentation.
ForceNextLine, ForceNextLineWithoutIndent,
} }
// The left hand side must contain everything up to, and including, the // The left hand side must contain everything up to, and including, the
@ -2072,11 +2072,12 @@ fn choose_rhs<R: Rewrite>(
_ => { _ => {
// Expression did not fit on the same line as the identifier. // Expression did not fit on the same line as the identifier.
// Try splitting the line and see if that works better. // Try splitting the line and see if that works better.
let new_shape = let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
Shape::indented(shape.indent.block_indent(context.config), context.config)
.sub_width(shape.rhs_overhead(context.config))?;
let new_rhs = expr.rewrite(context, new_shape); let new_rhs = expr.rewrite(context, new_shape);
let new_indent_str = &new_shape.indent.to_string_with_newline(context.config); let new_indent_str = &shape
.indent
.block_indent(context.config)
.to_string_with_newline(context.config);
match (orig_rhs, new_rhs) { match (orig_rhs, new_rhs) {
(Some(ref orig_rhs), Some(ref new_rhs)) (Some(ref orig_rhs), Some(ref new_rhs))
@ -2098,8 +2099,22 @@ fn choose_rhs<R: Rewrite>(
} }
} }
fn shape_from_rhs_tactic(
context: &RewriteContext,
shape: Shape,
rhs_tactic: RhsTactics,
) -> Option<Shape> {
match rhs_tactic {
RhsTactics::ForceNextLineWithoutIndent => Some(shape.with_max_width(context.config)),
RhsTactics::Default => {
Shape::indented(shape.indent.block_indent(context.config), context.config)
.sub_width(shape.rhs_overhead(context.config))
}
}
}
pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool { pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
rhs_tactics == RhsTactics::ForceNextLine rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
|| !next_line_rhs.contains('\n') || !next_line_rhs.contains('\n')
|| count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
} }

View File

@ -346,7 +346,7 @@ impl UseTree {
.collect(), .collect(),
)); ));
} }
UseTreeKind::Simple(ref rename) => { UseTreeKind::Simple(ref rename, ..) => {
let mut name = (*path_to_imported_ident(&a.prefix).name.as_str()).to_owned(); let mut name = (*path_to_imported_ident(&a.prefix).name.as_str()).to_owned();
let alias = rename.and_then(|ident| { let alias = rename.and_then(|ident| {
if ident == path_to_imported_ident(&a.prefix) { if ident == path_to_imported_ident(&a.prefix) {

View File

@ -36,7 +36,6 @@ use overflow;
use rewrite::{Rewrite, RewriteContext}; use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape}; use shape::{Indent, Shape};
use spanned::Spanned; use spanned::Spanned;
use types::TraitTyParamBounds;
use utils::*; use utils::*;
use vertical::rewrite_with_alignment; use vertical::rewrite_with_alignment;
use visitor::FmtVisitor; use visitor::FmtVisitor;
@ -971,7 +970,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
is_auto, is_auto,
unsafety, unsafety,
ref generics, ref generics,
ref type_param_bounds, ref generic_bounds,
ref trait_items, ref trait_items,
) = item.node ) = item.node
{ {
@ -997,23 +996,22 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
result.push_str(&generics_str); result.push_str(&generics_str);
// FIXME(#2055): rustfmt fails to format when there are comments between trait bounds. // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
if !type_param_bounds.is_empty() { if !generic_bounds.is_empty() {
let ident_hi = context let ident_hi = context
.snippet_provider .snippet_provider
.span_after(item.span, &format!("{}", item.ident)); .span_after(item.span, &format!("{}", item.ident));
let bound_hi = type_param_bounds.last().unwrap().span().hi(); let bound_hi = generic_bounds.last().unwrap().span().hi();
let snippet = context.snippet(mk_sp(ident_hi, bound_hi)); let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
if contains_comment(snippet) { if contains_comment(snippet) {
return None; return None;
} }
}
if !type_param_bounds.is_empty() {
result = rewrite_assign_rhs_with( result = rewrite_assign_rhs_with(
context, context,
result + ":", result + ":",
&TraitTyParamBounds::new(type_param_bounds), generic_bounds,
shape, shape,
RhsTactics::ForceNextLine, RhsTactics::ForceNextLineWithoutIndent,
)?; )?;
} }
@ -1026,10 +1024,10 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
}; };
let where_budget = context.budget(last_line_width(&result)); let where_budget = context.budget(last_line_width(&result));
let pos_before_where = if type_param_bounds.is_empty() { let pos_before_where = if generic_bounds.is_empty() {
generics.where_clause.span.lo() generics.where_clause.span.lo()
} else { } else {
type_param_bounds[type_param_bounds.len() - 1].span().hi() generic_bounds[generic_bounds.len() - 1].span().hi()
}; };
let option = WhereClauseOption::snuggled(&generics_str); let option = WhereClauseOption::snuggled(&generics_str);
let where_clause_str = rewrite_where_clause( let where_clause_str = rewrite_where_clause(
@ -1134,7 +1132,7 @@ pub fn format_trait_alias(
context: &RewriteContext, context: &RewriteContext,
ident: ast::Ident, ident: ast::Ident,
generics: &ast::Generics, generics: &ast::Generics,
ty_param_bounds: &ast::TyParamBounds, generic_bounds: &ast::GenericBounds,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> Option<String> {
let alias = ident.name.as_str(); let alias = ident.name.as_str();
@ -1143,7 +1141,7 @@ pub fn format_trait_alias(
let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?; let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
let lhs = format!("trait {} =", generics_str); let lhs = format!("trait {} =", generics_str);
// 1 = ";" // 1 = ";"
rewrite_assign_rhs(context, lhs, ty_param_bounds, shape.sub_width(1)?).map(|s| s + ";") rewrite_assign_rhs(context, lhs, generic_bounds, shape.sub_width(1)?).map(|s| s + ";")
} }
fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> { fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
@ -1671,13 +1669,13 @@ fn rewrite_static(
pub fn rewrite_associated_type( pub fn rewrite_associated_type(
ident: ast::Ident, ident: ast::Ident,
ty_opt: Option<&ptr::P<ast::Ty>>, ty_opt: Option<&ptr::P<ast::Ty>>,
ty_param_bounds_opt: Option<&ast::TyParamBounds>, generic_bounds_opt: Option<&ast::GenericBounds>,
context: &RewriteContext, context: &RewriteContext,
indent: Indent, indent: Indent,
) -> Option<String> { ) -> Option<String> {
let prefix = format!("type {}", ident); let prefix = format!("type {}", ident);
let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt { let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
if bounds.is_empty() { if bounds.is_empty() {
String::new() String::new()
} else { } else {
@ -1703,11 +1701,11 @@ pub fn rewrite_associated_impl_type(
ident: ast::Ident, ident: ast::Ident,
defaultness: ast::Defaultness, defaultness: ast::Defaultness,
ty_opt: Option<&ptr::P<ast::Ty>>, ty_opt: Option<&ptr::P<ast::Ty>>,
ty_param_bounds_opt: Option<&ast::TyParamBounds>, generic_bounds_opt: Option<&ast::GenericBounds>,
context: &RewriteContext, context: &RewriteContext,
indent: Indent, indent: Indent,
) -> Option<String> { ) -> Option<String> {
let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?; let result = rewrite_associated_type(ident, ty_opt, generic_bounds_opt, context, indent)?;
match defaultness { match defaultness {
ast::Defaultness::Default => Some(format!("default {}", result)), ast::Defaultness::Default => Some(format!("default {}", result)),
@ -2698,7 +2696,7 @@ fn format_generics(
} }
// If the generics are not parameterized then generics.span.hi() == 0, // If the generics are not parameterized then generics.span.hi() == 0,
// so we use span.lo(), which is the position after `struct Foo`. // so we use span.lo(), which is the position after `struct Foo`.
let span_end_before_where = if generics.is_parameterized() { let span_end_before_where = if !generics.params.is_empty() {
generics.span.hi() generics.span.hi()
} else { } else {
span.lo() span.lo()
@ -2804,15 +2802,6 @@ impl Rewrite for ast::ForeignItem {
} }
} }
impl Rewrite for ast::GenericParam {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match *self {
ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.rewrite(context, shape),
ast::GenericParam::Type(ref ty) => ty.rewrite(context, shape),
}
}
}
/// Rewrite an inline mod. /// Rewrite an inline mod.
pub fn rewrite_mod(item: &ast::Item) -> String { pub fn rewrite_mod(item: &ast::Item) -> String {
let mut result = String::with_capacity(32); let mut result = String::with_capacity(32);

View File

@ -14,6 +14,8 @@ use syntax::codemap::Span;
use macros::MacroArg; use macros::MacroArg;
use utils::{mk_sp, outer_attributes}; use utils::{mk_sp, outer_attributes};
use std::cmp::max;
/// Spanned returns a span including attributes, if available. /// Spanned returns a span including attributes, if available.
pub trait Spanned { pub trait Spanned {
fn span(&self) -> Span; fn span(&self) -> Span;
@ -110,10 +112,25 @@ impl Spanned for ast::Arg {
impl Spanned for ast::GenericParam { impl Spanned for ast::GenericParam {
fn span(&self) -> Span { fn span(&self) -> Span {
match *self { let lo = if self.attrs.is_empty() {
ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.span(), self.ident.span.lo()
ast::GenericParam::Type(ref ty) => ty.span(), } else {
} self.attrs[0].span.lo()
};
let hi = if self.bounds.is_empty() {
self.ident.span.hi()
} else {
self.bounds.last().unwrap().span().hi()
};
let ty_hi = if let ast::GenericParamKind::Type {
default: Some(ref ty),
} = self.kind
{
ty.span().hi()
} else {
hi
};
mk_sp(lo, max(hi, ty_hi))
} }
} }
@ -142,42 +159,21 @@ impl Spanned for ast::FunctionRetTy {
} }
} }
impl Spanned for ast::TyParam { impl Spanned for ast::GenericArg {
fn span(&self) -> Span {
// Note that ty.span is the span for ty.ident, not the whole item.
let lo = if self.attrs.is_empty() {
self.ident.span.lo()
} else {
self.attrs[0].span.lo()
};
if let Some(ref def) = self.default {
return mk_sp(lo, def.span.hi());
}
if self.bounds.is_empty() {
return mk_sp(lo, self.ident.span.hi());
}
let hi = self.bounds[self.bounds.len() - 1].span().hi();
mk_sp(lo, hi)
}
}
impl Spanned for ast::TyParamBound {
fn span(&self) -> Span { fn span(&self) -> Span {
match *self { match *self {
ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span, ast::GenericArg::Lifetime(ref lt) => lt.ident.span,
ast::TyParamBound::RegionTyParamBound(ref l) => l.ident.span, ast::GenericArg::Type(ref ty) => ty.span(),
} }
} }
} }
impl Spanned for ast::LifetimeDef { impl Spanned for ast::GenericBound {
fn span(&self) -> Span { fn span(&self) -> Span {
let hi = if self.bounds.is_empty() { match *self {
self.lifetime.ident.span.hi() ast::GenericBound::Trait(ref ptr, _) => ptr.span,
} else { ast::GenericBound::Outlives(ref l) => l.ident.span,
self.bounds[self.bounds.len() - 1].ident.span.hi() }
};
mk_sp(self.lifetime.ident.span.lo(), hi)
} }
} }

View File

@ -148,6 +148,15 @@ enum SegmentParam<'a> {
Binding(&'a ast::TypeBinding), Binding(&'a ast::TypeBinding),
} }
impl<'a> SegmentParam<'a> {
fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam {
match arg {
ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
}
}
}
impl<'a> Spanned for SegmentParam<'a> { impl<'a> Spanned for SegmentParam<'a> {
fn span(&self) -> Span { fn span(&self) -> Span {
match *self { match *self {
@ -220,18 +229,15 @@ fn rewrite_segment(
shape.shrink_left(ident_len)? shape.shrink_left(ident_len)?
}; };
if let Some(ref params) = segment.parameters { if let Some(ref args) = segment.args {
match **params { match **args {
ast::PathParameters::AngleBracketed(ref data) ast::GenericArgs::AngleBracketed(ref data)
if !data.lifetimes.is_empty() if !data.args.is_empty() || !data.bindings.is_empty() =>
|| !data.types.is_empty()
|| !data.bindings.is_empty() =>
{ {
let param_list = data let param_list = data
.lifetimes .args
.iter() .iter()
.map(SegmentParam::LifeTime) .map(SegmentParam::from_generic_arg)
.chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
.chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x))) .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -257,7 +263,7 @@ fn rewrite_segment(
result.push_str(&generics_str) result.push_str(&generics_str)
} }
ast::PathParameters::Parenthesized(ref data) => { ast::GenericArgs::Parenthesized(ref data) => {
let output = match data.output { let output = match data.output {
Some(ref ty) => FunctionRetTy::Ty(ty.clone()), Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
None => FunctionRetTy::Default(codemap::DUMMY_SP), None => FunctionRetTy::Default(codemap::DUMMY_SP),
@ -457,15 +463,18 @@ impl Rewrite for ast::WherePredicate {
} }
} }
impl Rewrite for ast::LifetimeDef { impl Rewrite for ast::GenericArg {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
rewrite_bounded_lifetime(&self.lifetime, &self.bounds, context, shape) match *self {
ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
}
} }
} }
fn rewrite_bounded_lifetime( fn rewrite_bounded_lifetime(
lt: &ast::Lifetime, lt: &ast::Lifetime,
bounds: &[ast::Lifetime], bounds: &[ast::GenericBound],
context: &RewriteContext, context: &RewriteContext,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> Option<String> {
@ -486,45 +495,36 @@ fn rewrite_bounded_lifetime(
} }
} }
impl Rewrite for ast::TyParamBound {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match *self {
ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
tref.rewrite(context, shape)
}
ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => Some(
format!("?{}", tref.rewrite(context, shape.offset_left(1)?)?),
),
ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
}
}
}
impl Rewrite for ast::Lifetime { impl Rewrite for ast::Lifetime {
fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> { fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
Some(self.ident.to_string()) Some(self.ident.to_string())
} }
} }
/// A simple wrapper over type param bounds in trait. impl Rewrite for ast::GenericBound {
#[derive(new)]
pub struct TraitTyParamBounds<'a> {
inner: &'a ast::TyParamBounds,
}
impl<'a> Rewrite for TraitTyParamBounds<'a> {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
join_bounds(context, shape, self.inner, false) match *self {
ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
match trait_bound_modifier {
ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
ast::TraitBoundModifier::Maybe => {
let rw = poly_trait_ref.rewrite(context, shape.offset_left(1)?)?;
Some(format!("?{}", rw))
}
}
}
ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
}
} }
} }
impl Rewrite for ast::TyParamBounds { impl Rewrite for ast::GenericBounds {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
join_bounds(context, shape, self, true) join_bounds(context, shape, self, true)
} }
} }
impl Rewrite for ast::TyParam { impl Rewrite for ast::GenericParam {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
let mut result = String::with_capacity(128); let mut result = String::with_capacity(128);
// FIXME: If there are more than one attributes, this will force multiline. // FIXME: If there are more than one attributes, this will force multiline.
@ -537,7 +537,10 @@ impl Rewrite for ast::TyParam {
result.push_str(type_bound_colon(context)); result.push_str(type_bound_colon(context));
result.push_str(&self.bounds.rewrite(context, shape)?) result.push_str(&self.bounds.rewrite(context, shape)?)
} }
if let Some(ref def) = self.default { if let ast::GenericParamKind::Type {
default: Some(ref def),
} = self.kind
{
let eq_str = match context.config.type_punctuation_density() { let eq_str = match context.config.type_punctuation_density() {
TypeDensity::Compressed => "=", TypeDensity::Compressed => "=",
TypeDensity::Wide => " = ", TypeDensity::Wide => " = ",
@ -786,7 +789,10 @@ fn rewrite_lifetime_param(
) -> Option<String> { ) -> Option<String> {
let result = generic_params let result = generic_params
.iter() .iter()
.filter(|p| p.is_lifetime_param()) .filter(|p| match p.kind {
ast::GenericParamKind::Lifetime => true,
_ => false,
})
.map(|lt| lt.rewrite(context, shape)) .map(|lt| lt.rewrite(context, shape))
.collect::<Option<Vec<_>>>()? .collect::<Option<Vec<_>>>()?
.join(", "); .join(", ");

View File

@ -354,13 +354,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
let rw = format_trait(&self.get_context(), item, self.block_indent); let rw = format_trait(&self.get_context(), item, self.block_indent);
self.push_rewrite(item.span, rw); self.push_rewrite(item.span, rw);
} }
ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => { ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
let shape = Shape::indented(self.block_indent, self.config); let shape = Shape::indented(self.block_indent, self.config);
let rw = format_trait_alias( let rw = format_trait_alias(
&self.get_context(), &self.get_context(),
item.ident, item.ident,
generics, generics,
ty_param_bounds, generic_bounds,
shape, shape,
); );
self.push_rewrite(item.span, rw); self.push_rewrite(item.span, rw);
@ -461,11 +461,11 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
Some(&inner_attrs), Some(&inner_attrs),
); );
} }
ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => { ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
let rewrite = rewrite_associated_type( let rewrite = rewrite_associated_type(
ti.ident, ti.ident,
type_default.as_ref(), type_default.as_ref(),
Some(type_param_bounds), Some(generic_bounds),
&self.get_context(), &self.get_context(),
self.block_indent, self.block_indent,
); );