use std::cmp::min;
use itertools::Itertools;
-use syntax::parse::token::DelimToken;
-use syntax::source_map::{BytePos, SourceMap, Span};
-use syntax::{ast, ptr};
+use rustc_ast::token::{DelimToken, LitKind};
+use rustc_ast::{ast, ptr};
+use rustc_span::{BytePos, Span};
use crate::chains::rewrite_chain;
use crate::closures;
use crate::comment::{
- combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
- rewrite_missing_comment, CharClasses, FindUncommented,
+ combine_strs_with_missing_comments, comment_style, contains_comment, recover_comment_removed,
+ rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented,
};
use crate::config::lists::*;
use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
use crate::lists::{
definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
- struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
+ struct_lit_tactic, write_list, ListFormatting, Separator,
};
use crate::macros::{rewrite_macro, MacroPosition};
use crate::matches::rewrite_match;
use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
-use crate::patterns::is_short_pattern;
use crate::rewrite::{Rewrite, RewriteContext};
use crate::shape::{Indent, Shape};
use crate::source_map::{LineRangeUtils, SpanUtils};
use crate::types::{rewrite_path, PathContext};
use crate::utils::{
colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
- last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
- semicolon_for_expr, unicode_str_width, wrap_str,
+ last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
+ unicode_str_width, wrap_str,
};
use crate::vertical::rewrite_with_alignment;
use crate::visitor::FmtVisitor;
shape
};
- let expr_rw = match expr.node {
+ let expr_rw = match expr.kind {
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
"",
expr_vec.iter(),
choose_separator_tactic(context, expr.span),
None,
),
- ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
+ ast::ExprKind::Lit(ref l) => {
+ if let Some(expr_rw) = rewrite_literal(context, l, shape) {
+ Some(expr_rw)
+ } else {
+ if let LitKind::StrRaw(_) = l.token.kind {
+ Some(context.snippet(l.span).trim().into())
+ } else {
+ None
+ }
+ }
+ }
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
let callee_str = callee.rewrite(context, shape)?;
| ast::ExprKind::Loop(..)
| ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape)),
+ ast::ExprKind::ConstBlock(ref anon_const) => {
+ Some(format!("const {}", anon_const.rewrite(context, shape)?))
+ }
ast::ExprKind::Block(ref block, opt_label) => {
match expr_type {
ExprType::Statement => {
ast::ExprKind::Path(ref qself, ref path) => {
rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
}
- ast::ExprKind::Assign(ref lhs, ref rhs) => {
+ ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
rewrite_assignment(context, lhs, rhs, None, shape)
}
ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
rewrite_chain(expr, context, shape)
}
- ast::ExprKind::Mac(ref mac) => {
+ ast::ExprKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
wrap_str(
context.snippet(expr.span).to_owned(),
rewrite_unary_prefix(context, "return ", &**expr, shape)
}
ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
- ast::ExprKind::AddrOf(mutability, ref expr) => {
- rewrite_expr_addrof(context, mutability, expr, shape)
+ ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
+ rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
}
ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
&**expr,
};
fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
- match lhs.node {
- ast::ExprKind::Lit(ref lit) => match lit.node {
- ast::LitKind::FloatUnsuffixed(..) => {
+ match lhs.kind {
+ ast::ExprKind::Lit(ref lit) => match lit.kind {
+ ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
context.snippet(lit.span).ends_with('.')
}
_ => false,
},
+ ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
_ => false,
}
}
fn needs_space_after_range(rhs: &ast::Expr) -> bool {
- match rhs.node {
+ match rhs.kind {
// Don't format `.. ..` into `....`, which is invalid.
//
// This check is unnecessary for `lhs`, because a range
}
// We do not format these expressions yet, but they should still
// satisfy our width restrictions.
- ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
+ // Style Guide RFC for InlineAsm variant pending
+ // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
+ ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
+ Some(context.snippet(expr.span).to_owned())
+ }
ast::ExprKind::TryBlock(ref block) => {
if let rw @ Some(_) =
rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
return None;
}
- if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
+ if !block_contains_comment(context, block) && shape.width >= 2 {
return Some(format!("{}{}{{}}", prefix, label_str));
}
label: Option<ast::Label>,
shape: Shape,
) -> Option<String> {
- if is_simple_block(block, attrs, context.source_map) {
+ if is_simple_block(context, block, attrs) {
let expr_shape = shape.offset_left(last_line_width(prefix))?;
let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
let label_str = rewrite_label(label);
let inner_attrs = attrs.map(inner_attributes);
let label_str = rewrite_label(label);
visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
+ let visitor_context = visitor.get_context();
+ context
+ .skipped_range
+ .borrow_mut()
+ .append(&mut visitor_context.skipped_range.borrow_mut());
Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
}
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
- match expr.node {
+ match expr.kind {
ast::ExprKind::Match(ref cond, _) => {
// `match `cond` {`
let cond_shape = match context.config.indent_style() {
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
label: Option<ast::Label>,
- pats: Vec<&'a ast::Pat>,
+ pat: Option<&'a ast::Pat>,
keyword: &'a str,
matcher: &'a str,
connector: &'a str,
span: Span,
}
-fn extract_pats_and_cond(expr: &ast::Expr) -> (Vec<&ast::Pat>, &ast::Expr) {
- match expr.node {
- ast::ExprKind::Let(ref pats, ref cond) => (ptr_vec_to_ref_vec(pats), cond),
- _ => (vec![], expr),
+fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
+ match expr.kind {
+ ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
+ _ => (None, expr),
}
}
// FIXME: Refactor this.
fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
- match expr.node {
+ match expr.kind {
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
- let (pats, cond) = extract_pats_and_cond(cond);
+ let (pat, cond) = extract_pats_and_cond(cond);
Some(ControlFlow::new_if(
cond,
- pats,
+ pat,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
Some(ControlFlow::new_loop(block, label, expr.span))
}
ast::ExprKind::While(ref cond, ref block, label) => {
- let (pats, cond) = extract_pats_and_cond(cond);
- Some(ControlFlow::new_while(pats, cond, block, label, expr.span))
+ let (pat, cond) = extract_pats_and_cond(cond);
+ Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
}
_ => None,
}
}
-fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
- if pats.is_empty() { "" } else { "let" }
+fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
+ pat.map_or("", |_| "let")
}
impl<'a> ControlFlow<'a> {
fn new_if(
cond: &'a ast::Expr,
- pats: Vec<&'a ast::Pat>,
+ pat: Option<&'a ast::Pat>,
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
allow_single_line: bool,
nested_if: bool,
span: Span,
) -> ControlFlow<'a> {
- let matcher = choose_matcher(&pats);
+ let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block,
label: None,
- pats,
+ pat,
keyword: "if",
matcher,
connector: " =",
block,
else_block: None,
label,
- pats: vec![],
+ pat: None,
keyword: "loop",
matcher: "",
connector: "",
}
fn new_while(
- pats: Vec<&'a ast::Pat>,
+ pat: Option<&'a ast::Pat>,
cond: &'a ast::Expr,
block: &'a ast::Block,
label: Option<ast::Label>,
span: Span,
) -> ControlFlow<'a> {
- let matcher = choose_matcher(&pats);
+ let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block: None,
label,
- pats,
+ pat,
keyword: "while",
matcher,
connector: " =",
block,
else_block: None,
label,
- pats: vec![pat],
+ pat: Some(pat),
keyword: "for",
matcher: "",
connector: " in",
let else_block = self.else_block?;
let fixed_cost = self.keyword.len() + " { } else { }".len();
- if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
- if !is_simple_block(self.block, None, context.source_map)
- || !is_simple_block(else_node, None, context.source_map)
+ if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
+ if !is_simple_block(context, self.block, None)
+ || !is_simple_block(context, else_node, None)
|| pat_expr_str.contains('\n')
{
return None;
shape: Shape,
offset: usize,
) -> Option<String> {
- debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
+ debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
let cond_shape = shape.offset_left(offset)?;
- if !self.pats.is_empty() {
+ if let Some(pat) = self.pat {
let matcher = if self.matcher.is_empty() {
self.matcher.to_owned()
} else {
let pat_shape = cond_shape
.offset_left(matcher.len())?
.sub_width(self.connector.len())?;
- let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
- let result = format!("{}{}{}", matcher, pat_string, self.connector);
+ let pat_string = pat.rewrite(context, pat_shape)?;
+ let comments_lo = context
+ .snippet_provider
+ .span_after(self.span, self.connector.trim());
+ let missing_comments = if let Some(comment) =
+ rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
+ {
+ if !self.connector.is_empty() && !comment.is_empty() {
+ if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
+ let newline = &pat_shape
+ .indent
+ .block_indent(context.config)
+ .to_string_with_newline(context.config);
+ // An extra space is added when the lhs and rhs are joined
+ // so we need to remove one space from the end to ensure
+ // the comment and rhs are aligned.
+ let mut suffix = newline.as_ref().to_string();
+ if !suffix.is_empty() {
+ suffix.truncate(suffix.len() - 1);
+ }
+ format!("{}{}{}", newline, comment, suffix)
+ } else {
+ format!(" {}", comment)
+ }
+ } else {
+ comment
+ }
+ } else {
+ "".to_owned()
+ };
+
+ let result = format!(
+ "{}{}{}{}",
+ matcher, pat_string, self.connector, missing_comments
+ );
return rewrite_assign_rhs(context, result, expr, cond_shape);
}
context
.snippet_provider
.span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
- if self.pats.is_empty() {
+ if self.pat.is_none() {
cond_span.lo()
} else if self.matcher.is_empty() {
- self.pats[0].span.lo()
+ self.pat.unwrap().span.lo()
} else {
context
.snippet_provider
if let Some(else_block) = self.else_block {
let shape = Shape::indented(shape.indent, context.config);
let mut last_in_chain = false;
- let rewrite = match else_block.node {
+ let rewrite = match else_block.kind {
// If the else expression is another if-else expression, prevent it
// from being formatted on a single line.
// Note how we're passing the original shape, as the
}
}
-pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
- let snippet = source_map.span_to_snippet(block.span).unwrap();
- contains_comment(&snippet)
+pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
+ contains_comment(context.snippet(block.span))
}
// Checks that a block contains no statements, an expression and no comments or
// FIXME: incorrectly returns false when comment is contained completely within
// the expression.
pub(crate) fn is_simple_block(
+ context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
- source_map: &SourceMap,
) -> bool {
- (block.stmts.len() == 1
+ block.stmts.len() == 1
&& stmt_is_expr(&block.stmts[0])
- && !block_contains_comment(block, source_map)
- && attrs.map_or(true, |a| a.is_empty()))
+ && !block_contains_comment(context, block)
+ && attrs.map_or(true, |a| a.is_empty())
}
/// Checks whether a block contains at most one statement or expression, and no
/// comments or attributes.
pub(crate) fn is_simple_block_stmt(
+ context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
- source_map: &SourceMap,
) -> bool {
block.stmts.len() <= 1
- && !block_contains_comment(block, source_map)
+ && !block_contains_comment(context, block)
&& attrs.map_or(true, |a| a.is_empty())
}
/// Checks whether a block contains no statements, expressions, comments, or
/// inner attributes.
pub(crate) fn is_empty_block(
+ context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
- source_map: &SourceMap,
) -> bool {
block.stmts.is_empty()
- && !block_contains_comment(block, source_map)
+ && !block_contains_comment(context, block)
&& attrs.map_or(true, |a| inner_attributes(a).is_empty())
}
pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
- match stmt.node {
+ match stmt.kind {
ast::StmtKind::Expr(..) => true,
_ => false,
}
}
}
-pub(crate) fn rewrite_multiple_patterns(
- context: &RewriteContext<'_>,
- pats: &[&ast::Pat],
- shape: Shape,
-) -> Option<String> {
- let pat_strs = pats
- .iter()
- .map(|p| p.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?;
-
- let use_mixed_layout = pats
- .iter()
- .zip(pat_strs.iter())
- .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
- let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
- let tactic = if use_mixed_layout {
- DefinitiveListTactic::Mixed
- } else {
- definitive_tactic(
- &items,
- ListTactic::HorizontalVertical,
- Separator::VerticalBar,
- shape.width,
- )
- };
- let fmt = ListFormatting::new(shape, context.config)
- .tactic(tactic)
- .separator(" |")
- .separator_place(context.config.binop_separator())
- .ends_with_newline(false);
- write_list(&items, &fmt)
-}
-
pub(crate) fn rewrite_literal(
context: &RewriteContext<'_>,
l: &ast::Lit,
shape: Shape,
) -> Option<String> {
- match l.node {
+ match l.kind {
ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
_ => wrap_str(
context.snippet(l.span).to_owned(),
.lines()
.dropping_back(1)
.all(|line| line.ends_with('\\'))
+ && context.config.version() == Version::Two
{
- let new_indent = shape.visual_indent(1).indent;
- let indented_string_lit = String::from(
- string_lit
- .lines()
- .map(|line| {
- format!(
- "{}{}",
- new_indent.to_string(context.config),
- line.trim_start()
- )
- })
- .collect::<Vec<_>>()
- .join("\n")
- .trim_start(),
- );
- return if context.config.version() == Version::Two {
- Some(indented_string_lit)
- } else {
- wrap_str(indented_string_lit, context.config.max_width(), shape)
- };
+ return Some(string_lit.to_owned());
} else {
return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
}
}
pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
- match expr.node {
+ match expr.kind {
ast::ExprKind::Lit(..) => true,
ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
- ast::ExprKind::AddrOf(_, ref expr)
+ ast::ExprKind::AddrOf(_, _, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Cast(ref expr, _)
| ast::ExprKind::Field(ref expr, _)
expr: &ast::Expr,
args_len: usize,
) -> bool {
- match expr.node {
+ match expr.kind {
_ if !expr.attrs.is_empty() => false,
ast::ExprKind::Match(..) => {
(context.use_block_indent() && args_len == 1)
context.config.overflow_delimited_expr()
|| (context.use_block_indent() && args_len == 1)
}
- ast::ExprKind::Mac(ref mac) => {
- match (mac.delim, context.config.overflow_delimited_expr()) {
- (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
+ ast::ExprKind::MacCall(ref mac) => {
+ match (
+ rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
+ context.config.overflow_delimited_expr(),
+ ) {
+ (Some(ast::MacDelimiter::Bracket), true)
+ | (Some(ast::MacDelimiter::Brace), true) => true,
_ => context.use_block_indent() && args_len == 1,
}
}
}
// Handle unary-like expressions
- ast::ExprKind::AddrOf(_, ref expr)
+ ast::ExprKind::AddrOf(_, _, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr)
}
pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
- match expr.node {
- ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
- ast::ExprKind::AddrOf(_, ref expr)
+ match expr.kind {
+ ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
+ ast::ExprKind::AddrOf(_, _, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Try(ref expr)
| ast::ExprKind::Unary(_, ref expr)
post_comment = rewrite_missing_comment(post_span, shape, context)?;
// Remove nested parens if there are no comments.
- if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
+ if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
span = subexpr.span;
subexpr = subsubexpr;
fn rewrite_expr_addrof(
context: &RewriteContext<'_>,
+ borrow_kind: ast::BorrowKind,
mutability: ast::Mutability,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
- let operator_str = match mutability {
- ast::Mutability::Immutable => "&",
- ast::Mutability::Mutable => "&mut ",
+ let operator_str = match (mutability, borrow_kind) {
+ (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
+ (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
+ (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
+ (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
};
rewrite_unary_prefix(context, operator_str, expr, shape)
}
pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
- match expr.node {
+ match expr.kind {
ast::ExprKind::MethodCall(..) => true,
- ast::ExprKind::AddrOf(_, ref expr)
+ ast::ExprKind::AddrOf(_, _, ref expr)
| ast::ExprKind::Box(ref expr)
| ast::ExprKind::Cast(ref expr, _)
| ast::ExprKind::Try(ref expr)