-// 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.
-
// Formatting top-level items - functions, structs, enums, traits, impls.
use std::borrow::Cow;
use std::cmp::{min, Ordering};
-use config::lists::*;
use regex::Regex;
use rustc_target::spec::abi;
-use syntax::codemap::{self, BytePos, Span};
+use syntax::source_map::{self, BytePos, Span};
use syntax::visit;
use syntax::{ast, ptr, symbol};
-use codemap::{LineRangeUtils, SpanUtils};
-use comment::{
+use crate::comment::{
combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented,
};
-use config::{BraceStyle, Config, Density, IndentStyle};
-use expr::{
+use crate::config::lists::*;
+use crate::config::{BraceStyle, Config, Density, IndentStyle, Version};
+use crate::expr::{
format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
ExprType, RhsTactics,
};
-use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
-use macros::{rewrite_macro, MacroPosition};
-use overflow;
-use rewrite::{Rewrite, RewriteContext};
-use shape::{Indent, Shape};
-use spanned::Spanned;
-use utils::*;
-use vertical::rewrite_with_alignment;
-use visitor::FmtVisitor;
-
-const DEFAULT_VISIBILITY: ast::Visibility = codemap::Spanned {
+use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
+use crate::macros::{rewrite_macro, MacroPosition};
+use crate::overflow;
+use crate::rewrite::{Rewrite, RewriteContext};
+use crate::shape::{Indent, Shape};
+use crate::source_map::{LineRangeUtils, SpanUtils};
+use crate::spanned::Spanned;
+use crate::utils::*;
+use crate::vertical::rewrite_with_alignment;
+use crate::visitor::FmtVisitor;
+
+const DEFAULT_VISIBILITY: ast::Visibility = source_map::Spanned {
node: ast::VisibilityKind::Inherited,
- span: codemap::DUMMY_SP,
+ span: source_map::DUMMY_SP,
};
fn type_annotation_separator(config: &Config) -> &str {
// Statements of the form
// let pat: ty = init;
impl Rewrite for ast::Local {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
debug!(
"Local::rewrite {:?} {} {:?}",
self, shape.width, shape.indent
if let Some(ref ty) = self.ty {
let separator = type_annotation_separator(context.config);
- let indent = shape.indent + last_line_width(&result) + separator.len();
- // 1 = ;
- let budget = shape.width.checked_sub(indent.width() + 1)?;
- let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
+ let ty_shape = if pat_str.contains('\n') {
+ shape.with_max_width(context.config)
+ } else {
+ shape
+ }
+ .offset_left(last_line_width(&result) + separator.len())?
+ // 2 = ` =`
+ .sub_width(2)?;
+
+ let rewrite = ty.rewrite(context, ty_shape)?;
infix.push_str(separator);
infix.push_str(&rewrite);
) -> FnSig<'a> {
FnSig {
unsafety: method_sig.header.unsafety,
- is_async: method_sig.header.asyncness,
+ is_async: method_sig.header.asyncness.node,
constness: method_sig.header.constness.node,
defaultness: ast::Defaultness::Final,
abi: method_sig.header.abi,
}
pub fn from_fn_kind(
- fn_kind: &'a visit::FnKind,
+ fn_kind: &'a visit::FnKind<'_>,
generics: &'a ast::Generics,
decl: &'a ast::FnDecl,
defaultness: ast::Defaultness,
generics,
abi: fn_header.abi,
constness: fn_header.constness.node,
- is_async: fn_header.asyncness,
+ is_async: fn_header.asyncness.node,
defaultness,
unsafety: fn_header.unsafety,
visibility: visibility.clone(),
}
}
- fn to_str(&self, context: &RewriteContext) -> String {
+ fn to_str(&self, context: &RewriteContext<'_>) -> String {
let mut result = String::with_capacity(128);
// Vis defaultness constness unsafety abi.
result.push_str(&*format_visibility(context, &self.visibility));
}
impl<'a> FmtVisitor<'a> {
- fn format_item(&mut self, item: &Item) {
+ fn format_item(&mut self, item: &Item<'_>) {
self.buffer.push_str(&item.abi);
let snippet = self.snippet(item.span);
self.last_pos = item.span.hi();
}
- fn format_body_element(&mut self, element: &BodyElement) {
+ fn format_body_element(&mut self, element: &BodyElement<'_>) {
match *element {
BodyElement::ForeignItem(item) => self.format_foreign_item(item),
}
&mut self,
indent: Indent,
ident: ast::Ident,
- fn_sig: &FnSig,
+ fn_sig: &FnSig<'_>,
span: Span,
block: &ast::Block,
inner_attrs: Option<&[ast::Attribute]>,
newline_brace = false;
}
- // Prepare for the function body by possibly adding a newline and
- // indent.
- // FIXME we'll miss anything between the end of the signature and the
- // start of the body, but we need more spans from the compiler to solve
- // this.
- if newline_brace {
- result.push_str(&indent.to_string_with_newline(self.config));
+ if let rw @ Some(..) = self.single_line_fn(&result, block, inner_attrs) {
+ rw
} else {
- result.push(' ');
+ // Prepare for the function body by possibly adding a newline and
+ // indent.
+ // FIXME we'll miss anything between the end of the signature and the
+ // start of the body, but we need more spans from the compiler to solve
+ // this.
+ if newline_brace {
+ result.push_str(&indent.to_string_with_newline(self.config));
+ } else {
+ result.push(' ');
+ }
+ Some(result)
}
-
- self.single_line_fn(&result, block, inner_attrs)
- .or_else(|| Some(result))
}
pub fn rewrite_required_fn(
return None;
}
- let codemap = self.get_context().codemap;
+ let source_map = self.get_context().source_map;
if self.config.empty_item_single_line()
- && is_empty_block(block, None, codemap)
- && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
+ && is_empty_block(block, None, source_map)
+ && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
+ && !last_line_contains_single_line_comment(fn_str)
{
- return Some(format!("{}{{}}", fn_str));
+ return Some(format!("{} {{}}", fn_str));
}
- if self.config.fn_single_line() && is_simple_block_stmt(block, None, codemap) {
- let rewrite = {
- if let Some(stmt) = block.stmts.first() {
- match stmt_expr(stmt) {
- Some(e) => {
- let suffix = if semicolon_for_expr(&self.get_context(), e) {
- ";"
- } else {
- ""
- };
-
- format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
- .map(|s| s + suffix)
- .or_else(|| Some(self.snippet(e.span).to_owned()))
- }
- None => stmt.rewrite(&self.get_context(), self.shape()),
- }
+ if !self.config.fn_single_line() || !is_simple_block_stmt(block, None, source_map) {
+ return None;
+ }
+
+ let stmt = block.stmts.first()?;
+ let res = match stmt_expr(stmt) {
+ Some(e) => {
+ let suffix = if semicolon_for_expr(&self.get_context(), e) {
+ ";"
} else {
- None
- }
- };
+ ""
+ };
- if let Some(res) = rewrite {
- let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
- if !res.contains('\n') && width <= self.config.max_width() {
- return Some(format!("{}{{ {} }}", fn_str, res));
- }
+ format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
+ .map(|s| s + suffix)?
}
- }
+ None => stmt.rewrite(&self.get_context(), self.shape())?,
+ };
- None
+ let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
+ if !res.contains('\n') && width <= self.config.max_width() {
+ Some(format!("{} {{ {} }}", fn_str, res))
+ } else {
+ None
+ }
}
- pub fn visit_static(&mut self, static_parts: &StaticParts) {
+ pub fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
self.push_rewrite(static_parts.span, rewrite);
}
- pub fn visit_struct(&mut self, struct_parts: &StructParts) {
+ pub fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
let is_tuple = struct_parts.def.is_tuple();
let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
.map(|s| if is_tuple { s + ";" } else { s });
BracePos::Auto
},
self.block_indent,
- mk_sp(span.lo(), body_start),
+ // make a span that starts right after `enum Foo`
+ mk_sp(ident.span.hi(), body_start),
last_line_width(&enum_header),
- ).unwrap();
+ )
+ .unwrap();
self.push_str(&generics_str);
self.last_pos = body_start;
let original_offset = self.block_indent;
self.block_indent = self.block_indent.block_indent(self.config);
+ // If enum variants have discriminants, try to vertically align those,
+ // provided the discrims are not shifted too much to the right
+ let align_threshold: usize = self.config.enum_discrim_align_threshold();
+ let discr_ident_lens: Vec<usize> = enum_def
+ .variants
+ .iter()
+ .filter(|var| var.node.disr_expr.is_some())
+ .map(|var| rewrite_ident(&self.get_context(), var.node.ident).len())
+ .collect();
+ // cut the list at the point of longest discrim shorter than the threshold
+ // All of the discrims under the threshold will get padded, and all above - left as is.
+ let pad_discrim_ident_to = *discr_ident_lens
+ .iter()
+ .filter(|&l| *l <= align_threshold)
+ .max()
+ .unwrap_or(&0);
+
let itemize_list_with = |one_line_width: usize| {
itemize_list(
self.snippet_provider,
}
},
|f| f.span.hi(),
- |f| self.format_variant(f, one_line_width),
+ |f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
body_lo,
body_hi,
false,
- ).collect()
+ )
+ .collect()
};
let mut items: Vec<_> =
itemize_list_with(self.config.width_heuristics().struct_variant_width);
}
// Variant of an enum.
- fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
+ fn format_variant(
+ &self,
+ field: &ast::Variant,
+ one_line_width: usize,
+ pad_discrim_ident_to: usize,
+ ) -> Option<String> {
if contains_skip(&field.node.attrs) {
let lo = field.node.attrs[0].span.lo();
let span = mk_sp(lo, field.span.hi());
)?,
ast::VariantData::Unit(..) => {
if let Some(ref expr) = field.node.disr_expr {
- let lhs = format!("{} =", rewrite_ident(&context, field.node.ident));
+ let lhs = format!(
+ "{:1$} =",
+ rewrite_ident(&context, field.node.ident),
+ pad_discrim_ident_to
+ );
rewrite_assign_rhs(&context, lhs, &*expr.value, shape)?
} else {
rewrite_ident(&context, field.node.ident).to_owned()
self.buffer.clear();
}
// type -> existential -> const -> macro -> method
- use ast::ImplItemKind::*;
+ use crate::ast::ImplItemKind::*;
fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
match (a, b) {
(Type(..), Type(..))
}
pub fn format_impl(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
item: &ast::Item,
offset: Indent,
where_span_end: Option<BytePos>,
false,
)?;
- // If there is no where clause, we may have missing comments between the trait name and
+ // If there is no where-clause, we may have missing comments between the trait name and
// the opening brace.
if generics.where_clause.predicates.is_empty() {
if let Some(hi) = where_span_end {
result.push_str(&where_clause_str);
if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
// if the where_clause contains extra comments AND
- // there is only one where clause predicate
+ // there is only one where-clause predicate
// recover the suppressed comma in single line where_clause formatting
if generics.where_clause.predicates.len() == 1 {
result.push_str(",");
let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
result.push_str(&inner_indent_str);
- result.push_str(visitor.buffer.to_string().trim());
+ result.push_str(visitor.buffer.trim());
result.push_str(&outer_indent_str);
- }
-
- if result.ends_with('{') && !context.config.empty_item_single_line() {
+ } else if need_newline || !context.config.empty_item_single_line() {
result.push_str(&sep);
}
+
result.push('}');
Some(result)
}
fn is_impl_single_line(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
items: &[ast::ImplItem],
result: &str,
where_clause_str: &str,
}
fn format_impl_ref_and_type(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
item: &ast::Item,
offset: Indent,
) -> Option<String> {
// ` for`
let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
- // If there is no where clause adapt budget for type formatting to take space and curly
+ // If there is no where-clause adapt budget for type formatting to take space and curly
// brace into account.
match context.config.brace_style() {
BraceStyle::AlwaysNextLine => 0,
}
fn rewrite_trait_ref(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
trait_ref: &ast::TraitRef,
offset: Indent,
polarity_str: &str,
}
impl<'a> StructParts<'a> {
- fn format_header(&self, context: &RewriteContext) -> String {
+ fn format_header(&self, context: &RewriteContext<'_>) -> String {
format_header(context, self.prefix, self.ident, self.vis)
}
}
fn format_struct(
- context: &RewriteContext,
- struct_parts: &StructParts,
+ context: &RewriteContext<'_>,
+ struct_parts: &StructParts<'_>,
offset: Indent,
one_line_width: Option<usize>,
) -> Option<String> {
}
}
-pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
+pub fn format_trait(
+ context: &RewriteContext<'_>,
+ item: &ast::Item,
+ offset: Indent,
+) -> Option<String> {
if let ast::ItemKind::Trait(
is_auto,
unsafety,
)?;
}
- // Rewrite where clause.
+ // Rewrite where-clause.
if !generics.where_clause.predicates.is_empty() {
let where_density = if context.config.indent_style() == IndentStyle::Block {
Density::Compressed
option,
false,
)?;
- // If the where clause cannot fit on the same line,
- // put the where clause on a new line
+ // If the where-clause cannot fit on the same line,
+ // put the where-clause on a new line
if !where_clause_str.contains('\n')
&& last_line_width(&result) + where_clause_str.len() + offset.width()
> context.config.comment_width()
let snippet = context.snippet(item.span);
let open_pos = snippet.find_uncommented("{")? + 1;
+ let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
let mut visitor = FmtVisitor::from_context(context);
visitor.format_missing(item.span.hi() - BytePos(1));
let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
- let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
result.push_str(&inner_indent_str);
- result.push_str(visitor.buffer.to_string().trim());
+ result.push_str(visitor.buffer.trim());
result.push_str(&outer_indent_str);
} else if result.contains('\n') {
- result.push('\n');
+ result.push_str(&outer_indent_str);
}
result.push('}');
}
pub fn format_trait_alias(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
ident: ast::Ident,
+ vis: &ast::Visibility,
generics: &ast::Generics,
generic_bounds: &ast::GenericBounds,
shape: Shape,
// 6 = "trait ", 2 = " ="
let g_shape = shape.offset_left(6)?.sub_width(2)?;
let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
- let lhs = format!("trait {} =", generics_str);
+ let vis_str = format_visibility(context, vis);
+ let lhs = format!("{}trait {} =", vis_str, generics_str);
// 1 = ";"
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> {
let header_str = format_header(context, p.prefix, p.ident, p.vis);
let generics_str = if let Some(generics) = p.generics {
let hi = if generics.where_clause.predicates.is_empty() {
context.config.brace_style(),
BracePos::None,
offset,
- mk_sp(generics.span.lo(), hi),
+ // make a span that starts right after `struct Foo`
+ mk_sp(p.ident.span.hi(), hi),
last_line_width(&header_str),
)?
} else {
}
pub fn format_struct_struct(
- context: &RewriteContext,
- struct_parts: &StructParts,
+ context: &RewriteContext<'_>,
+ struct_parts: &StructParts<'_>,
fields: &[ast::StructField],
offset: Indent,
one_line_width: Option<usize>,
let header_str = struct_parts.format_header(context);
result.push_str(&header_str);
- let header_hi = span.lo() + BytePos(header_str.len() as u32);
+ let header_hi = struct_parts.ident.span.hi();
let body_lo = context.snippet_provider.span_after(span, "{");
let generics_str = match struct_parts.generics {
BracePos::Auto
},
offset,
+ // make a span that starts right after `struct Foo`
mk_sp(header_hi, body_lo),
last_line_width(&result),
)?,
{
result.push('\n');
result.push_str(&offset.to_string(context.config));
- result.push_str(generics_str.trim_left());
+ result.push_str(generics_str.trim_start());
} else {
result.push_str(&generics_str);
}
let items_str = rewrite_with_alignment(
fields,
context,
- Shape::indented(offset, context.config).sub_width(1)?,
+ Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
mk_sp(body_lo, span.hi()),
one_line_budget,
)?;
// Format tuple or struct without any fields. We need to make sure that the comments
// inside the delimiters are preserved.
fn format_empty_struct_or_tuple(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
span: Span,
offset: Indent,
result: &mut String,
}
fn format_tuple_struct(
- context: &RewriteContext,
- struct_parts: &StructParts,
+ context: &RewriteContext<'_>,
+ struct_parts: &StructParts<'_>,
fields: &[ast::StructField],
offset: Indent,
) -> Option<String> {
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,
|| offset.block_indent + result.len() + where_clause_str.len() + 1
> context.config.max_width())
{
- // We need to put the where clause on a new line, but we didn't
- // know that earlier, so the where clause will not be indented properly.
+ // We need to put the where-clause on a new line, but we didn't
+ // know that earlier, so the where-clause will not be indented properly.
result.push('\n');
result.push_str(
&(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
}
fn rewrite_type_prefix(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
prefix: &str,
ident: ast::Ident,
}
fn rewrite_type_item<R: Rewrite>(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
prefix: &str,
suffix: &str,
result.push_str(suffix);
} else {
result.push_str(&indent.to_string_with_newline(context.config));
- result.push_str(suffix.trim_left());
+ result.push_str(suffix.trim_start());
}
// 1 = ";"
}
pub fn rewrite_type_alias(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
ident: ast::Ident,
ty: &ast::Ty,
}
pub fn rewrite_existential_type(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
ident: ast::Ident,
generic_bounds: &ast::GenericBounds,
}
pub fn rewrite_struct_field_prefix(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
field: &ast::StructField,
) -> Option<String> {
let vis = format_visibility(context, &field.vis);
rewrite_ident(context, name),
type_annotation_spacing.0
),
- None => format!("{}", vis),
+ None => vis.to_string(),
})
}
impl Rewrite for ast::StructField {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
rewrite_struct_field(context, self, shape, 0)
}
}
pub fn rewrite_struct_field(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
field: &ast::StructField,
shape: Shape,
lhs_max_width: usize,
for _ in 0..lhs_offset {
spacing.push(' ');
}
- // In this extreme case we will be missing a space betweeen an attribute and a field.
+ // In this extreme case we will be missing a space between an attribute and a field.
if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
spacing.push(' ');
}
let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
// Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
let field_str = if is_prefix_empty {
- field_str.trim_left()
+ field_str.trim_start()
} else {
&field_str
};
}
fn rewrite_static(
- context: &RewriteContext,
- static_parts: &StaticParts,
+ context: &RewriteContext<'_>,
+ static_parts: &StaticParts<'_>,
offset: Indent,
) -> Option<String> {
let colon = colon_spaces(
lhs,
&**expr,
Shape::legacy(remaining_width, offset.block_only()),
- ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
+ )
+ .and_then(|res| recover_comment_removed(res, static_parts.span, context))
.map(|s| if s.ends_with(';') { s } else { s + ";" })
} else {
Some(format!("{}{};", prefix, ty_str))
pub fn rewrite_associated_type(
ident: ast::Ident,
ty_opt: Option<&ptr::P<ast::Ty>>,
+ generics: &ast::Generics,
generic_bounds_opt: Option<&ast::GenericBounds>,
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
) -> Option<String> {
- let prefix = format!("type {}", rewrite_ident(context, ident));
+ let ident_str = rewrite_ident(context, ident);
+ // 5 = "type "
+ let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
+ let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
+ let prefix = format!("type {}", generics_str);
let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
if bounds.is_empty() {
}
pub fn rewrite_existential_impl_type(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
ident: ast::Ident,
+ generics: &ast::Generics,
generic_bounds: &ast::GenericBounds,
indent: Indent,
) -> Option<String> {
- rewrite_associated_type(ident, None, Some(generic_bounds), context, indent)
+ rewrite_associated_type(ident, None, generics, Some(generic_bounds), context, indent)
.map(|s| format!("existential {}", s))
}
ident: ast::Ident,
defaultness: ast::Defaultness,
ty_opt: Option<&ptr::P<ast::Ty>>,
- context: &RewriteContext,
+ generics: &ast::Generics,
+ context: &RewriteContext<'_>,
indent: Indent,
) -> Option<String> {
- let result = rewrite_associated_type(ident, ty_opt, None, context, indent)?;
+ let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
match defaultness {
ast::Defaultness::Default => Some(format!("default {}", result)),
}
impl Rewrite for ast::FunctionRetTy {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
match *self {
ast::FunctionRetTy::Default(_) => Some(String::new()),
ast::FunctionRetTy::Ty(ref ty) => {
}
}
-fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
+fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
match ty.node {
- ast::TyKind::Infer => {
- let original = context.snippet(ty.span);
- original != "_"
- }
+ ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
_ => false,
}
}
impl Rewrite for ast::Arg {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- if is_named_arg(self) {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+ if let Some(ref explicit_self) = self.to_self() {
+ rewrite_explicit_self(context, explicit_self)
+ } else if is_named_arg(self) {
let mut result = self
.pat
.rewrite(context, Shape::legacy(shape.width, shape.indent))?;
- if !is_empty_infer(context, &*self.ty) {
+ if !is_empty_infer(&*self.ty, self.pat.span) {
if context.config.space_before_colon() {
result.push_str(" ");
}
}
fn rewrite_explicit_self(
+ context: &RewriteContext<'_>,
explicit_self: &ast::ExplicitSelf,
- args: &[ast::Arg],
- context: &RewriteContext,
) -> Option<String> {
match explicit_self.node {
ast::SelfKind::Region(lt, m) => {
None => Some(format!("&{}self", mut_str)),
}
}
- ast::SelfKind::Explicit(ref ty, _) => {
- assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
-
- let mutability = explicit_self_mutability(&args[0]);
+ ast::SelfKind::Explicit(ref ty, mutability) => {
let type_str = ty.rewrite(
context,
Shape::legacy(context.config.max_width(), Indent::empty()),
type_str
))
}
- ast::SelfKind::Value(_) => {
- assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
-
- let mutability = explicit_self_mutability(&args[0]);
-
- Some(format!("{}self", format_mutability(mutability)))
- }
- }
-}
-
-// Hacky solution caused by absence of `Mutability` in `SelfValue` and
-// `SelfExplicit` variants of `ast::ExplicitSelf_`.
-fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
- if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
- mutability
- } else {
- unreachable!()
+ ast::SelfKind::Value(mutability) => Some(format!("{}self", format_mutability(mutability))),
}
}
}
}
-pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
+pub fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos {
match arg.ty.node {
ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
// Return type is (result, force_new_line_for_brace)
fn rewrite_fn_base(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
indent: Indent,
ident: ast::Ident,
- fn_sig: &FnSig,
+ fn_sig: &FnSig<'_>,
span: Span,
newline_brace: bool,
has_body: bool,
let snuggle_angle_bracket = generics_str
.lines()
.last()
- .map_or(false, |l| l.trim_left().len() == 1);
+ .map_or(false, |l| l.trim_start().len() == 1);
// Note that the width and indent don't really matter, we'll re-layout the
// return type later anyway.
one_line_budget, multi_line_budget, arg_indent
);
+ result.push('(');
// Check if vertical layout was forced.
- if one_line_budget == 0 {
- if snuggle_angle_bracket {
- result.push('(');
- } else {
- result.push_str("(");
- if context.config.indent_style() == IndentStyle::Visual {
- result.push_str(&arg_indent.to_string_with_newline(context.config));
- }
- }
- } else {
- result.push('(');
+ if one_line_budget == 0
+ && !snuggle_angle_bracket
+ && context.config.indent_style() == IndentStyle::Visual
+ {
+ result.push_str(&arg_indent.to_string_with_newline(context.config));
}
// Skip `pub(crate)`.
let arg_str = rewrite_args(
context,
&fd.inputs,
- fd.get_self().as_ref(),
one_line_budget,
multi_line_budget,
indent,
arg_indent,
args_span,
- fd.variadic,
- generics_str.contains('\n'),
+ fd.c_variadic,
)?;
let put_args_in_block = match context.config.indent_style() {
} && !fd.inputs.is_empty();
let mut args_last_line_contains_comment = false;
+ let mut no_args_and_over_max_width = false;
+
if put_args_in_block {
arg_indent = indent.block_indent(context.config);
result.push_str(&arg_indent.to_string_with_newline(context.config));
let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
// Put the closing brace on the next line if it overflows the max width.
// 1 = `)`
- if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
- result.push('\n');
- }
+ let closing_paren_overflow_max_width =
+ fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
// If the last line of args contains comment, we cannot put the closing paren
// on the same line.
- if arg_str
+ args_last_line_contains_comment = arg_str
.lines()
.last()
- .map_or(false, |last_line| last_line.contains("//"))
- {
- args_last_line_contains_comment = true;
- result.push_str(&arg_indent.to_string_with_newline(context.config));
+ .map_or(false, |last_line| last_line.contains("//"));
+
+ if context.config.version() == Version::Two {
+ result.push(')');
+ if closing_paren_overflow_max_width || args_last_line_contains_comment {
+ result.push_str(&indent.to_string_with_newline(context.config));
+ no_args_and_over_max_width = true;
+ }
+ } else {
+ if closing_paren_overflow_max_width || args_last_line_contains_comment {
+ result.push_str(&indent.to_string_with_newline(context.config));
+ }
+ result.push(')');
}
- result.push(')');
}
// Return type.
// the closing parenthesis of the argument and the arrow '->' is considered.
let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
- // If there is no where clause, take into account the space after the return type
+ // If there is no where-clause, take into account the space after the return type
// and the brace.
if where_clause.predicates.is_empty() {
sig_length += 2;
} else {
// FIXME: we might want to check that using the arg indent
// doesn't blow our budget, and if it does, then fallback to
- // the where clause indent.
+ // the where-clause indent.
arg_indent
};
result.push_str(&indent.to_string_with_newline(context.config));
indent
} else {
- result.push(' ');
+ if context.config.version() == Version::Two {
+ if arg_str.len() != 0 || !no_args_and_over_max_width {
+ result.push(' ');
+ }
+ } else {
+ result.push(' ');
+ }
+
Indent::new(indent.block_indent, last_line_width(&result))
};
option,
is_args_multi_lined,
)?;
- // If there are neither where clause nor return type, we may be missing comments between
+ // If there are neither where-clause nor return type, we may be missing comments between
// args and `{`.
if where_clause_str.is_empty() {
if let ast::FunctionRetTy::Default(ret_span) = fd.output {
struct WhereClauseOption {
suppress_comma: bool, // Force no trailing comma
snuggle: bool, // Do not insert newline before `where`
- compress_where: bool, // Try single line where clause instead of vertical layout
+ compress_where: bool, // Try single line where-clause instead of vertical layout
}
impl WhereClauseOption {
}
fn rewrite_args(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
args: &[ast::Arg],
- explicit_self: Option<&ast::ExplicitSelf>,
one_line_budget: usize,
multi_line_budget: usize,
indent: Indent,
arg_indent: Indent,
span: Span,
variadic: bool,
- generics_str_contains_newline: bool,
) -> Option<String> {
- let mut arg_item_strs = args
- .iter()
- .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
- .collect::<Option<Vec<_>>>()?;
-
- // Account for sugary self.
- // FIXME: the comment for the self argument is dropped. This is blocked
- // on rust issue #27522.
- let min_args = explicit_self
- .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
- .map_or(1, |self_str| {
- arg_item_strs[0] = self_str;
- 2
- });
-
- // Comments between args.
- let mut arg_items = Vec::new();
- if min_args == 2 {
- arg_items.push(ListItem::from_str(""));
- }
-
- // FIXME(#21): if there are no args, there might still be a comment, but
- // without spans for the comment or parens, there is no chance of
- // getting it right. You also don't get to put a comment on self, unless
- // it is explicit.
- if args.len() >= min_args || variadic {
- let comment_span_start = if min_args == 2 {
- let second_arg_start = if arg_has_pattern(&args[1]) {
- args[1].pat.span.lo()
- } else {
- args[1].ty.span.lo()
- };
- let reduced_span = mk_sp(span.lo(), second_arg_start);
-
- context.snippet_provider.span_after_last(reduced_span, ",")
- } else {
- span.lo()
- };
-
- enum ArgumentKind<'a> {
- Regular(&'a ast::Arg),
- Variadic(BytePos),
- }
-
- let variadic_arg = if variadic {
- let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
- let variadic_start =
- context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
- Some(ArgumentKind::Variadic(variadic_start))
- } else {
- None
- };
-
- let more_items = itemize_list(
- context.snippet_provider,
- args[min_args - 1..]
- .iter()
- .map(ArgumentKind::Regular)
- .chain(variadic_arg),
- ")",
- ",",
- |arg| match *arg {
- ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
- ArgumentKind::Variadic(start) => start,
- },
- |arg| match *arg {
- ArgumentKind::Regular(arg) => arg.ty.span.hi(),
- ArgumentKind::Variadic(start) => start + BytePos(3),
- },
- |arg| match *arg {
- ArgumentKind::Regular(..) => None,
- ArgumentKind::Variadic(..) => Some("...".to_owned()),
- },
- comment_span_start,
- span.hi(),
- false,
- );
-
- arg_items.extend(more_items);
- }
-
- let fits_in_one_line = !generics_str_contains_newline
- && (arg_items.is_empty()
- || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
-
- for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
- item.item = Some(arg);
+ if args.len() == 0 {
+ let comment = context
+ .snippet(mk_sp(
+ span.lo(),
+ // to remove ')'
+ span.hi() - BytePos(1),
+ ))
+ .trim();
+ return Some(comment.to_owned());
}
-
- let last_line_ends_with_comment = arg_items
- .iter()
- .last()
- .and_then(|item| item.post_comment.as_ref())
- .map_or(false, |s| s.trim().starts_with("//"));
-
- let (indent, trailing_comma) = match context.config.indent_style() {
- IndentStyle::Block if fits_in_one_line => {
- (indent.block_indent(context.config), SeparatorTactic::Never)
- }
- IndentStyle::Block => (
- indent.block_indent(context.config),
- context.config.trailing_comma(),
- ),
- IndentStyle::Visual if last_line_ends_with_comment => {
- (arg_indent, context.config.trailing_comma())
- }
- IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
- };
+ let arg_items: Vec<_> = itemize_list(
+ context.snippet_provider,
+ args.iter(),
+ ")",
+ ",",
+ |arg| span_lo_for_arg(arg),
+ |arg| arg.ty.span.hi(),
+ |arg| {
+ arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
+ .or_else(|| Some(context.snippet(arg.span()).to_owned()))
+ },
+ span.lo(),
+ span.hi(),
+ false,
+ )
+ .collect();
let tactic = definitive_tactic(
&arg_items,
- context.config.fn_args_density().to_list_tactic(),
+ context
+ .config
+ .fn_args_density()
+ .to_list_tactic(arg_items.len()),
Separator::Comma,
one_line_budget,
);
DefinitiveListTactic::Horizontal => one_line_budget,
_ => multi_line_budget,
};
-
- debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
-
+ let indent = match context.config.indent_style() {
+ IndentStyle::Block => indent.block_indent(context.config),
+ IndentStyle::Visual => arg_indent,
+ };
let trailing_separator = if variadic {
SeparatorTactic::Never
} else {
- trailing_comma
+ match context.config.indent_style() {
+ IndentStyle::Block => context.config.trailing_comma(),
+ IndentStyle::Visual => SeparatorTactic::Never,
+ }
};
let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
.tactic(tactic)
write_list(&arg_items, &fmt)
}
-fn arg_has_pattern(arg: &ast::Arg) -> bool {
- if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
- ident != symbol::keywords::Invalid.ident()
- } else {
- true
- }
-}
-
fn compute_budgets_for_args(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
result: &str,
indent: Indent,
ret_str_len: usize,
}
fn rewrite_generics(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
ident: &str,
generics: &ast::Generics,
shape: Shape,
) -> Option<String> {
- // FIXME: convert bounds to where clauses where they get too big or if
- // there is a where clause at all.
+ // FIXME: convert bounds to where-clauses where they get too big or if
+ // there is a where-clause at all.
if generics.params.is_empty() {
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)
}
}
fn rewrite_where_clause_rfc_style(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
where_clause: &ast::WhereClause,
shape: Shape,
terminator: &str,
};
// shape should be vertical only and only if we have `where_single_line` option enabled
- // and the number of items of the where clause is equal to 1
+ // and the number of items of the where-clause is equal to 1
let shape_tactic = if where_single_line {
DefinitiveListTactic::Horizontal
} else {
}
fn rewrite_where_clause(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
where_clause: &ast::WhereClause,
brace_style: BraceStyle,
shape: Shape,
let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
let mut comma_tactic = context.config.trailing_comma();
- // Kind of a hack because we don't usually have trailing commas in where clauses.
+ // Kind of a hack because we don't usually have trailing commas in where-clauses.
if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
comma_tactic = SeparatorTactic::Never;
}
}
fn rewrite_comments_before_after_where(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
span_before_where: Span,
span_after_where: Span,
shape: Shape,
}
fn format_header(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
item_name: &str,
ident: ast::Ident,
vis: &ast::Visibility,
}
fn format_generics(
- context: &RewriteContext,
+ context: &RewriteContext<'_>,
generics: &ast::Generics,
brace_style: BraceStyle,
brace_pos: BracePos,
}
impl Rewrite for ast::ForeignItem {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
let attrs_str = self.attrs.rewrite(context, shape)?;
// Drop semicolon or it will be interpreted as comment.
// FIXME: this may be a faulty span from libsyntax.
span,
false,
false,
- ).map(|(s, _)| format!("{};", s)),
+ )
+ .map(|(s, _)| format!("{};", s)),
ast::ForeignItemKind::Static(ref ty, is_mutable) => {
// FIXME(#21): we're dropping potential comments in between the
// function keywords here.
}
/// Rewrite an inline mod.
-pub fn rewrite_mod(context: &RewriteContext, item: &ast::Item) -> String {
+pub fn rewrite_mod(context: &RewriteContext<'_>, item: &ast::Item) -> String {
let mut result = String::with_capacity(32);
result.push_str(&*format_visibility(context, &item.vis));
result.push_str("mod ");
}
/// Rewrite `extern crate foo;` WITHOUT attributes.
-pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
+pub fn rewrite_extern_crate(context: &RewriteContext<'_>, item: &ast::Item) -> Option<String> {
assert!(is_extern_crate(item));
let new_str = context.snippet(item.span);
Some(if contains_comment(new_str) {
})
}
-/// Returns true for `mod foo;`, false for `mod foo { .. }`.
+/// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
pub fn is_mod_decl(item: &ast::Item) -> bool {
match item.node {
ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),